Unify new_symbol and new_symbol_full
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "common/hash_enum.h"
78 #include "filename-seen-cache.h"
79 #include "producer.h"
80 #include <fcntl.h>
81 #include <sys/types.h>
82 #include <algorithm>
83 #include <unordered_set>
84 #include <unordered_map>
85 #include "selftest.h"
86 #include <cmath>
87 #include <set>
88 #include <forward_list>
89
90 typedef struct symbol *symbolp;
91 DEF_VEC_P (symbolp);
92
93 /* When == 1, print basic high level tracing messages.
94    When > 1, be more verbose.
95    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
96 static unsigned int dwarf_read_debug = 0;
97
98 /* When non-zero, dump DIEs after they are read in.  */
99 static unsigned int dwarf_die_debug = 0;
100
101 /* When non-zero, dump line number entries as they are read in.  */
102 static unsigned int dwarf_line_debug = 0;
103
104 /* When non-zero, cross-check physname against demangler.  */
105 static int check_physname = 0;
106
107 /* When non-zero, do not reject deprecated .gdb_index sections.  */
108 static int use_deprecated_index_sections = 0;
109
110 static const struct objfile_data *dwarf2_objfile_data_key;
111
112 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
113
114 static int dwarf2_locexpr_index;
115 static int dwarf2_loclist_index;
116 static int dwarf2_locexpr_block_index;
117 static int dwarf2_loclist_block_index;
118
119 /* A descriptor for dwarf sections.
120
121    S.ASECTION, SIZE are typically initialized when the objfile is first
122    scanned.  BUFFER, READIN are filled in later when the section is read.
123    If the section contained compressed data then SIZE is updated to record
124    the uncompressed size of the section.
125
126    DWP file format V2 introduces a wrinkle that is easiest to handle by
127    creating the concept of virtual sections contained within a real section.
128    In DWP V2 the sections of the input DWO files are concatenated together
129    into one section, but section offsets are kept relative to the original
130    input section.
131    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
132    the real section this "virtual" section is contained in, and BUFFER,SIZE
133    describe the virtual section.  */
134
135 struct dwarf2_section_info
136 {
137   union
138   {
139     /* If this is a real section, the bfd section.  */
140     asection *section;
141     /* If this is a virtual section, pointer to the containing ("real")
142        section.  */
143     struct dwarf2_section_info *containing_section;
144   } s;
145   /* Pointer to section data, only valid if readin.  */
146   const gdb_byte *buffer;
147   /* The size of the section, real or virtual.  */
148   bfd_size_type size;
149   /* If this is a virtual section, the offset in the real section.
150      Only valid if is_virtual.  */
151   bfd_size_type virtual_offset;
152   /* True if we have tried to read this section.  */
153   char readin;
154   /* True if this is a virtual section, False otherwise.
155      This specifies which of s.section and s.containing_section to use.  */
156   char is_virtual;
157 };
158
159 typedef struct dwarf2_section_info dwarf2_section_info_def;
160 DEF_VEC_O (dwarf2_section_info_def);
161
162 /* All offsets in the index are of this type.  It must be
163    architecture-independent.  */
164 typedef uint32_t offset_type;
165
166 DEF_VEC_I (offset_type);
167
168 /* Ensure only legit values are used.  */
169 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
170   do { \
171     gdb_assert ((unsigned int) (value) <= 1); \
172     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
173   } while (0)
174
175 /* Ensure only legit values are used.  */
176 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
177   do { \
178     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
179                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
180     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
181   } while (0)
182
183 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
184 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
185   do { \
186     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
187     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
188   } while (0)
189
190 #if WORDS_BIGENDIAN
191
192 /* Convert VALUE between big- and little-endian.  */
193
194 static offset_type
195 byte_swap (offset_type value)
196 {
197   offset_type result;
198
199   result = (value & 0xff) << 24;
200   result |= (value & 0xff00) << 8;
201   result |= (value & 0xff0000) >> 8;
202   result |= (value & 0xff000000) >> 24;
203   return result;
204 }
205
206 #define MAYBE_SWAP(V)  byte_swap (V)
207
208 #else
209 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
210 #endif /* WORDS_BIGENDIAN */
211
212 /* An index into a (C++) symbol name component in a symbol name as
213    recorded in the mapped_index's symbol table.  For each C++ symbol
214    in the symbol table, we record one entry for the start of each
215    component in the symbol in a table of name components, and then
216    sort the table, in order to be able to binary search symbol names,
217    ignoring leading namespaces, both completion and regular look up.
218    For example, for symbol "A::B::C", we'll have an entry that points
219    to "A::B::C", another that points to "B::C", and another for "C".
220    Note that function symbols in GDB index have no parameter
221    information, just the function/method names.  You can convert a
222    name_component to a "const char *" using the
223    'mapped_index::symbol_name_at(offset_type)' method.  */
224
225 struct name_component
226 {
227   /* Offset in the symbol name where the component starts.  Stored as
228      a (32-bit) offset instead of a pointer to save memory and improve
229      locality on 64-bit architectures.  */
230   offset_type name_offset;
231
232   /* The symbol's index in the symbol and constant pool tables of a
233      mapped_index.  */
234   offset_type idx;
235 };
236
237 /* Base class containing bits shared by both .gdb_index and
238    .debug_name indexes.  */
239
240 struct mapped_index_base
241 {
242   /* The name_component table (a sorted vector).  See name_component's
243      description above.  */
244   std::vector<name_component> name_components;
245
246   /* How NAME_COMPONENTS is sorted.  */
247   enum case_sensitivity name_components_casing;
248
249   /* Return the number of names in the symbol table.  */
250   virtual size_t symbol_name_count () const = 0;
251
252   /* Get the name of the symbol at IDX in the symbol table.  */
253   virtual const char *symbol_name_at (offset_type idx) const = 0;
254
255   /* Return whether the name at IDX in the symbol table should be
256      ignored.  */
257   virtual bool symbol_name_slot_invalid (offset_type idx) const
258   {
259     return false;
260   }
261
262   /* Build the symbol name component sorted vector, if we haven't
263      yet.  */
264   void build_name_components ();
265
266   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
267      possible matches for LN_NO_PARAMS in the name component
268      vector.  */
269   std::pair<std::vector<name_component>::const_iterator,
270             std::vector<name_component>::const_iterator>
271     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
272
273   /* Prevent deleting/destroying via a base class pointer.  */
274 protected:
275   ~mapped_index_base() = default;
276 };
277
278 /* A description of the mapped index.  The file format is described in
279    a comment by the code that writes the index.  */
280 struct mapped_index final : public mapped_index_base
281 {
282   /* A slot/bucket in the symbol table hash.  */
283   struct symbol_table_slot
284   {
285     const offset_type name;
286     const offset_type vec;
287   };
288
289   /* Index data format version.  */
290   int version;
291
292   /* The total length of the buffer.  */
293   off_t total_size;
294
295   /* The address table data.  */
296   gdb::array_view<const gdb_byte> address_table;
297
298   /* The symbol table, implemented as a hash table.  */
299   gdb::array_view<symbol_table_slot> symbol_table;
300
301   /* A pointer to the constant pool.  */
302   const char *constant_pool;
303
304   bool symbol_name_slot_invalid (offset_type idx) const override
305   {
306     const auto &bucket = this->symbol_table[idx];
307     return bucket.name == 0 && bucket.vec;
308   }
309
310   /* Convenience method to get at the name of the symbol at IDX in the
311      symbol table.  */
312   const char *symbol_name_at (offset_type idx) const override
313   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
314
315   size_t symbol_name_count () const override
316   { return this->symbol_table.size (); }
317 };
318
319 /* A description of the mapped .debug_names.
320    Uninitialized map has CU_COUNT 0.  */
321 struct mapped_debug_names final : public mapped_index_base
322 {
323   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
324   : dwarf2_per_objfile (dwarf2_per_objfile_)
325   {}
326
327   struct dwarf2_per_objfile *dwarf2_per_objfile;
328   bfd_endian dwarf5_byte_order;
329   bool dwarf5_is_dwarf64;
330   bool augmentation_is_gdb;
331   uint8_t offset_size;
332   uint32_t cu_count = 0;
333   uint32_t tu_count, bucket_count, name_count;
334   const gdb_byte *cu_table_reordered, *tu_table_reordered;
335   const uint32_t *bucket_table_reordered, *hash_table_reordered;
336   const gdb_byte *name_table_string_offs_reordered;
337   const gdb_byte *name_table_entry_offs_reordered;
338   const gdb_byte *entry_pool;
339
340   struct index_val
341   {
342     ULONGEST dwarf_tag;
343     struct attr
344     {
345       /* Attribute name DW_IDX_*.  */
346       ULONGEST dw_idx;
347
348       /* Attribute form DW_FORM_*.  */
349       ULONGEST form;
350
351       /* Value if FORM is DW_FORM_implicit_const.  */
352       LONGEST implicit_const;
353     };
354     std::vector<attr> attr_vec;
355   };
356
357   std::unordered_map<ULONGEST, index_val> abbrev_map;
358
359   const char *namei_to_name (uint32_t namei) const;
360
361   /* Implementation of the mapped_index_base virtual interface, for
362      the name_components cache.  */
363
364   const char *symbol_name_at (offset_type idx) const override
365   { return namei_to_name (idx); }
366
367   size_t symbol_name_count () const override
368   { return this->name_count; }
369 };
370
371 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
372 DEF_VEC_P (dwarf2_per_cu_ptr);
373
374 struct tu_stats
375 {
376   int nr_uniq_abbrev_tables;
377   int nr_symtabs;
378   int nr_symtab_sharers;
379   int nr_stmt_less_type_units;
380   int nr_all_type_units_reallocs;
381 };
382
383 /* Collection of data recorded per objfile.
384    This hangs off of dwarf2_objfile_data_key.  */
385
386 struct dwarf2_per_objfile
387 {
388   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
389      dwarf2 section names, or is NULL if the standard ELF names are
390      used.  */
391   dwarf2_per_objfile (struct objfile *objfile,
392                       const dwarf2_debug_sections *names);
393
394   ~dwarf2_per_objfile ();
395
396   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
397
398   /* Free all cached compilation units.  */
399   void free_cached_comp_units ();
400 private:
401   /* This function is mapped across the sections and remembers the
402      offset and size of each of the debugging sections we are
403      interested in.  */
404   void locate_sections (bfd *abfd, asection *sectp,
405                         const dwarf2_debug_sections &names);
406
407 public:
408   dwarf2_section_info info {};
409   dwarf2_section_info abbrev {};
410   dwarf2_section_info line {};
411   dwarf2_section_info loc {};
412   dwarf2_section_info loclists {};
413   dwarf2_section_info macinfo {};
414   dwarf2_section_info macro {};
415   dwarf2_section_info str {};
416   dwarf2_section_info line_str {};
417   dwarf2_section_info ranges {};
418   dwarf2_section_info rnglists {};
419   dwarf2_section_info addr {};
420   dwarf2_section_info frame {};
421   dwarf2_section_info eh_frame {};
422   dwarf2_section_info gdb_index {};
423   dwarf2_section_info debug_names {};
424   dwarf2_section_info debug_aranges {};
425
426   VEC (dwarf2_section_info_def) *types = NULL;
427
428   /* Back link.  */
429   struct objfile *objfile = NULL;
430
431   /* Table of all the compilation units.  This is used to locate
432      the target compilation unit of a particular reference.  */
433   struct dwarf2_per_cu_data **all_comp_units = NULL;
434
435   /* The number of compilation units in ALL_COMP_UNITS.  */
436   int n_comp_units = 0;
437
438   /* The number of .debug_types-related CUs.  */
439   int n_type_units = 0;
440
441   /* The number of elements allocated in all_type_units.
442      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
443   int n_allocated_type_units = 0;
444
445   /* The .debug_types-related CUs (TUs).
446      This is stored in malloc space because we may realloc it.  */
447   struct signatured_type **all_type_units = NULL;
448
449   /* Table of struct type_unit_group objects.
450      The hash key is the DW_AT_stmt_list value.  */
451   htab_t type_unit_groups {};
452
453   /* A table mapping .debug_types signatures to its signatured_type entry.
454      This is NULL if the .debug_types section hasn't been read in yet.  */
455   htab_t signatured_types {};
456
457   /* Type unit statistics, to see how well the scaling improvements
458      are doing.  */
459   struct tu_stats tu_stats {};
460
461   /* A chain of compilation units that are currently read in, so that
462      they can be freed later.  */
463   dwarf2_per_cu_data *read_in_chain = NULL;
464
465   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
466      This is NULL if the table hasn't been allocated yet.  */
467   htab_t dwo_files {};
468
469   /* True if we've checked for whether there is a DWP file.  */
470   bool dwp_checked = false;
471
472   /* The DWP file if there is one, or NULL.  */
473   struct dwp_file *dwp_file = NULL;
474
475   /* The shared '.dwz' file, if one exists.  This is used when the
476      original data was compressed using 'dwz -m'.  */
477   struct dwz_file *dwz_file = NULL;
478
479   /* A flag indicating whether this objfile has a section loaded at a
480      VMA of 0.  */
481   bool has_section_at_zero = false;
482
483   /* True if we are using the mapped index,
484      or we are faking it for OBJF_READNOW's sake.  */
485   bool using_index = false;
486
487   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
488   mapped_index *index_table = NULL;
489
490   /* The mapped index, or NULL if .debug_names is missing or not being used.  */
491   std::unique_ptr<mapped_debug_names> debug_names_table;
492
493   /* When using index_table, this keeps track of all quick_file_names entries.
494      TUs typically share line table entries with a CU, so we maintain a
495      separate table of all line table entries to support the sharing.
496      Note that while there can be way more TUs than CUs, we've already
497      sorted all the TUs into "type unit groups", grouped by their
498      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
499      CU and its associated TU group if there is one.  */
500   htab_t quick_file_names_table {};
501
502   /* Set during partial symbol reading, to prevent queueing of full
503      symbols.  */
504   bool reading_partial_symbols = false;
505
506   /* Table mapping type DIEs to their struct type *.
507      This is NULL if not allocated yet.
508      The mapping is done via (CU/TU + DIE offset) -> type.  */
509   htab_t die_type_hash {};
510
511   /* The CUs we recently read.  */
512   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
513
514   /* Table containing line_header indexed by offset and offset_in_dwz.  */
515   htab_t line_header_hash {};
516
517   /* Table containing all filenames.  This is an optional because the
518      table is lazily constructed on first access.  */
519   gdb::optional<filename_seen_cache> filenames_cache;
520 };
521
522 /* Get the dwarf2_per_objfile associated to OBJFILE.  */
523
524 struct dwarf2_per_objfile *
525 get_dwarf2_per_objfile (struct objfile *objfile)
526 {
527   return ((struct dwarf2_per_objfile *)
528           objfile_data (objfile, dwarf2_objfile_data_key));
529 }
530
531 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
532
533 void
534 set_dwarf2_per_objfile (struct objfile *objfile,
535                         struct dwarf2_per_objfile *dwarf2_per_objfile)
536 {
537   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
538   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
539 }
540
541 /* Default names of the debugging sections.  */
542
543 /* Note that if the debugging section has been compressed, it might
544    have a name like .zdebug_info.  */
545
546 static const struct dwarf2_debug_sections dwarf2_elf_names =
547 {
548   { ".debug_info", ".zdebug_info" },
549   { ".debug_abbrev", ".zdebug_abbrev" },
550   { ".debug_line", ".zdebug_line" },
551   { ".debug_loc", ".zdebug_loc" },
552   { ".debug_loclists", ".zdebug_loclists" },
553   { ".debug_macinfo", ".zdebug_macinfo" },
554   { ".debug_macro", ".zdebug_macro" },
555   { ".debug_str", ".zdebug_str" },
556   { ".debug_line_str", ".zdebug_line_str" },
557   { ".debug_ranges", ".zdebug_ranges" },
558   { ".debug_rnglists", ".zdebug_rnglists" },
559   { ".debug_types", ".zdebug_types" },
560   { ".debug_addr", ".zdebug_addr" },
561   { ".debug_frame", ".zdebug_frame" },
562   { ".eh_frame", NULL },
563   { ".gdb_index", ".zgdb_index" },
564   { ".debug_names", ".zdebug_names" },
565   { ".debug_aranges", ".zdebug_aranges" },
566   23
567 };
568
569 /* List of DWO/DWP sections.  */
570
571 static const struct dwop_section_names
572 {
573   struct dwarf2_section_names abbrev_dwo;
574   struct dwarf2_section_names info_dwo;
575   struct dwarf2_section_names line_dwo;
576   struct dwarf2_section_names loc_dwo;
577   struct dwarf2_section_names loclists_dwo;
578   struct dwarf2_section_names macinfo_dwo;
579   struct dwarf2_section_names macro_dwo;
580   struct dwarf2_section_names str_dwo;
581   struct dwarf2_section_names str_offsets_dwo;
582   struct dwarf2_section_names types_dwo;
583   struct dwarf2_section_names cu_index;
584   struct dwarf2_section_names tu_index;
585 }
586 dwop_section_names =
587 {
588   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
589   { ".debug_info.dwo", ".zdebug_info.dwo" },
590   { ".debug_line.dwo", ".zdebug_line.dwo" },
591   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
592   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
593   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
594   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
595   { ".debug_str.dwo", ".zdebug_str.dwo" },
596   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
597   { ".debug_types.dwo", ".zdebug_types.dwo" },
598   { ".debug_cu_index", ".zdebug_cu_index" },
599   { ".debug_tu_index", ".zdebug_tu_index" },
600 };
601
602 /* local data types */
603
604 /* The data in a compilation unit header, after target2host
605    translation, looks like this.  */
606 struct comp_unit_head
607 {
608   unsigned int length;
609   short version;
610   unsigned char addr_size;
611   unsigned char signed_addr_p;
612   sect_offset abbrev_sect_off;
613
614   /* Size of file offsets; either 4 or 8.  */
615   unsigned int offset_size;
616
617   /* Size of the length field; either 4 or 12.  */
618   unsigned int initial_length_size;
619
620   enum dwarf_unit_type unit_type;
621
622   /* Offset to the first byte of this compilation unit header in the
623      .debug_info section, for resolving relative reference dies.  */
624   sect_offset sect_off;
625
626   /* Offset to first die in this cu from the start of the cu.
627      This will be the first byte following the compilation unit header.  */
628   cu_offset first_die_cu_offset;
629
630   /* 64-bit signature of this type unit - it is valid only for
631      UNIT_TYPE DW_UT_type.  */
632   ULONGEST signature;
633
634   /* For types, offset in the type's DIE of the type defined by this TU.  */
635   cu_offset type_cu_offset_in_tu;
636 };
637
638 /* Type used for delaying computation of method physnames.
639    See comments for compute_delayed_physnames.  */
640 struct delayed_method_info
641 {
642   /* The type to which the method is attached, i.e., its parent class.  */
643   struct type *type;
644
645   /* The index of the method in the type's function fieldlists.  */
646   int fnfield_index;
647
648   /* The index of the method in the fieldlist.  */
649   int index;
650
651   /* The name of the DIE.  */
652   const char *name;
653
654   /*  The DIE associated with this method.  */
655   struct die_info *die;
656 };
657
658 typedef struct delayed_method_info delayed_method_info;
659 DEF_VEC_O (delayed_method_info);
660
661 /* Internal state when decoding a particular compilation unit.  */
662 struct dwarf2_cu
663 {
664   /* The header of the compilation unit.  */
665   struct comp_unit_head header;
666
667   /* Base address of this compilation unit.  */
668   CORE_ADDR base_address;
669
670   /* Non-zero if base_address has been set.  */
671   int base_known;
672
673   /* The language we are debugging.  */
674   enum language language;
675   const struct language_defn *language_defn;
676
677   const char *producer;
678
679   /* The generic symbol table building routines have separate lists for
680      file scope symbols and all all other scopes (local scopes).  So
681      we need to select the right one to pass to add_symbol_to_list().
682      We do it by keeping a pointer to the correct list in list_in_scope.
683
684      FIXME: The original dwarf code just treated the file scope as the
685      first local scope, and all other local scopes as nested local
686      scopes, and worked fine.  Check to see if we really need to
687      distinguish these in buildsym.c.  */
688   struct pending **list_in_scope;
689
690   /* The abbrev table for this CU.
691      Normally this points to the abbrev table in the objfile.
692      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
693   struct abbrev_table *abbrev_table;
694
695   /* Hash table holding all the loaded partial DIEs
696      with partial_die->offset.SECT_OFF as hash.  */
697   htab_t partial_dies;
698
699   /* Storage for things with the same lifetime as this read-in compilation
700      unit, including partial DIEs.  */
701   struct obstack comp_unit_obstack;
702
703   /* When multiple dwarf2_cu structures are living in memory, this field
704      chains them all together, so that they can be released efficiently.
705      We will probably also want a generation counter so that most-recently-used
706      compilation units are cached...  */
707   struct dwarf2_per_cu_data *read_in_chain;
708
709   /* Backlink to our per_cu entry.  */
710   struct dwarf2_per_cu_data *per_cu;
711
712   /* How many compilation units ago was this CU last referenced?  */
713   int last_used;
714
715   /* A hash table of DIE cu_offset for following references with
716      die_info->offset.sect_off as hash.  */
717   htab_t die_hash;
718
719   /* Full DIEs if read in.  */
720   struct die_info *dies;
721
722   /* A set of pointers to dwarf2_per_cu_data objects for compilation
723      units referenced by this one.  Only set during full symbol processing;
724      partial symbol tables do not have dependencies.  */
725   htab_t dependencies;
726
727   /* Header data from the line table, during full symbol processing.  */
728   struct line_header *line_header;
729   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
730      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
731      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
732      to the line header as long as this DIE is being processed.  See
733      process_die_scope.  */
734   die_info *line_header_die_owner;
735
736   /* A list of methods which need to have physnames computed
737      after all type information has been read.  */
738   VEC (delayed_method_info) *method_list;
739
740   /* To be copied to symtab->call_site_htab.  */
741   htab_t call_site_htab;
742
743   /* Non-NULL if this CU came from a DWO file.
744      There is an invariant here that is important to remember:
745      Except for attributes copied from the top level DIE in the "main"
746      (or "stub") file in preparation for reading the DWO file
747      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
748      Either there isn't a DWO file (in which case this is NULL and the point
749      is moot), or there is and either we're not going to read it (in which
750      case this is NULL) or there is and we are reading it (in which case this
751      is non-NULL).  */
752   struct dwo_unit *dwo_unit;
753
754   /* The DW_AT_addr_base attribute if present, zero otherwise
755      (zero is a valid value though).
756      Note this value comes from the Fission stub CU/TU's DIE.  */
757   ULONGEST addr_base;
758
759   /* The DW_AT_ranges_base attribute if present, zero otherwise
760      (zero is a valid value though).
761      Note this value comes from the Fission stub CU/TU's DIE.
762      Also note that the value is zero in the non-DWO case so this value can
763      be used without needing to know whether DWO files are in use or not.
764      N.B. This does not apply to DW_AT_ranges appearing in
765      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
766      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
767      DW_AT_ranges_base *would* have to be applied, and we'd have to care
768      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
769   ULONGEST ranges_base;
770
771   /* Mark used when releasing cached dies.  */
772   unsigned int mark : 1;
773
774   /* This CU references .debug_loc.  See the symtab->locations_valid field.
775      This test is imperfect as there may exist optimized debug code not using
776      any location list and still facing inlining issues if handled as
777      unoptimized code.  For a future better test see GCC PR other/32998.  */
778   unsigned int has_loclist : 1;
779
780   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
781      if all the producer_is_* fields are valid.  This information is cached
782      because profiling CU expansion showed excessive time spent in
783      producer_is_gxx_lt_4_6.  */
784   unsigned int checked_producer : 1;
785   unsigned int producer_is_gxx_lt_4_6 : 1;
786   unsigned int producer_is_gcc_lt_4_3 : 1;
787   unsigned int producer_is_icc_lt_14 : 1;
788
789   /* When set, the file that we're processing is known to have
790      debugging info for C++ namespaces.  GCC 3.3.x did not produce
791      this information, but later versions do.  */
792
793   unsigned int processing_has_namespace_info : 1;
794 };
795
796 /* Persistent data held for a compilation unit, even when not
797    processing it.  We put a pointer to this structure in the
798    read_symtab_private field of the psymtab.  */
799
800 struct dwarf2_per_cu_data
801 {
802   /* The start offset and length of this compilation unit.
803      NOTE: Unlike comp_unit_head.length, this length includes
804      initial_length_size.
805      If the DIE refers to a DWO file, this is always of the original die,
806      not the DWO file.  */
807   sect_offset sect_off;
808   unsigned int length;
809
810   /* DWARF standard version this data has been read from (such as 4 or 5).  */
811   short dwarf_version;
812
813   /* Flag indicating this compilation unit will be read in before
814      any of the current compilation units are processed.  */
815   unsigned int queued : 1;
816
817   /* This flag will be set when reading partial DIEs if we need to load
818      absolutely all DIEs for this compilation unit, instead of just the ones
819      we think are interesting.  It gets set if we look for a DIE in the
820      hash table and don't find it.  */
821   unsigned int load_all_dies : 1;
822
823   /* Non-zero if this CU is from .debug_types.
824      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
825      this is non-zero.  */
826   unsigned int is_debug_types : 1;
827
828   /* Non-zero if this CU is from the .dwz file.  */
829   unsigned int is_dwz : 1;
830
831   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
832      This flag is only valid if is_debug_types is true.
833      We can't read a CU directly from a DWO file: There are required
834      attributes in the stub.  */
835   unsigned int reading_dwo_directly : 1;
836
837   /* Non-zero if the TU has been read.
838      This is used to assist the "Stay in DWO Optimization" for Fission:
839      When reading a DWO, it's faster to read TUs from the DWO instead of
840      fetching them from random other DWOs (due to comdat folding).
841      If the TU has already been read, the optimization is unnecessary
842      (and unwise - we don't want to change where gdb thinks the TU lives
843      "midflight").
844      This flag is only valid if is_debug_types is true.  */
845   unsigned int tu_read : 1;
846
847   /* The section this CU/TU lives in.
848      If the DIE refers to a DWO file, this is always the original die,
849      not the DWO file.  */
850   struct dwarf2_section_info *section;
851
852   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
853      of the CU cache it gets reset to NULL again.  This is left as NULL for
854      dummy CUs (a CU header, but nothing else).  */
855   struct dwarf2_cu *cu;
856
857   /* The corresponding dwarf2_per_objfile.  */
858   struct dwarf2_per_objfile *dwarf2_per_objfile;
859
860   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
861      is active.  Otherwise, the 'psymtab' field is active.  */
862   union
863   {
864     /* The partial symbol table associated with this compilation unit,
865        or NULL for unread partial units.  */
866     struct partial_symtab *psymtab;
867
868     /* Data needed by the "quick" functions.  */
869     struct dwarf2_per_cu_quick_data *quick;
870   } v;
871
872   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
873      while reading psymtabs, used to compute the psymtab dependencies,
874      and then cleared.  Then it is filled in again while reading full
875      symbols, and only deleted when the objfile is destroyed.
876
877      This is also used to work around a difference between the way gold
878      generates .gdb_index version <=7 and the way gdb does.  Arguably this
879      is a gold bug.  For symbols coming from TUs, gold records in the index
880      the CU that includes the TU instead of the TU itself.  This breaks
881      dw2_lookup_symbol: It assumes that if the index says symbol X lives
882      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
883      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
884      we need to look in TU Z to find X.  Fortunately, this is akin to
885      DW_TAG_imported_unit, so we just use the same mechanism: For
886      .gdb_index version <=7 this also records the TUs that the CU referred
887      to.  Concurrently with this change gdb was modified to emit version 8
888      indices so we only pay a price for gold generated indices.
889      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
890   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
891 };
892
893 /* Entry in the signatured_types hash table.  */
894
895 struct signatured_type
896 {
897   /* The "per_cu" object of this type.
898      This struct is used iff per_cu.is_debug_types.
899      N.B.: This is the first member so that it's easy to convert pointers
900      between them.  */
901   struct dwarf2_per_cu_data per_cu;
902
903   /* The type's signature.  */
904   ULONGEST signature;
905
906   /* Offset in the TU of the type's DIE, as read from the TU header.
907      If this TU is a DWO stub and the definition lives in a DWO file
908      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
909   cu_offset type_offset_in_tu;
910
911   /* Offset in the section of the type's DIE.
912      If the definition lives in a DWO file, this is the offset in the
913      .debug_types.dwo section.
914      The value is zero until the actual value is known.
915      Zero is otherwise not a valid section offset.  */
916   sect_offset type_offset_in_section;
917
918   /* Type units are grouped by their DW_AT_stmt_list entry so that they
919      can share them.  This points to the containing symtab.  */
920   struct type_unit_group *type_unit_group;
921
922   /* The type.
923      The first time we encounter this type we fully read it in and install it
924      in the symbol tables.  Subsequent times we only need the type.  */
925   struct type *type;
926
927   /* Containing DWO unit.
928      This field is valid iff per_cu.reading_dwo_directly.  */
929   struct dwo_unit *dwo_unit;
930 };
931
932 typedef struct signatured_type *sig_type_ptr;
933 DEF_VEC_P (sig_type_ptr);
934
935 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
936    This includes type_unit_group and quick_file_names.  */
937
938 struct stmt_list_hash
939 {
940   /* The DWO unit this table is from or NULL if there is none.  */
941   struct dwo_unit *dwo_unit;
942
943   /* Offset in .debug_line or .debug_line.dwo.  */
944   sect_offset line_sect_off;
945 };
946
947 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
948    an object of this type.  */
949
950 struct type_unit_group
951 {
952   /* dwarf2read.c's main "handle" on a TU symtab.
953      To simplify things we create an artificial CU that "includes" all the
954      type units using this stmt_list so that the rest of the code still has
955      a "per_cu" handle on the symtab.
956      This PER_CU is recognized by having no section.  */
957 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
958   struct dwarf2_per_cu_data per_cu;
959
960   /* The TUs that share this DW_AT_stmt_list entry.
961      This is added to while parsing type units to build partial symtabs,
962      and is deleted afterwards and not used again.  */
963   VEC (sig_type_ptr) *tus;
964
965   /* The compunit symtab.
966      Type units in a group needn't all be defined in the same source file,
967      so we create an essentially anonymous symtab as the compunit symtab.  */
968   struct compunit_symtab *compunit_symtab;
969
970   /* The data used to construct the hash key.  */
971   struct stmt_list_hash hash;
972
973   /* The number of symtabs from the line header.
974      The value here must match line_header.num_file_names.  */
975   unsigned int num_symtabs;
976
977   /* The symbol tables for this TU (obtained from the files listed in
978      DW_AT_stmt_list).
979      WARNING: The order of entries here must match the order of entries
980      in the line header.  After the first TU using this type_unit_group, the
981      line header for the subsequent TUs is recreated from this.  This is done
982      because we need to use the same symtabs for each TU using the same
983      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
984      there's no guarantee the line header doesn't have duplicate entries.  */
985   struct symtab **symtabs;
986 };
987
988 /* These sections are what may appear in a (real or virtual) DWO file.  */
989
990 struct dwo_sections
991 {
992   struct dwarf2_section_info abbrev;
993   struct dwarf2_section_info line;
994   struct dwarf2_section_info loc;
995   struct dwarf2_section_info loclists;
996   struct dwarf2_section_info macinfo;
997   struct dwarf2_section_info macro;
998   struct dwarf2_section_info str;
999   struct dwarf2_section_info str_offsets;
1000   /* In the case of a virtual DWO file, these two are unused.  */
1001   struct dwarf2_section_info info;
1002   VEC (dwarf2_section_info_def) *types;
1003 };
1004
1005 /* CUs/TUs in DWP/DWO files.  */
1006
1007 struct dwo_unit
1008 {
1009   /* Backlink to the containing struct dwo_file.  */
1010   struct dwo_file *dwo_file;
1011
1012   /* The "id" that distinguishes this CU/TU.
1013      .debug_info calls this "dwo_id", .debug_types calls this "signature".
1014      Since signatures came first, we stick with it for consistency.  */
1015   ULONGEST signature;
1016
1017   /* The section this CU/TU lives in, in the DWO file.  */
1018   struct dwarf2_section_info *section;
1019
1020   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
1021   sect_offset sect_off;
1022   unsigned int length;
1023
1024   /* For types, offset in the type's DIE of the type defined by this TU.  */
1025   cu_offset type_offset_in_tu;
1026 };
1027
1028 /* include/dwarf2.h defines the DWP section codes.
1029    It defines a max value but it doesn't define a min value, which we
1030    use for error checking, so provide one.  */
1031
1032 enum dwp_v2_section_ids
1033 {
1034   DW_SECT_MIN = 1
1035 };
1036
1037 /* Data for one DWO file.
1038
1039    This includes virtual DWO files (a virtual DWO file is a DWO file as it
1040    appears in a DWP file).  DWP files don't really have DWO files per se -
1041    comdat folding of types "loses" the DWO file they came from, and from
1042    a high level view DWP files appear to contain a mass of random types.
1043    However, to maintain consistency with the non-DWP case we pretend DWP
1044    files contain virtual DWO files, and we assign each TU with one virtual
1045    DWO file (generally based on the line and abbrev section offsets -
1046    a heuristic that seems to work in practice).  */
1047
1048 struct dwo_file
1049 {
1050   /* The DW_AT_GNU_dwo_name attribute.
1051      For virtual DWO files the name is constructed from the section offsets
1052      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
1053      from related CU+TUs.  */
1054   const char *dwo_name;
1055
1056   /* The DW_AT_comp_dir attribute.  */
1057   const char *comp_dir;
1058
1059   /* The bfd, when the file is open.  Otherwise this is NULL.
1060      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
1061   bfd *dbfd;
1062
1063   /* The sections that make up this DWO file.
1064      Remember that for virtual DWO files in DWP V2, these are virtual
1065      sections (for lack of a better name).  */
1066   struct dwo_sections sections;
1067
1068   /* The CUs in the file.
1069      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
1070      an extension to handle LLVM's Link Time Optimization output (where
1071      multiple source files may be compiled into a single object/dwo pair). */
1072   htab_t cus;
1073
1074   /* Table of TUs in the file.
1075      Each element is a struct dwo_unit.  */
1076   htab_t tus;
1077 };
1078
1079 /* These sections are what may appear in a DWP file.  */
1080
1081 struct dwp_sections
1082 {
1083   /* These are used by both DWP version 1 and 2.  */
1084   struct dwarf2_section_info str;
1085   struct dwarf2_section_info cu_index;
1086   struct dwarf2_section_info tu_index;
1087
1088   /* These are only used by DWP version 2 files.
1089      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
1090      sections are referenced by section number, and are not recorded here.
1091      In DWP version 2 there is at most one copy of all these sections, each
1092      section being (effectively) comprised of the concatenation of all of the
1093      individual sections that exist in the version 1 format.
1094      To keep the code simple we treat each of these concatenated pieces as a
1095      section itself (a virtual section?).  */
1096   struct dwarf2_section_info abbrev;
1097   struct dwarf2_section_info info;
1098   struct dwarf2_section_info line;
1099   struct dwarf2_section_info loc;
1100   struct dwarf2_section_info macinfo;
1101   struct dwarf2_section_info macro;
1102   struct dwarf2_section_info str_offsets;
1103   struct dwarf2_section_info types;
1104 };
1105
1106 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1107    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1108
1109 struct virtual_v1_dwo_sections
1110 {
1111   struct dwarf2_section_info abbrev;
1112   struct dwarf2_section_info line;
1113   struct dwarf2_section_info loc;
1114   struct dwarf2_section_info macinfo;
1115   struct dwarf2_section_info macro;
1116   struct dwarf2_section_info str_offsets;
1117   /* Each DWP hash table entry records one CU or one TU.
1118      That is recorded here, and copied to dwo_unit.section.  */
1119   struct dwarf2_section_info info_or_types;
1120 };
1121
1122 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1123    In version 2, the sections of the DWO files are concatenated together
1124    and stored in one section of that name.  Thus each ELF section contains
1125    several "virtual" sections.  */
1126
1127 struct virtual_v2_dwo_sections
1128 {
1129   bfd_size_type abbrev_offset;
1130   bfd_size_type abbrev_size;
1131
1132   bfd_size_type line_offset;
1133   bfd_size_type line_size;
1134
1135   bfd_size_type loc_offset;
1136   bfd_size_type loc_size;
1137
1138   bfd_size_type macinfo_offset;
1139   bfd_size_type macinfo_size;
1140
1141   bfd_size_type macro_offset;
1142   bfd_size_type macro_size;
1143
1144   bfd_size_type str_offsets_offset;
1145   bfd_size_type str_offsets_size;
1146
1147   /* Each DWP hash table entry records one CU or one TU.
1148      That is recorded here, and copied to dwo_unit.section.  */
1149   bfd_size_type info_or_types_offset;
1150   bfd_size_type info_or_types_size;
1151 };
1152
1153 /* Contents of DWP hash tables.  */
1154
1155 struct dwp_hash_table
1156 {
1157   uint32_t version, nr_columns;
1158   uint32_t nr_units, nr_slots;
1159   const gdb_byte *hash_table, *unit_table;
1160   union
1161   {
1162     struct
1163     {
1164       const gdb_byte *indices;
1165     } v1;
1166     struct
1167     {
1168       /* This is indexed by column number and gives the id of the section
1169          in that column.  */
1170 #define MAX_NR_V2_DWO_SECTIONS \
1171   (1 /* .debug_info or .debug_types */ \
1172    + 1 /* .debug_abbrev */ \
1173    + 1 /* .debug_line */ \
1174    + 1 /* .debug_loc */ \
1175    + 1 /* .debug_str_offsets */ \
1176    + 1 /* .debug_macro or .debug_macinfo */)
1177       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1178       const gdb_byte *offsets;
1179       const gdb_byte *sizes;
1180     } v2;
1181   } section_pool;
1182 };
1183
1184 /* Data for one DWP file.  */
1185
1186 struct dwp_file
1187 {
1188   /* Name of the file.  */
1189   const char *name;
1190
1191   /* File format version.  */
1192   int version;
1193
1194   /* The bfd.  */
1195   bfd *dbfd;
1196
1197   /* Section info for this file.  */
1198   struct dwp_sections sections;
1199
1200   /* Table of CUs in the file.  */
1201   const struct dwp_hash_table *cus;
1202
1203   /* Table of TUs in the file.  */
1204   const struct dwp_hash_table *tus;
1205
1206   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1207   htab_t loaded_cus;
1208   htab_t loaded_tus;
1209
1210   /* Table to map ELF section numbers to their sections.
1211      This is only needed for the DWP V1 file format.  */
1212   unsigned int num_sections;
1213   asection **elf_sections;
1214 };
1215
1216 /* This represents a '.dwz' file.  */
1217
1218 struct dwz_file
1219 {
1220   /* A dwz file can only contain a few sections.  */
1221   struct dwarf2_section_info abbrev;
1222   struct dwarf2_section_info info;
1223   struct dwarf2_section_info str;
1224   struct dwarf2_section_info line;
1225   struct dwarf2_section_info macro;
1226   struct dwarf2_section_info gdb_index;
1227   struct dwarf2_section_info debug_names;
1228
1229   /* The dwz's BFD.  */
1230   bfd *dwz_bfd;
1231 };
1232
1233 /* Struct used to pass misc. parameters to read_die_and_children, et
1234    al.  which are used for both .debug_info and .debug_types dies.
1235    All parameters here are unchanging for the life of the call.  This
1236    struct exists to abstract away the constant parameters of die reading.  */
1237
1238 struct die_reader_specs
1239 {
1240   /* The bfd of die_section.  */
1241   bfd* abfd;
1242
1243   /* The CU of the DIE we are parsing.  */
1244   struct dwarf2_cu *cu;
1245
1246   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1247   struct dwo_file *dwo_file;
1248
1249   /* The section the die comes from.
1250      This is either .debug_info or .debug_types, or the .dwo variants.  */
1251   struct dwarf2_section_info *die_section;
1252
1253   /* die_section->buffer.  */
1254   const gdb_byte *buffer;
1255
1256   /* The end of the buffer.  */
1257   const gdb_byte *buffer_end;
1258
1259   /* The value of the DW_AT_comp_dir attribute.  */
1260   const char *comp_dir;
1261 };
1262
1263 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1264 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1265                                       const gdb_byte *info_ptr,
1266                                       struct die_info *comp_unit_die,
1267                                       int has_children,
1268                                       void *data);
1269
1270 /* A 1-based directory index.  This is a strong typedef to prevent
1271    accidentally using a directory index as a 0-based index into an
1272    array/vector.  */
1273 enum class dir_index : unsigned int {};
1274
1275 /* Likewise, a 1-based file name index.  */
1276 enum class file_name_index : unsigned int {};
1277
1278 struct file_entry
1279 {
1280   file_entry () = default;
1281
1282   file_entry (const char *name_, dir_index d_index_,
1283               unsigned int mod_time_, unsigned int length_)
1284     : name (name_),
1285       d_index (d_index_),
1286       mod_time (mod_time_),
1287       length (length_)
1288   {}
1289
1290   /* Return the include directory at D_INDEX stored in LH.  Returns
1291      NULL if D_INDEX is out of bounds.  */
1292   const char *include_dir (const line_header *lh) const;
1293
1294   /* The file name.  Note this is an observing pointer.  The memory is
1295      owned by debug_line_buffer.  */
1296   const char *name {};
1297
1298   /* The directory index (1-based).  */
1299   dir_index d_index {};
1300
1301   unsigned int mod_time {};
1302
1303   unsigned int length {};
1304
1305   /* True if referenced by the Line Number Program.  */
1306   bool included_p {};
1307
1308   /* The associated symbol table, if any.  */
1309   struct symtab *symtab {};
1310 };
1311
1312 /* The line number information for a compilation unit (found in the
1313    .debug_line section) begins with a "statement program header",
1314    which contains the following information.  */
1315 struct line_header
1316 {
1317   line_header ()
1318     : offset_in_dwz {}
1319   {}
1320
1321   /* Add an entry to the include directory table.  */
1322   void add_include_dir (const char *include_dir);
1323
1324   /* Add an entry to the file name table.  */
1325   void add_file_name (const char *name, dir_index d_index,
1326                       unsigned int mod_time, unsigned int length);
1327
1328   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1329      is out of bounds.  */
1330   const char *include_dir_at (dir_index index) const
1331   {
1332     /* Convert directory index number (1-based) to vector index
1333        (0-based).  */
1334     size_t vec_index = to_underlying (index) - 1;
1335
1336     if (vec_index >= include_dirs.size ())
1337       return NULL;
1338     return include_dirs[vec_index];
1339   }
1340
1341   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1342      is out of bounds.  */
1343   file_entry *file_name_at (file_name_index index)
1344   {
1345     /* Convert file name index number (1-based) to vector index
1346        (0-based).  */
1347     size_t vec_index = to_underlying (index) - 1;
1348
1349     if (vec_index >= file_names.size ())
1350       return NULL;
1351     return &file_names[vec_index];
1352   }
1353
1354   /* Const version of the above.  */
1355   const file_entry *file_name_at (unsigned int index) const
1356   {
1357     if (index >= file_names.size ())
1358       return NULL;
1359     return &file_names[index];
1360   }
1361
1362   /* Offset of line number information in .debug_line section.  */
1363   sect_offset sect_off {};
1364
1365   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1366   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1367
1368   unsigned int total_length {};
1369   unsigned short version {};
1370   unsigned int header_length {};
1371   unsigned char minimum_instruction_length {};
1372   unsigned char maximum_ops_per_instruction {};
1373   unsigned char default_is_stmt {};
1374   int line_base {};
1375   unsigned char line_range {};
1376   unsigned char opcode_base {};
1377
1378   /* standard_opcode_lengths[i] is the number of operands for the
1379      standard opcode whose value is i.  This means that
1380      standard_opcode_lengths[0] is unused, and the last meaningful
1381      element is standard_opcode_lengths[opcode_base - 1].  */
1382   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1383
1384   /* The include_directories table.  Note these are observing
1385      pointers.  The memory is owned by debug_line_buffer.  */
1386   std::vector<const char *> include_dirs;
1387
1388   /* The file_names table.  */
1389   std::vector<file_entry> file_names;
1390
1391   /* The start and end of the statement program following this
1392      header.  These point into dwarf2_per_objfile->line_buffer.  */
1393   const gdb_byte *statement_program_start {}, *statement_program_end {};
1394 };
1395
1396 typedef std::unique_ptr<line_header> line_header_up;
1397
1398 const char *
1399 file_entry::include_dir (const line_header *lh) const
1400 {
1401   return lh->include_dir_at (d_index);
1402 }
1403
1404 /* When we construct a partial symbol table entry we only
1405    need this much information.  */
1406 struct partial_die_info
1407   {
1408     /* Offset of this DIE.  */
1409     sect_offset sect_off;
1410
1411     /* DWARF-2 tag for this DIE.  */
1412     ENUM_BITFIELD(dwarf_tag) tag : 16;
1413
1414     /* Assorted flags describing the data found in this DIE.  */
1415     unsigned int has_children : 1;
1416     unsigned int is_external : 1;
1417     unsigned int is_declaration : 1;
1418     unsigned int has_type : 1;
1419     unsigned int has_specification : 1;
1420     unsigned int has_pc_info : 1;
1421     unsigned int may_be_inlined : 1;
1422
1423     /* This DIE has been marked DW_AT_main_subprogram.  */
1424     unsigned int main_subprogram : 1;
1425
1426     /* Flag set if the SCOPE field of this structure has been
1427        computed.  */
1428     unsigned int scope_set : 1;
1429
1430     /* Flag set if the DIE has a byte_size attribute.  */
1431     unsigned int has_byte_size : 1;
1432
1433     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1434     unsigned int has_const_value : 1;
1435
1436     /* Flag set if any of the DIE's children are template arguments.  */
1437     unsigned int has_template_arguments : 1;
1438
1439     /* Flag set if fixup_partial_die has been called on this die.  */
1440     unsigned int fixup_called : 1;
1441
1442     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1443     unsigned int is_dwz : 1;
1444
1445     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1446     unsigned int spec_is_dwz : 1;
1447
1448     /* The name of this DIE.  Normally the value of DW_AT_name, but
1449        sometimes a default name for unnamed DIEs.  */
1450     const char *name;
1451
1452     /* The linkage name, if present.  */
1453     const char *linkage_name;
1454
1455     /* The scope to prepend to our children.  This is generally
1456        allocated on the comp_unit_obstack, so will disappear
1457        when this compilation unit leaves the cache.  */
1458     const char *scope;
1459
1460     /* Some data associated with the partial DIE.  The tag determines
1461        which field is live.  */
1462     union
1463     {
1464       /* The location description associated with this DIE, if any.  */
1465       struct dwarf_block *locdesc;
1466       /* The offset of an import, for DW_TAG_imported_unit.  */
1467       sect_offset sect_off;
1468     } d;
1469
1470     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1471     CORE_ADDR lowpc;
1472     CORE_ADDR highpc;
1473
1474     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1475        DW_AT_sibling, if any.  */
1476     /* NOTE: This member isn't strictly necessary, read_partial_die could
1477        return DW_AT_sibling values to its caller load_partial_dies.  */
1478     const gdb_byte *sibling;
1479
1480     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1481        DW_AT_specification (or DW_AT_abstract_origin or
1482        DW_AT_extension).  */
1483     sect_offset spec_offset;
1484
1485     /* Pointers to this DIE's parent, first child, and next sibling,
1486        if any.  */
1487     struct partial_die_info *die_parent, *die_child, *die_sibling;
1488   };
1489
1490 /* This data structure holds the information of an abbrev.  */
1491 struct abbrev_info
1492   {
1493     unsigned int number;        /* number identifying abbrev */
1494     enum dwarf_tag tag;         /* dwarf tag */
1495     unsigned short has_children;                /* boolean */
1496     unsigned short num_attrs;   /* number of attributes */
1497     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1498     struct abbrev_info *next;   /* next in chain */
1499   };
1500
1501 struct attr_abbrev
1502   {
1503     ENUM_BITFIELD(dwarf_attribute) name : 16;
1504     ENUM_BITFIELD(dwarf_form) form : 16;
1505
1506     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1507     LONGEST implicit_const;
1508   };
1509
1510 /* Size of abbrev_table.abbrev_hash_table.  */
1511 #define ABBREV_HASH_SIZE 121
1512
1513 /* Top level data structure to contain an abbreviation table.  */
1514
1515 struct abbrev_table
1516 {
1517   /* Where the abbrev table came from.
1518      This is used as a sanity check when the table is used.  */
1519   sect_offset sect_off;
1520
1521   /* Storage for the abbrev table.  */
1522   struct obstack abbrev_obstack;
1523
1524   /* Hash table of abbrevs.
1525      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1526      It could be statically allocated, but the previous code didn't so we
1527      don't either.  */
1528   struct abbrev_info **abbrevs;
1529 };
1530
1531 /* Attributes have a name and a value.  */
1532 struct attribute
1533   {
1534     ENUM_BITFIELD(dwarf_attribute) name : 16;
1535     ENUM_BITFIELD(dwarf_form) form : 15;
1536
1537     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1538        field should be in u.str (existing only for DW_STRING) but it is kept
1539        here for better struct attribute alignment.  */
1540     unsigned int string_is_canonical : 1;
1541
1542     union
1543       {
1544         const char *str;
1545         struct dwarf_block *blk;
1546         ULONGEST unsnd;
1547         LONGEST snd;
1548         CORE_ADDR addr;
1549         ULONGEST signature;
1550       }
1551     u;
1552   };
1553
1554 /* This data structure holds a complete die structure.  */
1555 struct die_info
1556   {
1557     /* DWARF-2 tag for this DIE.  */
1558     ENUM_BITFIELD(dwarf_tag) tag : 16;
1559
1560     /* Number of attributes */
1561     unsigned char num_attrs;
1562
1563     /* True if we're presently building the full type name for the
1564        type derived from this DIE.  */
1565     unsigned char building_fullname : 1;
1566
1567     /* True if this die is in process.  PR 16581.  */
1568     unsigned char in_process : 1;
1569
1570     /* Abbrev number */
1571     unsigned int abbrev;
1572
1573     /* Offset in .debug_info or .debug_types section.  */
1574     sect_offset sect_off;
1575
1576     /* The dies in a compilation unit form an n-ary tree.  PARENT
1577        points to this die's parent; CHILD points to the first child of
1578        this node; and all the children of a given node are chained
1579        together via their SIBLING fields.  */
1580     struct die_info *child;     /* Its first child, if any.  */
1581     struct die_info *sibling;   /* Its next sibling, if any.  */
1582     struct die_info *parent;    /* Its parent, if any.  */
1583
1584     /* An array of attributes, with NUM_ATTRS elements.  There may be
1585        zero, but it's not common and zero-sized arrays are not
1586        sufficiently portable C.  */
1587     struct attribute attrs[1];
1588   };
1589
1590 /* Get at parts of an attribute structure.  */
1591
1592 #define DW_STRING(attr)    ((attr)->u.str)
1593 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1594 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1595 #define DW_BLOCK(attr)     ((attr)->u.blk)
1596 #define DW_SND(attr)       ((attr)->u.snd)
1597 #define DW_ADDR(attr)      ((attr)->u.addr)
1598 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1599
1600 /* Blocks are a bunch of untyped bytes.  */
1601 struct dwarf_block
1602   {
1603     size_t size;
1604
1605     /* Valid only if SIZE is not zero.  */
1606     const gdb_byte *data;
1607   };
1608
1609 #ifndef ATTR_ALLOC_CHUNK
1610 #define ATTR_ALLOC_CHUNK 4
1611 #endif
1612
1613 /* Allocate fields for structs, unions and enums in this size.  */
1614 #ifndef DW_FIELD_ALLOC_CHUNK
1615 #define DW_FIELD_ALLOC_CHUNK 4
1616 #endif
1617
1618 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1619    but this would require a corresponding change in unpack_field_as_long
1620    and friends.  */
1621 static int bits_per_byte = 8;
1622
1623 struct nextfield
1624 {
1625   struct nextfield *next;
1626   int accessibility;
1627   int virtuality;
1628   struct field field;
1629 };
1630
1631 struct nextfnfield
1632 {
1633   struct nextfnfield *next;
1634   struct fn_field fnfield;
1635 };
1636
1637 struct fnfieldlist
1638 {
1639   const char *name;
1640   int length;
1641   struct nextfnfield *head;
1642 };
1643
1644 struct decl_field_list
1645 {
1646   struct decl_field field;
1647   struct decl_field_list *next;
1648 };
1649
1650 /* The routines that read and process dies for a C struct or C++ class
1651    pass lists of data member fields and lists of member function fields
1652    in an instance of a field_info structure, as defined below.  */
1653 struct field_info
1654   {
1655     /* List of data member and baseclasses fields.  */
1656     struct nextfield *fields, *baseclasses;
1657
1658     /* Number of fields (including baseclasses).  */
1659     int nfields;
1660
1661     /* Number of baseclasses.  */
1662     int nbaseclasses;
1663
1664     /* Set if the accesibility of one of the fields is not public.  */
1665     int non_public_fields;
1666
1667     /* Member function fieldlist array, contains name of possibly overloaded
1668        member function, number of overloaded member functions and a pointer
1669        to the head of the member function field chain.  */
1670     struct fnfieldlist *fnfieldlists;
1671
1672     /* Number of entries in the fnfieldlists array.  */
1673     int nfnfields;
1674
1675     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1676        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1677     struct decl_field_list *typedef_field_list;
1678     unsigned typedef_field_list_count;
1679
1680     /* Nested types defined by this class and the number of elements in this
1681        list.  */
1682     struct decl_field_list *nested_types_list;
1683     unsigned nested_types_list_count;
1684   };
1685
1686 /* One item on the queue of compilation units to read in full symbols
1687    for.  */
1688 struct dwarf2_queue_item
1689 {
1690   struct dwarf2_per_cu_data *per_cu;
1691   enum language pretend_language;
1692   struct dwarf2_queue_item *next;
1693 };
1694
1695 /* The current queue.  */
1696 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1697
1698 /* Loaded secondary compilation units are kept in memory until they
1699    have not been referenced for the processing of this many
1700    compilation units.  Set this to zero to disable caching.  Cache
1701    sizes of up to at least twenty will improve startup time for
1702    typical inter-CU-reference binaries, at an obvious memory cost.  */
1703 static int dwarf_max_cache_age = 5;
1704 static void
1705 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1706                           struct cmd_list_element *c, const char *value)
1707 {
1708   fprintf_filtered (file, _("The upper bound on the age of cached "
1709                             "DWARF compilation units is %s.\n"),
1710                     value);
1711 }
1712 \f
1713 /* local function prototypes */
1714
1715 static const char *get_section_name (const struct dwarf2_section_info *);
1716
1717 static const char *get_section_file_name (const struct dwarf2_section_info *);
1718
1719 static void dwarf2_find_base_address (struct die_info *die,
1720                                       struct dwarf2_cu *cu);
1721
1722 static struct partial_symtab *create_partial_symtab
1723   (struct dwarf2_per_cu_data *per_cu, const char *name);
1724
1725 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1726                                         const gdb_byte *info_ptr,
1727                                         struct die_info *type_unit_die,
1728                                         int has_children, void *data);
1729
1730 static void dwarf2_build_psymtabs_hard
1731   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1732
1733 static void scan_partial_symbols (struct partial_die_info *,
1734                                   CORE_ADDR *, CORE_ADDR *,
1735                                   int, struct dwarf2_cu *);
1736
1737 static void add_partial_symbol (struct partial_die_info *,
1738                                 struct dwarf2_cu *);
1739
1740 static void add_partial_namespace (struct partial_die_info *pdi,
1741                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1742                                    int set_addrmap, struct dwarf2_cu *cu);
1743
1744 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1745                                 CORE_ADDR *highpc, int set_addrmap,
1746                                 struct dwarf2_cu *cu);
1747
1748 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1749                                      struct dwarf2_cu *cu);
1750
1751 static void add_partial_subprogram (struct partial_die_info *pdi,
1752                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1753                                     int need_pc, struct dwarf2_cu *cu);
1754
1755 static void dwarf2_read_symtab (struct partial_symtab *,
1756                                 struct objfile *);
1757
1758 static void psymtab_to_symtab_1 (struct partial_symtab *);
1759
1760 static struct abbrev_info *abbrev_table_lookup_abbrev
1761   (const struct abbrev_table *, unsigned int);
1762
1763 static struct abbrev_table *abbrev_table_read_table
1764   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1765    sect_offset);
1766
1767 static void abbrev_table_free (struct abbrev_table *);
1768
1769 static void abbrev_table_free_cleanup (void *);
1770
1771 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1772                                  struct dwarf2_section_info *);
1773
1774 static void dwarf2_free_abbrev_table (void *);
1775
1776 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1777
1778 static struct partial_die_info *load_partial_dies
1779   (const struct die_reader_specs *, const gdb_byte *, int);
1780
1781 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1782                                          struct partial_die_info *,
1783                                          struct abbrev_info *,
1784                                          unsigned int,
1785                                          const gdb_byte *);
1786
1787 static struct partial_die_info *find_partial_die (sect_offset, int,
1788                                                   struct dwarf2_cu *);
1789
1790 static void fixup_partial_die (struct partial_die_info *,
1791                                struct dwarf2_cu *);
1792
1793 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1794                                        struct attribute *, struct attr_abbrev *,
1795                                        const gdb_byte *);
1796
1797 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1798
1799 static int read_1_signed_byte (bfd *, const gdb_byte *);
1800
1801 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1802
1803 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1804
1805 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1806
1807 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1808                                unsigned int *);
1809
1810 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1811
1812 static LONGEST read_checked_initial_length_and_offset
1813   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1814    unsigned int *, unsigned int *);
1815
1816 static LONGEST read_offset (bfd *, const gdb_byte *,
1817                             const struct comp_unit_head *,
1818                             unsigned int *);
1819
1820 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1821
1822 static sect_offset read_abbrev_offset
1823   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1824    struct dwarf2_section_info *, sect_offset);
1825
1826 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1827
1828 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1829
1830 static const char *read_indirect_string
1831   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1832    const struct comp_unit_head *, unsigned int *);
1833
1834 static const char *read_indirect_line_string
1835   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1836    const struct comp_unit_head *, unsigned int *);
1837
1838 static const char *read_indirect_string_at_offset
1839   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1840    LONGEST str_offset);
1841
1842 static const char *read_indirect_string_from_dwz
1843   (struct objfile *objfile, struct dwz_file *, LONGEST);
1844
1845 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1846
1847 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1848                                               const gdb_byte *,
1849                                               unsigned int *);
1850
1851 static const char *read_str_index (const struct die_reader_specs *reader,
1852                                    ULONGEST str_index);
1853
1854 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1855
1856 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1857                                       struct dwarf2_cu *);
1858
1859 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1860                                                 unsigned int);
1861
1862 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1863                                        struct dwarf2_cu *cu);
1864
1865 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1866                                struct dwarf2_cu *cu);
1867
1868 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1869
1870 static struct die_info *die_specification (struct die_info *die,
1871                                            struct dwarf2_cu **);
1872
1873 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1874                                                 struct dwarf2_cu *cu);
1875
1876 static void dwarf_decode_lines (struct line_header *, const char *,
1877                                 struct dwarf2_cu *, struct partial_symtab *,
1878                                 CORE_ADDR, int decode_mapping);
1879
1880 static void dwarf2_start_subfile (const char *, const char *);
1881
1882 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1883                                                     const char *, const char *,
1884                                                     CORE_ADDR);
1885
1886 static struct symbol *new_symbol (struct die_info *, struct type *,
1887                                   struct dwarf2_cu *, struct symbol * = NULL);
1888
1889 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1890                                 struct dwarf2_cu *);
1891
1892 static void dwarf2_const_value_attr (const struct attribute *attr,
1893                                      struct type *type,
1894                                      const char *name,
1895                                      struct obstack *obstack,
1896                                      struct dwarf2_cu *cu, LONGEST *value,
1897                                      const gdb_byte **bytes,
1898                                      struct dwarf2_locexpr_baton **baton);
1899
1900 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1901
1902 static int need_gnat_info (struct dwarf2_cu *);
1903
1904 static struct type *die_descriptive_type (struct die_info *,
1905                                           struct dwarf2_cu *);
1906
1907 static void set_descriptive_type (struct type *, struct die_info *,
1908                                   struct dwarf2_cu *);
1909
1910 static struct type *die_containing_type (struct die_info *,
1911                                          struct dwarf2_cu *);
1912
1913 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1914                                      struct dwarf2_cu *);
1915
1916 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1917
1918 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1919
1920 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1921
1922 static char *typename_concat (struct obstack *obs, const char *prefix,
1923                               const char *suffix, int physname,
1924                               struct dwarf2_cu *cu);
1925
1926 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1927
1928 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1929
1930 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1931
1932 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1933
1934 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1935
1936 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1937
1938 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1939                                struct dwarf2_cu *, struct partial_symtab *);
1940
1941 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1942    values.  Keep the items ordered with increasing constraints compliance.  */
1943 enum pc_bounds_kind
1944 {
1945   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1946   PC_BOUNDS_NOT_PRESENT,
1947
1948   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1949      were present but they do not form a valid range of PC addresses.  */
1950   PC_BOUNDS_INVALID,
1951
1952   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1953   PC_BOUNDS_RANGES,
1954
1955   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1956   PC_BOUNDS_HIGH_LOW,
1957 };
1958
1959 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1960                                                  CORE_ADDR *, CORE_ADDR *,
1961                                                  struct dwarf2_cu *,
1962                                                  struct partial_symtab *);
1963
1964 static void get_scope_pc_bounds (struct die_info *,
1965                                  CORE_ADDR *, CORE_ADDR *,
1966                                  struct dwarf2_cu *);
1967
1968 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1969                                         CORE_ADDR, struct dwarf2_cu *);
1970
1971 static void dwarf2_add_field (struct field_info *, struct die_info *,
1972                               struct dwarf2_cu *);
1973
1974 static void dwarf2_attach_fields_to_type (struct field_info *,
1975                                           struct type *, struct dwarf2_cu *);
1976
1977 static void dwarf2_add_member_fn (struct field_info *,
1978                                   struct die_info *, struct type *,
1979                                   struct dwarf2_cu *);
1980
1981 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1982                                              struct type *,
1983                                              struct dwarf2_cu *);
1984
1985 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1986
1987 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1988
1989 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1990
1991 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1992
1993 static struct using_direct **using_directives (enum language);
1994
1995 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1996
1997 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1998
1999 static struct type *read_module_type (struct die_info *die,
2000                                       struct dwarf2_cu *cu);
2001
2002 static const char *namespace_name (struct die_info *die,
2003                                    int *is_anonymous, struct dwarf2_cu *);
2004
2005 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
2006
2007 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
2008
2009 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
2010                                                        struct dwarf2_cu *);
2011
2012 static struct die_info *read_die_and_siblings_1
2013   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
2014    struct die_info *);
2015
2016 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
2017                                                const gdb_byte *info_ptr,
2018                                                const gdb_byte **new_info_ptr,
2019                                                struct die_info *parent);
2020
2021 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
2022                                         struct die_info **, const gdb_byte *,
2023                                         int *, int);
2024
2025 static const gdb_byte *read_full_die (const struct die_reader_specs *,
2026                                       struct die_info **, const gdb_byte *,
2027                                       int *);
2028
2029 static void process_die (struct die_info *, struct dwarf2_cu *);
2030
2031 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
2032                                              struct obstack *);
2033
2034 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
2035
2036 static const char *dwarf2_full_name (const char *name,
2037                                      struct die_info *die,
2038                                      struct dwarf2_cu *cu);
2039
2040 static const char *dwarf2_physname (const char *name, struct die_info *die,
2041                                     struct dwarf2_cu *cu);
2042
2043 static struct die_info *dwarf2_extension (struct die_info *die,
2044                                           struct dwarf2_cu **);
2045
2046 static const char *dwarf_tag_name (unsigned int);
2047
2048 static const char *dwarf_attr_name (unsigned int);
2049
2050 static const char *dwarf_form_name (unsigned int);
2051
2052 static const char *dwarf_bool_name (unsigned int);
2053
2054 static const char *dwarf_type_encoding_name (unsigned int);
2055
2056 static struct die_info *sibling_die (struct die_info *);
2057
2058 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
2059
2060 static void dump_die_for_error (struct die_info *);
2061
2062 static void dump_die_1 (struct ui_file *, int level, int max_level,
2063                         struct die_info *);
2064
2065 /*static*/ void dump_die (struct die_info *, int max_level);
2066
2067 static void store_in_ref_table (struct die_info *,
2068                                 struct dwarf2_cu *);
2069
2070 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
2071
2072 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
2073
2074 static struct die_info *follow_die_ref_or_sig (struct die_info *,
2075                                                const struct attribute *,
2076                                                struct dwarf2_cu **);
2077
2078 static struct die_info *follow_die_ref (struct die_info *,
2079                                         const struct attribute *,
2080                                         struct dwarf2_cu **);
2081
2082 static struct die_info *follow_die_sig (struct die_info *,
2083                                         const struct attribute *,
2084                                         struct dwarf2_cu **);
2085
2086 static struct type *get_signatured_type (struct die_info *, ULONGEST,
2087                                          struct dwarf2_cu *);
2088
2089 static struct type *get_DW_AT_signature_type (struct die_info *,
2090                                               const struct attribute *,
2091                                               struct dwarf2_cu *);
2092
2093 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
2094
2095 static void read_signatured_type (struct signatured_type *);
2096
2097 static int attr_to_dynamic_prop (const struct attribute *attr,
2098                                  struct die_info *die, struct dwarf2_cu *cu,
2099                                  struct dynamic_prop *prop);
2100
2101 /* memory allocation interface */
2102
2103 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
2104
2105 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
2106
2107 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
2108
2109 static int attr_form_is_block (const struct attribute *);
2110
2111 static int attr_form_is_section_offset (const struct attribute *);
2112
2113 static int attr_form_is_constant (const struct attribute *);
2114
2115 static int attr_form_is_ref (const struct attribute *);
2116
2117 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2118                                    struct dwarf2_loclist_baton *baton,
2119                                    const struct attribute *attr);
2120
2121 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2122                                          struct symbol *sym,
2123                                          struct dwarf2_cu *cu,
2124                                          int is_block);
2125
2126 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2127                                      const gdb_byte *info_ptr,
2128                                      struct abbrev_info *abbrev);
2129
2130 static void free_stack_comp_unit (void *);
2131
2132 static hashval_t partial_die_hash (const void *item);
2133
2134 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2135
2136 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2137   (sect_offset sect_off, unsigned int offset_in_dwz,
2138    struct dwarf2_per_objfile *dwarf2_per_objfile);
2139
2140 static void init_one_comp_unit (struct dwarf2_cu *cu,
2141                                 struct dwarf2_per_cu_data *per_cu);
2142
2143 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2144                                    struct die_info *comp_unit_die,
2145                                    enum language pretend_language);
2146
2147 static void free_heap_comp_unit (void *);
2148
2149 static void free_cached_comp_units (void *);
2150
2151 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2152
2153 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2154
2155 static struct type *set_die_type (struct die_info *, struct type *,
2156                                   struct dwarf2_cu *);
2157
2158 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2159
2160 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
2161
2162 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2163                                  enum language);
2164
2165 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2166                                     enum language);
2167
2168 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2169                                     enum language);
2170
2171 static void dwarf2_add_dependence (struct dwarf2_cu *,
2172                                    struct dwarf2_per_cu_data *);
2173
2174 static void dwarf2_mark (struct dwarf2_cu *);
2175
2176 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2177
2178 static struct type *get_die_type_at_offset (sect_offset,
2179                                             struct dwarf2_per_cu_data *);
2180
2181 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2182
2183 static void dwarf2_release_queue (void *dummy);
2184
2185 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2186                              enum language pretend_language);
2187
2188 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
2189
2190 /* The return type of find_file_and_directory.  Note, the enclosed
2191    string pointers are only valid while this object is valid.  */
2192
2193 struct file_and_directory
2194 {
2195   /* The filename.  This is never NULL.  */
2196   const char *name;
2197
2198   /* The compilation directory.  NULL if not known.  If we needed to
2199      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2200      points directly to the DW_AT_comp_dir string attribute owned by
2201      the obstack that owns the DIE.  */
2202   const char *comp_dir;
2203
2204   /* If we needed to build a new string for comp_dir, this is what
2205      owns the storage.  */
2206   std::string comp_dir_storage;
2207 };
2208
2209 static file_and_directory find_file_and_directory (struct die_info *die,
2210                                                    struct dwarf2_cu *cu);
2211
2212 static char *file_full_name (int file, struct line_header *lh,
2213                              const char *comp_dir);
2214
2215 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2216 enum class rcuh_kind { COMPILE, TYPE };
2217
2218 static const gdb_byte *read_and_check_comp_unit_head
2219   (struct dwarf2_per_objfile* dwarf2_per_objfile,
2220    struct comp_unit_head *header,
2221    struct dwarf2_section_info *section,
2222    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2223    rcuh_kind section_kind);
2224
2225 static void init_cutu_and_read_dies
2226   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2227    int use_existing_cu, int keep,
2228    die_reader_func_ftype *die_reader_func, void *data);
2229
2230 static void init_cutu_and_read_dies_simple
2231   (struct dwarf2_per_cu_data *this_cu,
2232    die_reader_func_ftype *die_reader_func, void *data);
2233
2234 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2235
2236 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2237
2238 static struct dwo_unit *lookup_dwo_unit_in_dwp
2239   (struct dwarf2_per_objfile *dwarf2_per_objfile,
2240    struct dwp_file *dwp_file, const char *comp_dir,
2241    ULONGEST signature, int is_debug_types);
2242
2243 static struct dwp_file *get_dwp_file
2244   (struct dwarf2_per_objfile *dwarf2_per_objfile);
2245
2246 static struct dwo_unit *lookup_dwo_comp_unit
2247   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2248
2249 static struct dwo_unit *lookup_dwo_type_unit
2250   (struct signatured_type *, const char *, const char *);
2251
2252 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2253
2254 static void free_dwo_file_cleanup (void *);
2255
2256 struct free_dwo_file_cleanup_data
2257 {
2258   struct dwo_file *dwo_file;
2259   struct dwarf2_per_objfile *dwarf2_per_objfile;
2260 };
2261
2262 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
2263
2264 static void check_producer (struct dwarf2_cu *cu);
2265
2266 static void free_line_header_voidp (void *arg);
2267 \f
2268 /* Various complaints about symbol reading that don't abort the process.  */
2269
2270 static void
2271 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2272 {
2273   complaint (&symfile_complaints,
2274              _("statement list doesn't fit in .debug_line section"));
2275 }
2276
2277 static void
2278 dwarf2_debug_line_missing_file_complaint (void)
2279 {
2280   complaint (&symfile_complaints,
2281              _(".debug_line section has line data without a file"));
2282 }
2283
2284 static void
2285 dwarf2_debug_line_missing_end_sequence_complaint (void)
2286 {
2287   complaint (&symfile_complaints,
2288              _(".debug_line section has line "
2289                "program sequence without an end"));
2290 }
2291
2292 static void
2293 dwarf2_complex_location_expr_complaint (void)
2294 {
2295   complaint (&symfile_complaints, _("location expression too complex"));
2296 }
2297
2298 static void
2299 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2300                                               int arg3)
2301 {
2302   complaint (&symfile_complaints,
2303              _("const value length mismatch for '%s', got %d, expected %d"),
2304              arg1, arg2, arg3);
2305 }
2306
2307 static void
2308 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2309 {
2310   complaint (&symfile_complaints,
2311              _("debug info runs off end of %s section"
2312                " [in module %s]"),
2313              get_section_name (section),
2314              get_section_file_name (section));
2315 }
2316
2317 static void
2318 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2319 {
2320   complaint (&symfile_complaints,
2321              _("macro debug info contains a "
2322                "malformed macro definition:\n`%s'"),
2323              arg1);
2324 }
2325
2326 static void
2327 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2328 {
2329   complaint (&symfile_complaints,
2330              _("invalid attribute class or form for '%s' in '%s'"),
2331              arg1, arg2);
2332 }
2333
2334 /* Hash function for line_header_hash.  */
2335
2336 static hashval_t
2337 line_header_hash (const struct line_header *ofs)
2338 {
2339   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2340 }
2341
2342 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2343
2344 static hashval_t
2345 line_header_hash_voidp (const void *item)
2346 {
2347   const struct line_header *ofs = (const struct line_header *) item;
2348
2349   return line_header_hash (ofs);
2350 }
2351
2352 /* Equality function for line_header_hash.  */
2353
2354 static int
2355 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2356 {
2357   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2358   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2359
2360   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2361           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2362 }
2363
2364 \f
2365
2366 /* Read the given attribute value as an address, taking the attribute's
2367    form into account.  */
2368
2369 static CORE_ADDR
2370 attr_value_as_address (struct attribute *attr)
2371 {
2372   CORE_ADDR addr;
2373
2374   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2375     {
2376       /* Aside from a few clearly defined exceptions, attributes that
2377          contain an address must always be in DW_FORM_addr form.
2378          Unfortunately, some compilers happen to be violating this
2379          requirement by encoding addresses using other forms, such
2380          as DW_FORM_data4 for example.  For those broken compilers,
2381          we try to do our best, without any guarantee of success,
2382          to interpret the address correctly.  It would also be nice
2383          to generate a complaint, but that would require us to maintain
2384          a list of legitimate cases where a non-address form is allowed,
2385          as well as update callers to pass in at least the CU's DWARF
2386          version.  This is more overhead than what we're willing to
2387          expand for a pretty rare case.  */
2388       addr = DW_UNSND (attr);
2389     }
2390   else
2391     addr = DW_ADDR (attr);
2392
2393   return addr;
2394 }
2395
2396 /* The suffix for an index file.  */
2397 #define INDEX4_SUFFIX ".gdb-index"
2398 #define INDEX5_SUFFIX ".debug_names"
2399 #define DEBUG_STR_SUFFIX ".debug_str"
2400
2401 /* See declaration.  */
2402
2403 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2404                                         const dwarf2_debug_sections *names)
2405   : objfile (objfile_)
2406 {
2407   if (names == NULL)
2408     names = &dwarf2_elf_names;
2409
2410   bfd *obfd = objfile->obfd;
2411
2412   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2413     locate_sections (obfd, sec, *names);
2414 }
2415
2416 dwarf2_per_objfile::~dwarf2_per_objfile ()
2417 {
2418   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2419   free_cached_comp_units ();
2420
2421   if (quick_file_names_table)
2422     htab_delete (quick_file_names_table);
2423
2424   if (line_header_hash)
2425     htab_delete (line_header_hash);
2426
2427   /* Everything else should be on the objfile obstack.  */
2428 }
2429
2430 /* See declaration.  */
2431
2432 void
2433 dwarf2_per_objfile::free_cached_comp_units ()
2434 {
2435   dwarf2_per_cu_data *per_cu = read_in_chain;
2436   dwarf2_per_cu_data **last_chain = &read_in_chain;
2437   while (per_cu != NULL)
2438     {
2439       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2440
2441       free_heap_comp_unit (per_cu->cu);
2442       *last_chain = next_cu;
2443       per_cu = next_cu;
2444     }
2445 }
2446
2447 /* Try to locate the sections we need for DWARF 2 debugging
2448    information and return true if we have enough to do something.
2449    NAMES points to the dwarf2 section names, or is NULL if the standard
2450    ELF names are used.  */
2451
2452 int
2453 dwarf2_has_info (struct objfile *objfile,
2454                  const struct dwarf2_debug_sections *names)
2455 {
2456   if (objfile->flags & OBJF_READNEVER)
2457     return 0;
2458
2459   struct dwarf2_per_objfile *dwarf2_per_objfile
2460     = get_dwarf2_per_objfile (objfile);
2461
2462   if (dwarf2_per_objfile == NULL)
2463     {
2464       /* Initialize per-objfile state.  */
2465       struct dwarf2_per_objfile *data
2466         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2467
2468       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2469       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2470     }
2471   return (!dwarf2_per_objfile->info.is_virtual
2472           && dwarf2_per_objfile->info.s.section != NULL
2473           && !dwarf2_per_objfile->abbrev.is_virtual
2474           && dwarf2_per_objfile->abbrev.s.section != NULL);
2475 }
2476
2477 /* Return the containing section of virtual section SECTION.  */
2478
2479 static struct dwarf2_section_info *
2480 get_containing_section (const struct dwarf2_section_info *section)
2481 {
2482   gdb_assert (section->is_virtual);
2483   return section->s.containing_section;
2484 }
2485
2486 /* Return the bfd owner of SECTION.  */
2487
2488 static struct bfd *
2489 get_section_bfd_owner (const struct dwarf2_section_info *section)
2490 {
2491   if (section->is_virtual)
2492     {
2493       section = get_containing_section (section);
2494       gdb_assert (!section->is_virtual);
2495     }
2496   return section->s.section->owner;
2497 }
2498
2499 /* Return the bfd section of SECTION.
2500    Returns NULL if the section is not present.  */
2501
2502 static asection *
2503 get_section_bfd_section (const struct dwarf2_section_info *section)
2504 {
2505   if (section->is_virtual)
2506     {
2507       section = get_containing_section (section);
2508       gdb_assert (!section->is_virtual);
2509     }
2510   return section->s.section;
2511 }
2512
2513 /* Return the name of SECTION.  */
2514
2515 static const char *
2516 get_section_name (const struct dwarf2_section_info *section)
2517 {
2518   asection *sectp = get_section_bfd_section (section);
2519
2520   gdb_assert (sectp != NULL);
2521   return bfd_section_name (get_section_bfd_owner (section), sectp);
2522 }
2523
2524 /* Return the name of the file SECTION is in.  */
2525
2526 static const char *
2527 get_section_file_name (const struct dwarf2_section_info *section)
2528 {
2529   bfd *abfd = get_section_bfd_owner (section);
2530
2531   return bfd_get_filename (abfd);
2532 }
2533
2534 /* Return the id of SECTION.
2535    Returns 0 if SECTION doesn't exist.  */
2536
2537 static int
2538 get_section_id (const struct dwarf2_section_info *section)
2539 {
2540   asection *sectp = get_section_bfd_section (section);
2541
2542   if (sectp == NULL)
2543     return 0;
2544   return sectp->id;
2545 }
2546
2547 /* Return the flags of SECTION.
2548    SECTION (or containing section if this is a virtual section) must exist.  */
2549
2550 static int
2551 get_section_flags (const struct dwarf2_section_info *section)
2552 {
2553   asection *sectp = get_section_bfd_section (section);
2554
2555   gdb_assert (sectp != NULL);
2556   return bfd_get_section_flags (sectp->owner, sectp);
2557 }
2558
2559 /* When loading sections, we look either for uncompressed section or for
2560    compressed section names.  */
2561
2562 static int
2563 section_is_p (const char *section_name,
2564               const struct dwarf2_section_names *names)
2565 {
2566   if (names->normal != NULL
2567       && strcmp (section_name, names->normal) == 0)
2568     return 1;
2569   if (names->compressed != NULL
2570       && strcmp (section_name, names->compressed) == 0)
2571     return 1;
2572   return 0;
2573 }
2574
2575 /* See declaration.  */
2576
2577 void
2578 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2579                                      const dwarf2_debug_sections &names)
2580 {
2581   flagword aflag = bfd_get_section_flags (abfd, sectp);
2582
2583   if ((aflag & SEC_HAS_CONTENTS) == 0)
2584     {
2585     }
2586   else if (section_is_p (sectp->name, &names.info))
2587     {
2588       this->info.s.section = sectp;
2589       this->info.size = bfd_get_section_size (sectp);
2590     }
2591   else if (section_is_p (sectp->name, &names.abbrev))
2592     {
2593       this->abbrev.s.section = sectp;
2594       this->abbrev.size = bfd_get_section_size (sectp);
2595     }
2596   else if (section_is_p (sectp->name, &names.line))
2597     {
2598       this->line.s.section = sectp;
2599       this->line.size = bfd_get_section_size (sectp);
2600     }
2601   else if (section_is_p (sectp->name, &names.loc))
2602     {
2603       this->loc.s.section = sectp;
2604       this->loc.size = bfd_get_section_size (sectp);
2605     }
2606   else if (section_is_p (sectp->name, &names.loclists))
2607     {
2608       this->loclists.s.section = sectp;
2609       this->loclists.size = bfd_get_section_size (sectp);
2610     }
2611   else if (section_is_p (sectp->name, &names.macinfo))
2612     {
2613       this->macinfo.s.section = sectp;
2614       this->macinfo.size = bfd_get_section_size (sectp);
2615     }
2616   else if (section_is_p (sectp->name, &names.macro))
2617     {
2618       this->macro.s.section = sectp;
2619       this->macro.size = bfd_get_section_size (sectp);
2620     }
2621   else if (section_is_p (sectp->name, &names.str))
2622     {
2623       this->str.s.section = sectp;
2624       this->str.size = bfd_get_section_size (sectp);
2625     }
2626   else if (section_is_p (sectp->name, &names.line_str))
2627     {
2628       this->line_str.s.section = sectp;
2629       this->line_str.size = bfd_get_section_size (sectp);
2630     }
2631   else if (section_is_p (sectp->name, &names.addr))
2632     {
2633       this->addr.s.section = sectp;
2634       this->addr.size = bfd_get_section_size (sectp);
2635     }
2636   else if (section_is_p (sectp->name, &names.frame))
2637     {
2638       this->frame.s.section = sectp;
2639       this->frame.size = bfd_get_section_size (sectp);
2640     }
2641   else if (section_is_p (sectp->name, &names.eh_frame))
2642     {
2643       this->eh_frame.s.section = sectp;
2644       this->eh_frame.size = bfd_get_section_size (sectp);
2645     }
2646   else if (section_is_p (sectp->name, &names.ranges))
2647     {
2648       this->ranges.s.section = sectp;
2649       this->ranges.size = bfd_get_section_size (sectp);
2650     }
2651   else if (section_is_p (sectp->name, &names.rnglists))
2652     {
2653       this->rnglists.s.section = sectp;
2654       this->rnglists.size = bfd_get_section_size (sectp);
2655     }
2656   else if (section_is_p (sectp->name, &names.types))
2657     {
2658       struct dwarf2_section_info type_section;
2659
2660       memset (&type_section, 0, sizeof (type_section));
2661       type_section.s.section = sectp;
2662       type_section.size = bfd_get_section_size (sectp);
2663
2664       VEC_safe_push (dwarf2_section_info_def, this->types,
2665                      &type_section);
2666     }
2667   else if (section_is_p (sectp->name, &names.gdb_index))
2668     {
2669       this->gdb_index.s.section = sectp;
2670       this->gdb_index.size = bfd_get_section_size (sectp);
2671     }
2672   else if (section_is_p (sectp->name, &names.debug_names))
2673     {
2674       this->debug_names.s.section = sectp;
2675       this->debug_names.size = bfd_get_section_size (sectp);
2676     }
2677   else if (section_is_p (sectp->name, &names.debug_aranges))
2678     {
2679       this->debug_aranges.s.section = sectp;
2680       this->debug_aranges.size = bfd_get_section_size (sectp);
2681     }
2682
2683   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2684       && bfd_section_vma (abfd, sectp) == 0)
2685     this->has_section_at_zero = true;
2686 }
2687
2688 /* A helper function that decides whether a section is empty,
2689    or not present.  */
2690
2691 static int
2692 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2693 {
2694   if (section->is_virtual)
2695     return section->size == 0;
2696   return section->s.section == NULL || section->size == 0;
2697 }
2698
2699 /* Read the contents of the section INFO.
2700    OBJFILE is the main object file, but not necessarily the file where
2701    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2702    of the DWO file.
2703    If the section is compressed, uncompress it before returning.  */
2704
2705 static void
2706 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2707 {
2708   asection *sectp;
2709   bfd *abfd;
2710   gdb_byte *buf, *retbuf;
2711
2712   if (info->readin)
2713     return;
2714   info->buffer = NULL;
2715   info->readin = 1;
2716
2717   if (dwarf2_section_empty_p (info))
2718     return;
2719
2720   sectp = get_section_bfd_section (info);
2721
2722   /* If this is a virtual section we need to read in the real one first.  */
2723   if (info->is_virtual)
2724     {
2725       struct dwarf2_section_info *containing_section =
2726         get_containing_section (info);
2727
2728       gdb_assert (sectp != NULL);
2729       if ((sectp->flags & SEC_RELOC) != 0)
2730         {
2731           error (_("Dwarf Error: DWP format V2 with relocations is not"
2732                    " supported in section %s [in module %s]"),
2733                  get_section_name (info), get_section_file_name (info));
2734         }
2735       dwarf2_read_section (objfile, containing_section);
2736       /* Other code should have already caught virtual sections that don't
2737          fit.  */
2738       gdb_assert (info->virtual_offset + info->size
2739                   <= containing_section->size);
2740       /* If the real section is empty or there was a problem reading the
2741          section we shouldn't get here.  */
2742       gdb_assert (containing_section->buffer != NULL);
2743       info->buffer = containing_section->buffer + info->virtual_offset;
2744       return;
2745     }
2746
2747   /* If the section has relocations, we must read it ourselves.
2748      Otherwise we attach it to the BFD.  */
2749   if ((sectp->flags & SEC_RELOC) == 0)
2750     {
2751       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2752       return;
2753     }
2754
2755   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2756   info->buffer = buf;
2757
2758   /* When debugging .o files, we may need to apply relocations; see
2759      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2760      We never compress sections in .o files, so we only need to
2761      try this when the section is not compressed.  */
2762   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2763   if (retbuf != NULL)
2764     {
2765       info->buffer = retbuf;
2766       return;
2767     }
2768
2769   abfd = get_section_bfd_owner (info);
2770   gdb_assert (abfd != NULL);
2771
2772   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2773       || bfd_bread (buf, info->size, abfd) != info->size)
2774     {
2775       error (_("Dwarf Error: Can't read DWARF data"
2776                " in section %s [in module %s]"),
2777              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2778     }
2779 }
2780
2781 /* A helper function that returns the size of a section in a safe way.
2782    If you are positive that the section has been read before using the
2783    size, then it is safe to refer to the dwarf2_section_info object's
2784    "size" field directly.  In other cases, you must call this
2785    function, because for compressed sections the size field is not set
2786    correctly until the section has been read.  */
2787
2788 static bfd_size_type
2789 dwarf2_section_size (struct objfile *objfile,
2790                      struct dwarf2_section_info *info)
2791 {
2792   if (!info->readin)
2793     dwarf2_read_section (objfile, info);
2794   return info->size;
2795 }
2796
2797 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2798    SECTION_NAME.  */
2799
2800 void
2801 dwarf2_get_section_info (struct objfile *objfile,
2802                          enum dwarf2_section_enum sect,
2803                          asection **sectp, const gdb_byte **bufp,
2804                          bfd_size_type *sizep)
2805 {
2806   struct dwarf2_per_objfile *data
2807     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2808                                                   dwarf2_objfile_data_key);
2809   struct dwarf2_section_info *info;
2810
2811   /* We may see an objfile without any DWARF, in which case we just
2812      return nothing.  */
2813   if (data == NULL)
2814     {
2815       *sectp = NULL;
2816       *bufp = NULL;
2817       *sizep = 0;
2818       return;
2819     }
2820   switch (sect)
2821     {
2822     case DWARF2_DEBUG_FRAME:
2823       info = &data->frame;
2824       break;
2825     case DWARF2_EH_FRAME:
2826       info = &data->eh_frame;
2827       break;
2828     default:
2829       gdb_assert_not_reached ("unexpected section");
2830     }
2831
2832   dwarf2_read_section (objfile, info);
2833
2834   *sectp = get_section_bfd_section (info);
2835   *bufp = info->buffer;
2836   *sizep = info->size;
2837 }
2838
2839 /* A helper function to find the sections for a .dwz file.  */
2840
2841 static void
2842 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2843 {
2844   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2845
2846   /* Note that we only support the standard ELF names, because .dwz
2847      is ELF-only (at the time of writing).  */
2848   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2849     {
2850       dwz_file->abbrev.s.section = sectp;
2851       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2852     }
2853   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2854     {
2855       dwz_file->info.s.section = sectp;
2856       dwz_file->info.size = bfd_get_section_size (sectp);
2857     }
2858   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2859     {
2860       dwz_file->str.s.section = sectp;
2861       dwz_file->str.size = bfd_get_section_size (sectp);
2862     }
2863   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2864     {
2865       dwz_file->line.s.section = sectp;
2866       dwz_file->line.size = bfd_get_section_size (sectp);
2867     }
2868   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2869     {
2870       dwz_file->macro.s.section = sectp;
2871       dwz_file->macro.size = bfd_get_section_size (sectp);
2872     }
2873   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2874     {
2875       dwz_file->gdb_index.s.section = sectp;
2876       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2877     }
2878   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2879     {
2880       dwz_file->debug_names.s.section = sectp;
2881       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2882     }
2883 }
2884
2885 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2886    there is no .gnu_debugaltlink section in the file.  Error if there
2887    is such a section but the file cannot be found.  */
2888
2889 static struct dwz_file *
2890 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2891 {
2892   const char *filename;
2893   struct dwz_file *result;
2894   bfd_size_type buildid_len_arg;
2895   size_t buildid_len;
2896   bfd_byte *buildid;
2897
2898   if (dwarf2_per_objfile->dwz_file != NULL)
2899     return dwarf2_per_objfile->dwz_file;
2900
2901   bfd_set_error (bfd_error_no_error);
2902   gdb::unique_xmalloc_ptr<char> data
2903     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2904                                   &buildid_len_arg, &buildid));
2905   if (data == NULL)
2906     {
2907       if (bfd_get_error () == bfd_error_no_error)
2908         return NULL;
2909       error (_("could not read '.gnu_debugaltlink' section: %s"),
2910              bfd_errmsg (bfd_get_error ()));
2911     }
2912
2913   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2914
2915   buildid_len = (size_t) buildid_len_arg;
2916
2917   filename = data.get ();
2918
2919   std::string abs_storage;
2920   if (!IS_ABSOLUTE_PATH (filename))
2921     {
2922       gdb::unique_xmalloc_ptr<char> abs
2923         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2924
2925       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2926       filename = abs_storage.c_str ();
2927     }
2928
2929   /* First try the file name given in the section.  If that doesn't
2930      work, try to use the build-id instead.  */
2931   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2932   if (dwz_bfd != NULL)
2933     {
2934       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2935         dwz_bfd.release ();
2936     }
2937
2938   if (dwz_bfd == NULL)
2939     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2940
2941   if (dwz_bfd == NULL)
2942     error (_("could not find '.gnu_debugaltlink' file for %s"),
2943            objfile_name (dwarf2_per_objfile->objfile));
2944
2945   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2946                            struct dwz_file);
2947   result->dwz_bfd = dwz_bfd.release ();
2948
2949   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2950
2951   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2952   dwarf2_per_objfile->dwz_file = result;
2953   return result;
2954 }
2955 \f
2956 /* DWARF quick_symbols_functions support.  */
2957
2958 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2959    unique line tables, so we maintain a separate table of all .debug_line
2960    derived entries to support the sharing.
2961    All the quick functions need is the list of file names.  We discard the
2962    line_header when we're done and don't need to record it here.  */
2963 struct quick_file_names
2964 {
2965   /* The data used to construct the hash key.  */
2966   struct stmt_list_hash hash;
2967
2968   /* The number of entries in file_names, real_names.  */
2969   unsigned int num_file_names;
2970
2971   /* The file names from the line table, after being run through
2972      file_full_name.  */
2973   const char **file_names;
2974
2975   /* The file names from the line table after being run through
2976      gdb_realpath.  These are computed lazily.  */
2977   const char **real_names;
2978 };
2979
2980 /* When using the index (and thus not using psymtabs), each CU has an
2981    object of this type.  This is used to hold information needed by
2982    the various "quick" methods.  */
2983 struct dwarf2_per_cu_quick_data
2984 {
2985   /* The file table.  This can be NULL if there was no file table
2986      or it's currently not read in.
2987      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2988   struct quick_file_names *file_names;
2989
2990   /* The corresponding symbol table.  This is NULL if symbols for this
2991      CU have not yet been read.  */
2992   struct compunit_symtab *compunit_symtab;
2993
2994   /* A temporary mark bit used when iterating over all CUs in
2995      expand_symtabs_matching.  */
2996   unsigned int mark : 1;
2997
2998   /* True if we've tried to read the file table and found there isn't one.
2999      There will be no point in trying to read it again next time.  */
3000   unsigned int no_file_data : 1;
3001 };
3002
3003 /* Utility hash function for a stmt_list_hash.  */
3004
3005 static hashval_t
3006 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
3007 {
3008   hashval_t v = 0;
3009
3010   if (stmt_list_hash->dwo_unit != NULL)
3011     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
3012   v += to_underlying (stmt_list_hash->line_sect_off);
3013   return v;
3014 }
3015
3016 /* Utility equality function for a stmt_list_hash.  */
3017
3018 static int
3019 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
3020                     const struct stmt_list_hash *rhs)
3021 {
3022   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
3023     return 0;
3024   if (lhs->dwo_unit != NULL
3025       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
3026     return 0;
3027
3028   return lhs->line_sect_off == rhs->line_sect_off;
3029 }
3030
3031 /* Hash function for a quick_file_names.  */
3032
3033 static hashval_t
3034 hash_file_name_entry (const void *e)
3035 {
3036   const struct quick_file_names *file_data
3037     = (const struct quick_file_names *) e;
3038
3039   return hash_stmt_list_entry (&file_data->hash);
3040 }
3041
3042 /* Equality function for a quick_file_names.  */
3043
3044 static int
3045 eq_file_name_entry (const void *a, const void *b)
3046 {
3047   const struct quick_file_names *ea = (const struct quick_file_names *) a;
3048   const struct quick_file_names *eb = (const struct quick_file_names *) b;
3049
3050   return eq_stmt_list_entry (&ea->hash, &eb->hash);
3051 }
3052
3053 /* Delete function for a quick_file_names.  */
3054
3055 static void
3056 delete_file_name_entry (void *e)
3057 {
3058   struct quick_file_names *file_data = (struct quick_file_names *) e;
3059   int i;
3060
3061   for (i = 0; i < file_data->num_file_names; ++i)
3062     {
3063       xfree ((void*) file_data->file_names[i]);
3064       if (file_data->real_names)
3065         xfree ((void*) file_data->real_names[i]);
3066     }
3067
3068   /* The space for the struct itself lives on objfile_obstack,
3069      so we don't free it here.  */
3070 }
3071
3072 /* Create a quick_file_names hash table.  */
3073
3074 static htab_t
3075 create_quick_file_names_table (unsigned int nr_initial_entries)
3076 {
3077   return htab_create_alloc (nr_initial_entries,
3078                             hash_file_name_entry, eq_file_name_entry,
3079                             delete_file_name_entry, xcalloc, xfree);
3080 }
3081
3082 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
3083    have to be created afterwards.  You should call age_cached_comp_units after
3084    processing PER_CU->CU.  dw2_setup must have been already called.  */
3085
3086 static void
3087 load_cu (struct dwarf2_per_cu_data *per_cu)
3088 {
3089   if (per_cu->is_debug_types)
3090     load_full_type_unit (per_cu);
3091   else
3092     load_full_comp_unit (per_cu, language_minimal);
3093
3094   if (per_cu->cu == NULL)
3095     return;  /* Dummy CU.  */
3096
3097   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
3098 }
3099
3100 /* Read in the symbols for PER_CU.  */
3101
3102 static void
3103 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3104 {
3105   struct cleanup *back_to;
3106   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3107
3108   /* Skip type_unit_groups, reading the type units they contain
3109      is handled elsewhere.  */
3110   if (IS_TYPE_UNIT_GROUP (per_cu))
3111     return;
3112
3113   back_to = make_cleanup (dwarf2_release_queue, NULL);
3114
3115   if (dwarf2_per_objfile->using_index
3116       ? per_cu->v.quick->compunit_symtab == NULL
3117       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
3118     {
3119       queue_comp_unit (per_cu, language_minimal);
3120       load_cu (per_cu);
3121
3122       /* If we just loaded a CU from a DWO, and we're working with an index
3123          that may badly handle TUs, load all the TUs in that DWO as well.
3124          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
3125       if (!per_cu->is_debug_types
3126           && per_cu->cu != NULL
3127           && per_cu->cu->dwo_unit != NULL
3128           && dwarf2_per_objfile->index_table != NULL
3129           && dwarf2_per_objfile->index_table->version <= 7
3130           /* DWP files aren't supported yet.  */
3131           && get_dwp_file (dwarf2_per_objfile) == NULL)
3132         queue_and_load_all_dwo_tus (per_cu);
3133     }
3134
3135   process_queue (dwarf2_per_objfile);
3136
3137   /* Age the cache, releasing compilation units that have not
3138      been used recently.  */
3139   age_cached_comp_units (dwarf2_per_objfile);
3140
3141   do_cleanups (back_to);
3142 }
3143
3144 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3145    the objfile from which this CU came.  Returns the resulting symbol
3146    table.  */
3147
3148 static struct compunit_symtab *
3149 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3150 {
3151   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
3152
3153   gdb_assert (dwarf2_per_objfile->using_index);
3154   if (!per_cu->v.quick->compunit_symtab)
3155     {
3156       struct cleanup *back_to = make_cleanup (free_cached_comp_units,
3157                                               dwarf2_per_objfile);
3158       scoped_restore decrementer = increment_reading_symtab ();
3159       dw2_do_instantiate_symtab (per_cu);
3160       process_cu_includes (dwarf2_per_objfile);
3161       do_cleanups (back_to);
3162     }
3163
3164   return per_cu->v.quick->compunit_symtab;
3165 }
3166
3167 /* Return the CU/TU given its index.
3168
3169    This is intended for loops like:
3170
3171    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3172                     + dwarf2_per_objfile->n_type_units); ++i)
3173      {
3174        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3175
3176        ...;
3177      }
3178 */
3179
3180 static struct dwarf2_per_cu_data *
3181 dw2_get_cutu (struct dwarf2_per_objfile *dwarf2_per_objfile,
3182               int index)
3183 {
3184   if (index >= dwarf2_per_objfile->n_comp_units)
3185     {
3186       index -= dwarf2_per_objfile->n_comp_units;
3187       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3188       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3189     }
3190
3191   return dwarf2_per_objfile->all_comp_units[index];
3192 }
3193
3194 /* Return the CU given its index.
3195    This differs from dw2_get_cutu in that it's for when you know INDEX
3196    refers to a CU.  */
3197
3198 static struct dwarf2_per_cu_data *
3199 dw2_get_cu (struct dwarf2_per_objfile *dwarf2_per_objfile, int index)
3200 {
3201   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3202
3203   return dwarf2_per_objfile->all_comp_units[index];
3204 }
3205
3206 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3207    objfile_obstack, and constructed with the specified field
3208    values.  */
3209
3210 static dwarf2_per_cu_data *
3211 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
3212                           struct dwarf2_section_info *section,
3213                           int is_dwz,
3214                           sect_offset sect_off, ULONGEST length)
3215 {
3216   struct objfile *objfile = dwarf2_per_objfile->objfile;
3217   dwarf2_per_cu_data *the_cu
3218     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3219                      struct dwarf2_per_cu_data);
3220   the_cu->sect_off = sect_off;
3221   the_cu->length = length;
3222   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
3223   the_cu->section = section;
3224   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3225                                    struct dwarf2_per_cu_quick_data);
3226   the_cu->is_dwz = is_dwz;
3227   return the_cu;
3228 }
3229
3230 /* A helper for create_cus_from_index that handles a given list of
3231    CUs.  */
3232
3233 static void
3234 create_cus_from_index_list (struct objfile *objfile,
3235                             const gdb_byte *cu_list, offset_type n_elements,
3236                             struct dwarf2_section_info *section,
3237                             int is_dwz,
3238                             int base_offset)
3239 {
3240   offset_type i;
3241   struct dwarf2_per_objfile *dwarf2_per_objfile
3242     = get_dwarf2_per_objfile (objfile);
3243
3244   for (i = 0; i < n_elements; i += 2)
3245     {
3246       gdb_static_assert (sizeof (ULONGEST) >= 8);
3247
3248       sect_offset sect_off
3249         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3250       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3251       cu_list += 2 * 8;
3252
3253       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3254         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
3255                                      sect_off, length);
3256     }
3257 }
3258
3259 /* Read the CU list from the mapped index, and use it to create all
3260    the CU objects for this objfile.  */
3261
3262 static void
3263 create_cus_from_index (struct objfile *objfile,
3264                        const gdb_byte *cu_list, offset_type cu_list_elements,
3265                        const gdb_byte *dwz_list, offset_type dwz_elements)
3266 {
3267   struct dwz_file *dwz;
3268   struct dwarf2_per_objfile *dwarf2_per_objfile
3269     = get_dwarf2_per_objfile (objfile);
3270
3271   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3272   dwarf2_per_objfile->all_comp_units =
3273     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3274                dwarf2_per_objfile->n_comp_units);
3275
3276   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3277                               &dwarf2_per_objfile->info, 0, 0);
3278
3279   if (dwz_elements == 0)
3280     return;
3281
3282   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3283   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3284                               cu_list_elements / 2);
3285 }
3286
3287 /* Create the signatured type hash table from the index.  */
3288
3289 static void
3290 create_signatured_type_table_from_index (struct objfile *objfile,
3291                                          struct dwarf2_section_info *section,
3292                                          const gdb_byte *bytes,
3293                                          offset_type elements)
3294 {
3295   offset_type i;
3296   htab_t sig_types_hash;
3297   struct dwarf2_per_objfile *dwarf2_per_objfile
3298     = get_dwarf2_per_objfile (objfile);
3299
3300   dwarf2_per_objfile->n_type_units
3301     = dwarf2_per_objfile->n_allocated_type_units
3302     = elements / 3;
3303   dwarf2_per_objfile->all_type_units =
3304     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3305
3306   sig_types_hash = allocate_signatured_type_table (objfile);
3307
3308   for (i = 0; i < elements; i += 3)
3309     {
3310       struct signatured_type *sig_type;
3311       ULONGEST signature;
3312       void **slot;
3313       cu_offset type_offset_in_tu;
3314
3315       gdb_static_assert (sizeof (ULONGEST) >= 8);
3316       sect_offset sect_off
3317         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3318       type_offset_in_tu
3319         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3320                                                 BFD_ENDIAN_LITTLE);
3321       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3322       bytes += 3 * 8;
3323
3324       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3325                                  struct signatured_type);
3326       sig_type->signature = signature;
3327       sig_type->type_offset_in_tu = type_offset_in_tu;
3328       sig_type->per_cu.is_debug_types = 1;
3329       sig_type->per_cu.section = section;
3330       sig_type->per_cu.sect_off = sect_off;
3331       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3332       sig_type->per_cu.v.quick
3333         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3334                           struct dwarf2_per_cu_quick_data);
3335
3336       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3337       *slot = sig_type;
3338
3339       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3340     }
3341
3342   dwarf2_per_objfile->signatured_types = sig_types_hash;
3343 }
3344
3345 /* Create the signatured type hash table from .debug_names.  */
3346
3347 static void
3348 create_signatured_type_table_from_debug_names
3349   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3350    const mapped_debug_names &map,
3351    struct dwarf2_section_info *section,
3352    struct dwarf2_section_info *abbrev_section)
3353 {
3354   struct objfile *objfile = dwarf2_per_objfile->objfile;
3355
3356   dwarf2_read_section (objfile, section);
3357   dwarf2_read_section (objfile, abbrev_section);
3358
3359   dwarf2_per_objfile->n_type_units
3360     = dwarf2_per_objfile->n_allocated_type_units
3361     = map.tu_count;
3362   dwarf2_per_objfile->all_type_units
3363     = XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3364
3365   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3366
3367   for (uint32_t i = 0; i < map.tu_count; ++i)
3368     {
3369       struct signatured_type *sig_type;
3370       ULONGEST signature;
3371       void **slot;
3372       cu_offset type_offset_in_tu;
3373
3374       sect_offset sect_off
3375         = (sect_offset) (extract_unsigned_integer
3376                          (map.tu_table_reordered + i * map.offset_size,
3377                           map.offset_size,
3378                           map.dwarf5_byte_order));
3379
3380       comp_unit_head cu_header;
3381       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3382                                      abbrev_section,
3383                                      section->buffer + to_underlying (sect_off),
3384                                      rcuh_kind::TYPE);
3385
3386       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3387                                  struct signatured_type);
3388       sig_type->signature = cu_header.signature;
3389       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3390       sig_type->per_cu.is_debug_types = 1;
3391       sig_type->per_cu.section = section;
3392       sig_type->per_cu.sect_off = sect_off;
3393       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3394       sig_type->per_cu.v.quick
3395         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3396                           struct dwarf2_per_cu_quick_data);
3397
3398       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3399       *slot = sig_type;
3400
3401       dwarf2_per_objfile->all_type_units[i] = sig_type;
3402     }
3403
3404   dwarf2_per_objfile->signatured_types = sig_types_hash;
3405 }
3406
3407 /* Read the address map data from the mapped index, and use it to
3408    populate the objfile's psymtabs_addrmap.  */
3409
3410 static void
3411 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3412                            struct mapped_index *index)
3413 {
3414   struct objfile *objfile = dwarf2_per_objfile->objfile;
3415   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3416   const gdb_byte *iter, *end;
3417   struct addrmap *mutable_map;
3418   CORE_ADDR baseaddr;
3419
3420   auto_obstack temp_obstack;
3421
3422   mutable_map = addrmap_create_mutable (&temp_obstack);
3423
3424   iter = index->address_table.data ();
3425   end = iter + index->address_table.size ();
3426
3427   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3428
3429   while (iter < end)
3430     {
3431       ULONGEST hi, lo, cu_index;
3432       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3433       iter += 8;
3434       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3435       iter += 8;
3436       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3437       iter += 4;
3438
3439       if (lo > hi)
3440         {
3441           complaint (&symfile_complaints,
3442                      _(".gdb_index address table has invalid range (%s - %s)"),
3443                      hex_string (lo), hex_string (hi));
3444           continue;
3445         }
3446
3447       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3448         {
3449           complaint (&symfile_complaints,
3450                      _(".gdb_index address table has invalid CU number %u"),
3451                      (unsigned) cu_index);
3452           continue;
3453         }
3454
3455       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3456       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3457       addrmap_set_empty (mutable_map, lo, hi - 1,
3458                          dw2_get_cutu (dwarf2_per_objfile, cu_index));
3459     }
3460
3461   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3462                                                     &objfile->objfile_obstack);
3463 }
3464
3465 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3466    populate the objfile's psymtabs_addrmap.  */
3467
3468 static void
3469 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3470                              struct dwarf2_section_info *section)
3471 {
3472   struct objfile *objfile = dwarf2_per_objfile->objfile;
3473   bfd *abfd = objfile->obfd;
3474   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3475   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3476                                        SECT_OFF_TEXT (objfile));
3477
3478   auto_obstack temp_obstack;
3479   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3480
3481   std::unordered_map<sect_offset,
3482                      dwarf2_per_cu_data *,
3483                      gdb::hash_enum<sect_offset>>
3484     debug_info_offset_to_per_cu;
3485   for (int cui = 0; cui < dwarf2_per_objfile->n_comp_units; ++cui)
3486     {
3487       dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, cui);
3488       const auto insertpair
3489         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3490       if (!insertpair.second)
3491         {
3492           warning (_("Section .debug_aranges in %s has duplicate "
3493                      "debug_info_offset %u, ignoring .debug_aranges."),
3494                    objfile_name (objfile), to_underlying (per_cu->sect_off));
3495           return;
3496         }
3497     }
3498
3499   dwarf2_read_section (objfile, section);
3500
3501   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3502
3503   const gdb_byte *addr = section->buffer;
3504
3505   while (addr < section->buffer + section->size)
3506     {
3507       const gdb_byte *const entry_addr = addr;
3508       unsigned int bytes_read;
3509
3510       const LONGEST entry_length = read_initial_length (abfd, addr,
3511                                                         &bytes_read);
3512       addr += bytes_read;
3513
3514       const gdb_byte *const entry_end = addr + entry_length;
3515       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3516       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3517       if (addr + entry_length > section->buffer + section->size)
3518         {
3519           warning (_("Section .debug_aranges in %s entry at offset %zu "
3520                      "length %s exceeds section length %s, "
3521                      "ignoring .debug_aranges."),
3522                    objfile_name (objfile), entry_addr - section->buffer,
3523                    plongest (bytes_read + entry_length),
3524                    pulongest (section->size));
3525           return;
3526         }
3527
3528       /* The version number.  */
3529       const uint16_t version = read_2_bytes (abfd, addr);
3530       addr += 2;
3531       if (version != 2)
3532         {
3533           warning (_("Section .debug_aranges in %s entry at offset %zu "
3534                      "has unsupported version %d, ignoring .debug_aranges."),
3535                    objfile_name (objfile), entry_addr - section->buffer,
3536                    version);
3537           return;
3538         }
3539
3540       const uint64_t debug_info_offset
3541         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3542       addr += offset_size;
3543       const auto per_cu_it
3544         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3545       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3546         {
3547           warning (_("Section .debug_aranges in %s entry at offset %zu "
3548                      "debug_info_offset %s does not exists, "
3549                      "ignoring .debug_aranges."),
3550                    objfile_name (objfile), entry_addr - section->buffer,
3551                    pulongest (debug_info_offset));
3552           return;
3553         }
3554       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3555
3556       const uint8_t address_size = *addr++;
3557       if (address_size < 1 || address_size > 8)
3558         {
3559           warning (_("Section .debug_aranges in %s entry at offset %zu "
3560                      "address_size %u is invalid, ignoring .debug_aranges."),
3561                    objfile_name (objfile), entry_addr - section->buffer,
3562                    address_size);
3563           return;
3564         }
3565
3566       const uint8_t segment_selector_size = *addr++;
3567       if (segment_selector_size != 0)
3568         {
3569           warning (_("Section .debug_aranges in %s entry at offset %zu "
3570                      "segment_selector_size %u is not supported, "
3571                      "ignoring .debug_aranges."),
3572                    objfile_name (objfile), entry_addr - section->buffer,
3573                    segment_selector_size);
3574           return;
3575         }
3576
3577       /* Must pad to an alignment boundary that is twice the address
3578          size.  It is undocumented by the DWARF standard but GCC does
3579          use it.  */
3580       for (size_t padding = ((-(addr - section->buffer))
3581                              & (2 * address_size - 1));
3582            padding > 0; padding--)
3583         if (*addr++ != 0)
3584           {
3585             warning (_("Section .debug_aranges in %s entry at offset %zu "
3586                        "padding is not zero, ignoring .debug_aranges."),
3587                      objfile_name (objfile), entry_addr - section->buffer);
3588             return;
3589           }
3590
3591       for (;;)
3592         {
3593           if (addr + 2 * address_size > entry_end)
3594             {
3595               warning (_("Section .debug_aranges in %s entry at offset %zu "
3596                          "address list is not properly terminated, "
3597                          "ignoring .debug_aranges."),
3598                        objfile_name (objfile), entry_addr - section->buffer);
3599               return;
3600             }
3601           ULONGEST start = extract_unsigned_integer (addr, address_size,
3602                                                      dwarf5_byte_order);
3603           addr += address_size;
3604           ULONGEST length = extract_unsigned_integer (addr, address_size,
3605                                                       dwarf5_byte_order);
3606           addr += address_size;
3607           if (start == 0 && length == 0)
3608             break;
3609           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3610             {
3611               /* Symbol was eliminated due to a COMDAT group.  */
3612               continue;
3613             }
3614           ULONGEST end = start + length;
3615           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3616           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3617           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3618         }
3619     }
3620
3621   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3622                                                     &objfile->objfile_obstack);
3623 }
3624
3625 /* The hash function for strings in the mapped index.  This is the same as
3626    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3627    implementation.  This is necessary because the hash function is tied to the
3628    format of the mapped index file.  The hash values do not have to match with
3629    SYMBOL_HASH_NEXT.
3630    
3631    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3632
3633 static hashval_t
3634 mapped_index_string_hash (int index_version, const void *p)
3635 {
3636   const unsigned char *str = (const unsigned char *) p;
3637   hashval_t r = 0;
3638   unsigned char c;
3639
3640   while ((c = *str++) != 0)
3641     {
3642       if (index_version >= 5)
3643         c = tolower (c);
3644       r = r * 67 + c - 113;
3645     }
3646
3647   return r;
3648 }
3649
3650 /* Find a slot in the mapped index INDEX for the object named NAME.
3651    If NAME is found, set *VEC_OUT to point to the CU vector in the
3652    constant pool and return true.  If NAME cannot be found, return
3653    false.  */
3654
3655 static bool
3656 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3657                           offset_type **vec_out)
3658 {
3659   offset_type hash;
3660   offset_type slot, step;
3661   int (*cmp) (const char *, const char *);
3662
3663   gdb::unique_xmalloc_ptr<char> without_params;
3664   if (current_language->la_language == language_cplus
3665       || current_language->la_language == language_fortran
3666       || current_language->la_language == language_d)
3667     {
3668       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3669          not contain any.  */
3670
3671       if (strchr (name, '(') != NULL)
3672         {
3673           without_params = cp_remove_params (name);
3674
3675           if (without_params != NULL)
3676             name = without_params.get ();
3677         }
3678     }
3679
3680   /* Index version 4 did not support case insensitive searches.  But the
3681      indices for case insensitive languages are built in lowercase, therefore
3682      simulate our NAME being searched is also lowercased.  */
3683   hash = mapped_index_string_hash ((index->version == 4
3684                                     && case_sensitivity == case_sensitive_off
3685                                     ? 5 : index->version),
3686                                    name);
3687
3688   slot = hash & (index->symbol_table.size () - 1);
3689   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3690   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3691
3692   for (;;)
3693     {
3694       const char *str;
3695
3696       const auto &bucket = index->symbol_table[slot];
3697       if (bucket.name == 0 && bucket.vec == 0)
3698         return false;
3699
3700       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3701       if (!cmp (name, str))
3702         {
3703           *vec_out = (offset_type *) (index->constant_pool
3704                                       + MAYBE_SWAP (bucket.vec));
3705           return true;
3706         }
3707
3708       slot = (slot + step) & (index->symbol_table.size () - 1);
3709     }
3710 }
3711
3712 /* A helper function that reads the .gdb_index from SECTION and fills
3713    in MAP.  FILENAME is the name of the file containing the section;
3714    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3715    ok to use deprecated sections.
3716
3717    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3718    out parameters that are filled in with information about the CU and
3719    TU lists in the section.
3720
3721    Returns 1 if all went well, 0 otherwise.  */
3722
3723 static int
3724 read_index_from_section (struct objfile *objfile,
3725                          const char *filename,
3726                          int deprecated_ok,
3727                          struct dwarf2_section_info *section,
3728                          struct mapped_index *map,
3729                          const gdb_byte **cu_list,
3730                          offset_type *cu_list_elements,
3731                          const gdb_byte **types_list,
3732                          offset_type *types_list_elements)
3733 {
3734   const gdb_byte *addr;
3735   offset_type version;
3736   offset_type *metadata;
3737   int i;
3738
3739   if (dwarf2_section_empty_p (section))
3740     return 0;
3741
3742   /* Older elfutils strip versions could keep the section in the main
3743      executable while splitting it for the separate debug info file.  */
3744   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3745     return 0;
3746
3747   dwarf2_read_section (objfile, section);
3748
3749   addr = section->buffer;
3750   /* Version check.  */
3751   version = MAYBE_SWAP (*(offset_type *) addr);
3752   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3753      causes the index to behave very poorly for certain requests.  Version 3
3754      contained incomplete addrmap.  So, it seems better to just ignore such
3755      indices.  */
3756   if (version < 4)
3757     {
3758       static int warning_printed = 0;
3759       if (!warning_printed)
3760         {
3761           warning (_("Skipping obsolete .gdb_index section in %s."),
3762                    filename);
3763           warning_printed = 1;
3764         }
3765       return 0;
3766     }
3767   /* Index version 4 uses a different hash function than index version
3768      5 and later.
3769
3770      Versions earlier than 6 did not emit psymbols for inlined
3771      functions.  Using these files will cause GDB not to be able to
3772      set breakpoints on inlined functions by name, so we ignore these
3773      indices unless the user has done
3774      "set use-deprecated-index-sections on".  */
3775   if (version < 6 && !deprecated_ok)
3776     {
3777       static int warning_printed = 0;
3778       if (!warning_printed)
3779         {
3780           warning (_("\
3781 Skipping deprecated .gdb_index section in %s.\n\
3782 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3783 to use the section anyway."),
3784                    filename);
3785           warning_printed = 1;
3786         }
3787       return 0;
3788     }
3789   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3790      of the TU (for symbols coming from TUs),
3791      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3792      Plus gold-generated indices can have duplicate entries for global symbols,
3793      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3794      These are just performance bugs, and we can't distinguish gdb-generated
3795      indices from gold-generated ones, so issue no warning here.  */
3796
3797   /* Indexes with higher version than the one supported by GDB may be no
3798      longer backward compatible.  */
3799   if (version > 8)
3800     return 0;
3801
3802   map->version = version;
3803   map->total_size = section->size;
3804
3805   metadata = (offset_type *) (addr + sizeof (offset_type));
3806
3807   i = 0;
3808   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3809   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3810                        / 8);
3811   ++i;
3812
3813   *types_list = addr + MAYBE_SWAP (metadata[i]);
3814   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3815                            - MAYBE_SWAP (metadata[i]))
3816                           / 8);
3817   ++i;
3818
3819   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3820   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3821   map->address_table
3822     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3823   ++i;
3824
3825   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3826   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3827   map->symbol_table
3828     = gdb::array_view<mapped_index::symbol_table_slot>
3829        ((mapped_index::symbol_table_slot *) symbol_table,
3830         (mapped_index::symbol_table_slot *) symbol_table_end);
3831
3832   ++i;
3833   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3834
3835   return 1;
3836 }
3837
3838 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3839    elements of all the CUs and return 1.  Otherwise, return 0.  */
3840
3841 static int
3842 dwarf2_read_index (struct objfile *objfile)
3843 {
3844   struct mapped_index local_map, *map;
3845   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3846   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3847   struct dwz_file *dwz;
3848   struct dwarf2_per_objfile *dwarf2_per_objfile
3849     = get_dwarf2_per_objfile (objfile);
3850
3851   if (!read_index_from_section (objfile, objfile_name (objfile),
3852                                 use_deprecated_index_sections,
3853                                 &dwarf2_per_objfile->gdb_index, &local_map,
3854                                 &cu_list, &cu_list_elements,
3855                                 &types_list, &types_list_elements))
3856     return 0;
3857
3858   /* Don't use the index if it's empty.  */
3859   if (local_map.symbol_table.empty ())
3860     return 0;
3861
3862   /* If there is a .dwz file, read it so we can get its CU list as
3863      well.  */
3864   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3865   if (dwz != NULL)
3866     {
3867       struct mapped_index dwz_map;
3868       const gdb_byte *dwz_types_ignore;
3869       offset_type dwz_types_elements_ignore;
3870
3871       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3872                                     1,
3873                                     &dwz->gdb_index, &dwz_map,
3874                                     &dwz_list, &dwz_list_elements,
3875                                     &dwz_types_ignore,
3876                                     &dwz_types_elements_ignore))
3877         {
3878           warning (_("could not read '.gdb_index' section from %s; skipping"),
3879                    bfd_get_filename (dwz->dwz_bfd));
3880           return 0;
3881         }
3882     }
3883
3884   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3885                          dwz_list_elements);
3886
3887   if (types_list_elements)
3888     {
3889       struct dwarf2_section_info *section;
3890
3891       /* We can only handle a single .debug_types when we have an
3892          index.  */
3893       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3894         return 0;
3895
3896       section = VEC_index (dwarf2_section_info_def,
3897                            dwarf2_per_objfile->types, 0);
3898
3899       create_signatured_type_table_from_index (objfile, section, types_list,
3900                                                types_list_elements);
3901     }
3902
3903   create_addrmap_from_index (dwarf2_per_objfile, &local_map);
3904
3905   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3906   map = new (map) mapped_index ();
3907   *map = local_map;
3908
3909   dwarf2_per_objfile->index_table = map;
3910   dwarf2_per_objfile->using_index = 1;
3911   dwarf2_per_objfile->quick_file_names_table =
3912     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3913
3914   return 1;
3915 }
3916
3917 /* die_reader_func for dw2_get_file_names.  */
3918
3919 static void
3920 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3921                            const gdb_byte *info_ptr,
3922                            struct die_info *comp_unit_die,
3923                            int has_children,
3924                            void *data)
3925 {
3926   struct dwarf2_cu *cu = reader->cu;
3927   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3928   struct dwarf2_per_objfile *dwarf2_per_objfile
3929     = cu->per_cu->dwarf2_per_objfile;
3930   struct objfile *objfile = dwarf2_per_objfile->objfile;
3931   struct dwarf2_per_cu_data *lh_cu;
3932   struct attribute *attr;
3933   int i;
3934   void **slot;
3935   struct quick_file_names *qfn;
3936
3937   gdb_assert (! this_cu->is_debug_types);
3938
3939   /* Our callers never want to match partial units -- instead they
3940      will match the enclosing full CU.  */
3941   if (comp_unit_die->tag == DW_TAG_partial_unit)
3942     {
3943       this_cu->v.quick->no_file_data = 1;
3944       return;
3945     }
3946
3947   lh_cu = this_cu;
3948   slot = NULL;
3949
3950   line_header_up lh;
3951   sect_offset line_offset {};
3952
3953   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3954   if (attr)
3955     {
3956       struct quick_file_names find_entry;
3957
3958       line_offset = (sect_offset) DW_UNSND (attr);
3959
3960       /* We may have already read in this line header (TU line header sharing).
3961          If we have we're done.  */
3962       find_entry.hash.dwo_unit = cu->dwo_unit;
3963       find_entry.hash.line_sect_off = line_offset;
3964       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3965                              &find_entry, INSERT);
3966       if (*slot != NULL)
3967         {
3968           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3969           return;
3970         }
3971
3972       lh = dwarf_decode_line_header (line_offset, cu);
3973     }
3974   if (lh == NULL)
3975     {
3976       lh_cu->v.quick->no_file_data = 1;
3977       return;
3978     }
3979
3980   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3981   qfn->hash.dwo_unit = cu->dwo_unit;
3982   qfn->hash.line_sect_off = line_offset;
3983   gdb_assert (slot != NULL);
3984   *slot = qfn;
3985
3986   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3987
3988   qfn->num_file_names = lh->file_names.size ();
3989   qfn->file_names =
3990     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3991   for (i = 0; i < lh->file_names.size (); ++i)
3992     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3993   qfn->real_names = NULL;
3994
3995   lh_cu->v.quick->file_names = qfn;
3996 }
3997
3998 /* A helper for the "quick" functions which attempts to read the line
3999    table for THIS_CU.  */
4000
4001 static struct quick_file_names *
4002 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
4003 {
4004   /* This should never be called for TUs.  */
4005   gdb_assert (! this_cu->is_debug_types);
4006   /* Nor type unit groups.  */
4007   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
4008
4009   if (this_cu->v.quick->file_names != NULL)
4010     return this_cu->v.quick->file_names;
4011   /* If we know there is no line data, no point in looking again.  */
4012   if (this_cu->v.quick->no_file_data)
4013     return NULL;
4014
4015   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
4016
4017   if (this_cu->v.quick->no_file_data)
4018     return NULL;
4019   return this_cu->v.quick->file_names;
4020 }
4021
4022 /* A helper for the "quick" functions which computes and caches the
4023    real path for a given file name from the line table.  */
4024
4025 static const char *
4026 dw2_get_real_path (struct objfile *objfile,
4027                    struct quick_file_names *qfn, int index)
4028 {
4029   if (qfn->real_names == NULL)
4030     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
4031                                       qfn->num_file_names, const char *);
4032
4033   if (qfn->real_names[index] == NULL)
4034     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
4035
4036   return qfn->real_names[index];
4037 }
4038
4039 static struct symtab *
4040 dw2_find_last_source_symtab (struct objfile *objfile)
4041 {
4042   struct dwarf2_per_objfile *dwarf2_per_objfile
4043     = get_dwarf2_per_objfile (objfile);
4044   int index = dwarf2_per_objfile->n_comp_units - 1;
4045   dwarf2_per_cu_data *dwarf_cu = dw2_get_cutu (dwarf2_per_objfile, index);
4046   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu);
4047
4048   if (cust == NULL)
4049     return NULL;
4050
4051   return compunit_primary_filetab (cust);
4052 }
4053
4054 /* Traversal function for dw2_forget_cached_source_info.  */
4055
4056 static int
4057 dw2_free_cached_file_names (void **slot, void *info)
4058 {
4059   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
4060
4061   if (file_data->real_names)
4062     {
4063       int i;
4064
4065       for (i = 0; i < file_data->num_file_names; ++i)
4066         {
4067           xfree ((void*) file_data->real_names[i]);
4068           file_data->real_names[i] = NULL;
4069         }
4070     }
4071
4072   return 1;
4073 }
4074
4075 static void
4076 dw2_forget_cached_source_info (struct objfile *objfile)
4077 {
4078   struct dwarf2_per_objfile *dwarf2_per_objfile
4079     = get_dwarf2_per_objfile (objfile);
4080
4081   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
4082                           dw2_free_cached_file_names, NULL);
4083 }
4084
4085 /* Helper function for dw2_map_symtabs_matching_filename that expands
4086    the symtabs and calls the iterator.  */
4087
4088 static int
4089 dw2_map_expand_apply (struct objfile *objfile,
4090                       struct dwarf2_per_cu_data *per_cu,
4091                       const char *name, const char *real_path,
4092                       gdb::function_view<bool (symtab *)> callback)
4093 {
4094   struct compunit_symtab *last_made = objfile->compunit_symtabs;
4095
4096   /* Don't visit already-expanded CUs.  */
4097   if (per_cu->v.quick->compunit_symtab)
4098     return 0;
4099
4100   /* This may expand more than one symtab, and we want to iterate over
4101      all of them.  */
4102   dw2_instantiate_symtab (per_cu);
4103
4104   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
4105                                     last_made, callback);
4106 }
4107
4108 /* Implementation of the map_symtabs_matching_filename method.  */
4109
4110 static bool
4111 dw2_map_symtabs_matching_filename
4112   (struct objfile *objfile, const char *name, const char *real_path,
4113    gdb::function_view<bool (symtab *)> callback)
4114 {
4115   int i;
4116   const char *name_basename = lbasename (name);
4117   struct dwarf2_per_objfile *dwarf2_per_objfile
4118     = get_dwarf2_per_objfile (objfile);
4119
4120   /* The rule is CUs specify all the files, including those used by
4121      any TU, so there's no need to scan TUs here.  */
4122
4123   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4124     {
4125       int j;
4126       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
4127       struct quick_file_names *file_data;
4128
4129       /* We only need to look at symtabs not already expanded.  */
4130       if (per_cu->v.quick->compunit_symtab)
4131         continue;
4132
4133       file_data = dw2_get_file_names (per_cu);
4134       if (file_data == NULL)
4135         continue;
4136
4137       for (j = 0; j < file_data->num_file_names; ++j)
4138         {
4139           const char *this_name = file_data->file_names[j];
4140           const char *this_real_name;
4141
4142           if (compare_filenames_for_search (this_name, name))
4143             {
4144               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4145                                         callback))
4146                 return true;
4147               continue;
4148             }
4149
4150           /* Before we invoke realpath, which can get expensive when many
4151              files are involved, do a quick comparison of the basenames.  */
4152           if (! basenames_may_differ
4153               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
4154             continue;
4155
4156           this_real_name = dw2_get_real_path (objfile, file_data, j);
4157           if (compare_filenames_for_search (this_real_name, name))
4158             {
4159               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4160                                         callback))
4161                 return true;
4162               continue;
4163             }
4164
4165           if (real_path != NULL)
4166             {
4167               gdb_assert (IS_ABSOLUTE_PATH (real_path));
4168               gdb_assert (IS_ABSOLUTE_PATH (name));
4169               if (this_real_name != NULL
4170                   && FILENAME_CMP (real_path, this_real_name) == 0)
4171                 {
4172                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
4173                                             callback))
4174                     return true;
4175                   continue;
4176                 }
4177             }
4178         }
4179     }
4180
4181   return false;
4182 }
4183
4184 /* Struct used to manage iterating over all CUs looking for a symbol.  */
4185
4186 struct dw2_symtab_iterator
4187 {
4188   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
4189   struct dwarf2_per_objfile *dwarf2_per_objfile;
4190   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
4191   int want_specific_block;
4192   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
4193      Unused if !WANT_SPECIFIC_BLOCK.  */
4194   int block_index;
4195   /* The kind of symbol we're looking for.  */
4196   domain_enum domain;
4197   /* The list of CUs from the index entry of the symbol,
4198      or NULL if not found.  */
4199   offset_type *vec;
4200   /* The next element in VEC to look at.  */
4201   int next;
4202   /* The number of elements in VEC, or zero if there is no match.  */
4203   int length;
4204   /* Have we seen a global version of the symbol?
4205      If so we can ignore all further global instances.
4206      This is to work around gold/15646, inefficient gold-generated
4207      indices.  */
4208   int global_seen;
4209 };
4210
4211 /* Initialize the index symtab iterator ITER.
4212    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
4213    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
4214
4215 static void
4216 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
4217                       struct dwarf2_per_objfile *dwarf2_per_objfile,
4218                       int want_specific_block,
4219                       int block_index,
4220                       domain_enum domain,
4221                       const char *name)
4222 {
4223   iter->dwarf2_per_objfile = dwarf2_per_objfile;
4224   iter->want_specific_block = want_specific_block;
4225   iter->block_index = block_index;
4226   iter->domain = domain;
4227   iter->next = 0;
4228   iter->global_seen = 0;
4229
4230   mapped_index *index = dwarf2_per_objfile->index_table;
4231
4232   /* index is NULL if OBJF_READNOW.  */
4233   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
4234     iter->length = MAYBE_SWAP (*iter->vec);
4235   else
4236     {
4237       iter->vec = NULL;
4238       iter->length = 0;
4239     }
4240 }
4241
4242 /* Return the next matching CU or NULL if there are no more.  */
4243
4244 static struct dwarf2_per_cu_data *
4245 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
4246 {
4247   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
4248
4249   for ( ; iter->next < iter->length; ++iter->next)
4250     {
4251       offset_type cu_index_and_attrs =
4252         MAYBE_SWAP (iter->vec[iter->next + 1]);
4253       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4254       struct dwarf2_per_cu_data *per_cu;
4255       int want_static = iter->block_index != GLOBAL_BLOCK;
4256       /* This value is only valid for index versions >= 7.  */
4257       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4258       gdb_index_symbol_kind symbol_kind =
4259         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4260       /* Only check the symbol attributes if they're present.
4261          Indices prior to version 7 don't record them,
4262          and indices >= 7 may elide them for certain symbols
4263          (gold does this).  */
4264       int attrs_valid =
4265         (dwarf2_per_objfile->index_table->version >= 7
4266          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4267
4268       /* Don't crash on bad data.  */
4269       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4270                        + dwarf2_per_objfile->n_type_units))
4271         {
4272           complaint (&symfile_complaints,
4273                      _(".gdb_index entry has bad CU index"
4274                        " [in module %s]"),
4275                      objfile_name (dwarf2_per_objfile->objfile));
4276           continue;
4277         }
4278
4279       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
4280
4281       /* Skip if already read in.  */
4282       if (per_cu->v.quick->compunit_symtab)
4283         continue;
4284
4285       /* Check static vs global.  */
4286       if (attrs_valid)
4287         {
4288           if (iter->want_specific_block
4289               && want_static != is_static)
4290             continue;
4291           /* Work around gold/15646.  */
4292           if (!is_static && iter->global_seen)
4293             continue;
4294           if (!is_static)
4295             iter->global_seen = 1;
4296         }
4297
4298       /* Only check the symbol's kind if it has one.  */
4299       if (attrs_valid)
4300         {
4301           switch (iter->domain)
4302             {
4303             case VAR_DOMAIN:
4304               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4305                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4306                   /* Some types are also in VAR_DOMAIN.  */
4307                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4308                 continue;
4309               break;
4310             case STRUCT_DOMAIN:
4311               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4312                 continue;
4313               break;
4314             case LABEL_DOMAIN:
4315               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4316                 continue;
4317               break;
4318             default:
4319               break;
4320             }
4321         }
4322
4323       ++iter->next;
4324       return per_cu;
4325     }
4326
4327   return NULL;
4328 }
4329
4330 static struct compunit_symtab *
4331 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4332                    const char *name, domain_enum domain)
4333 {
4334   struct compunit_symtab *stab_best = NULL;
4335   struct dwarf2_per_objfile *dwarf2_per_objfile
4336     = get_dwarf2_per_objfile (objfile);
4337
4338   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4339
4340   struct dw2_symtab_iterator iter;
4341   struct dwarf2_per_cu_data *per_cu;
4342
4343   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4344
4345   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4346     {
4347       struct symbol *sym, *with_opaque = NULL;
4348       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
4349       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4350       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4351
4352       sym = block_find_symbol (block, name, domain,
4353                                block_find_non_opaque_type_preferred,
4354                                &with_opaque);
4355
4356       /* Some caution must be observed with overloaded functions
4357          and methods, since the index will not contain any overload
4358          information (but NAME might contain it).  */
4359
4360       if (sym != NULL
4361           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4362         return stab;
4363       if (with_opaque != NULL
4364           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4365         stab_best = stab;
4366
4367       /* Keep looking through other CUs.  */
4368     }
4369
4370   return stab_best;
4371 }
4372
4373 static void
4374 dw2_print_stats (struct objfile *objfile)
4375 {
4376   struct dwarf2_per_objfile *dwarf2_per_objfile
4377     = get_dwarf2_per_objfile (objfile);
4378   int total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4379   int count = 0;
4380
4381   for (int i = 0; i < total; ++i)
4382     {
4383       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4384
4385       if (!per_cu->v.quick->compunit_symtab)
4386         ++count;
4387     }
4388   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4389   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4390 }
4391
4392 /* This dumps minimal information about the index.
4393    It is called via "mt print objfiles".
4394    One use is to verify .gdb_index has been loaded by the
4395    gdb.dwarf2/gdb-index.exp testcase.  */
4396
4397 static void
4398 dw2_dump (struct objfile *objfile)
4399 {
4400   struct dwarf2_per_objfile *dwarf2_per_objfile
4401     = get_dwarf2_per_objfile (objfile);
4402
4403   gdb_assert (dwarf2_per_objfile->using_index);
4404   printf_filtered (".gdb_index:");
4405   if (dwarf2_per_objfile->index_table != NULL)
4406     {
4407       printf_filtered (" version %d\n",
4408                        dwarf2_per_objfile->index_table->version);
4409     }
4410   else
4411     printf_filtered (" faked for \"readnow\"\n");
4412   printf_filtered ("\n");
4413 }
4414
4415 static void
4416 dw2_relocate (struct objfile *objfile,
4417               const struct section_offsets *new_offsets,
4418               const struct section_offsets *delta)
4419 {
4420   /* There's nothing to relocate here.  */
4421 }
4422
4423 static void
4424 dw2_expand_symtabs_for_function (struct objfile *objfile,
4425                                  const char *func_name)
4426 {
4427   struct dwarf2_per_objfile *dwarf2_per_objfile
4428     = get_dwarf2_per_objfile (objfile);
4429
4430   struct dw2_symtab_iterator iter;
4431   struct dwarf2_per_cu_data *per_cu;
4432
4433   /* Note: It doesn't matter what we pass for block_index here.  */
4434   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4435                         func_name);
4436
4437   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4438     dw2_instantiate_symtab (per_cu);
4439
4440 }
4441
4442 static void
4443 dw2_expand_all_symtabs (struct objfile *objfile)
4444 {
4445   struct dwarf2_per_objfile *dwarf2_per_objfile
4446     = get_dwarf2_per_objfile (objfile);
4447   int total_units = (dwarf2_per_objfile->n_comp_units
4448                      + dwarf2_per_objfile->n_type_units);
4449
4450   for (int i = 0; i < total_units; ++i)
4451     {
4452       struct dwarf2_per_cu_data *per_cu
4453         = dw2_get_cutu (dwarf2_per_objfile, i);
4454
4455       dw2_instantiate_symtab (per_cu);
4456     }
4457 }
4458
4459 static void
4460 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4461                                   const char *fullname)
4462 {
4463   struct dwarf2_per_objfile *dwarf2_per_objfile
4464     = get_dwarf2_per_objfile (objfile);
4465
4466   /* We don't need to consider type units here.
4467      This is only called for examining code, e.g. expand_line_sal.
4468      There can be an order of magnitude (or more) more type units
4469      than comp units, and we avoid them if we can.  */
4470
4471   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4472     {
4473       int j;
4474       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
4475       struct quick_file_names *file_data;
4476
4477       /* We only need to look at symtabs not already expanded.  */
4478       if (per_cu->v.quick->compunit_symtab)
4479         continue;
4480
4481       file_data = dw2_get_file_names (per_cu);
4482       if (file_data == NULL)
4483         continue;
4484
4485       for (j = 0; j < file_data->num_file_names; ++j)
4486         {
4487           const char *this_fullname = file_data->file_names[j];
4488
4489           if (filename_cmp (this_fullname, fullname) == 0)
4490             {
4491               dw2_instantiate_symtab (per_cu);
4492               break;
4493             }
4494         }
4495     }
4496 }
4497
4498 static void
4499 dw2_map_matching_symbols (struct objfile *objfile,
4500                           const char * name, domain_enum domain,
4501                           int global,
4502                           int (*callback) (struct block *,
4503                                            struct symbol *, void *),
4504                           void *data, symbol_name_match_type match,
4505                           symbol_compare_ftype *ordered_compare)
4506 {
4507   /* Currently unimplemented; used for Ada.  The function can be called if the
4508      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4509      does not look for non-Ada symbols this function should just return.  */
4510 }
4511
4512 /* Symbol name matcher for .gdb_index names.
4513
4514    Symbol names in .gdb_index have a few particularities:
4515
4516    - There's no indication of which is the language of each symbol.
4517
4518      Since each language has its own symbol name matching algorithm,
4519      and we don't know which language is the right one, we must match
4520      each symbol against all languages.  This would be a potential
4521      performance problem if it were not mitigated by the
4522      mapped_index::name_components lookup table, which significantly
4523      reduces the number of times we need to call into this matcher,
4524      making it a non-issue.
4525
4526    - Symbol names in the index have no overload (parameter)
4527      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4528      appear as "foo" in the index, for example.
4529
4530      This means that the lookup names passed to the symbol name
4531      matcher functions must have no parameter information either
4532      because (e.g.) symbol search name "foo" does not match
4533      lookup-name "foo(int)" [while swapping search name for lookup
4534      name would match].
4535 */
4536 class gdb_index_symbol_name_matcher
4537 {
4538 public:
4539   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4540   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4541
4542   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4543      Returns true if any matcher matches.  */
4544   bool matches (const char *symbol_name);
4545
4546 private:
4547   /* A reference to the lookup name we're matching against.  */
4548   const lookup_name_info &m_lookup_name;
4549
4550   /* A vector holding all the different symbol name matchers, for all
4551      languages.  */
4552   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4553 };
4554
4555 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4556   (const lookup_name_info &lookup_name)
4557     : m_lookup_name (lookup_name)
4558 {
4559   /* Prepare the vector of comparison functions upfront, to avoid
4560      doing the same work for each symbol.  Care is taken to avoid
4561      matching with the same matcher more than once if/when multiple
4562      languages use the same matcher function.  */
4563   auto &matchers = m_symbol_name_matcher_funcs;
4564   matchers.reserve (nr_languages);
4565
4566   matchers.push_back (default_symbol_name_matcher);
4567
4568   for (int i = 0; i < nr_languages; i++)
4569     {
4570       const language_defn *lang = language_def ((enum language) i);
4571       symbol_name_matcher_ftype *name_matcher
4572         = get_symbol_name_matcher (lang, m_lookup_name);
4573
4574       /* Don't insert the same comparison routine more than once.
4575          Note that we do this linear walk instead of a seemingly
4576          cheaper sorted insert, or use a std::set or something like
4577          that, because relative order of function addresses is not
4578          stable.  This is not a problem in practice because the number
4579          of supported languages is low, and the cost here is tiny
4580          compared to the number of searches we'll do afterwards using
4581          this object.  */
4582       if (name_matcher != default_symbol_name_matcher
4583           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4584               == matchers.end ()))
4585         matchers.push_back (name_matcher);
4586     }
4587 }
4588
4589 bool
4590 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4591 {
4592   for (auto matches_name : m_symbol_name_matcher_funcs)
4593     if (matches_name (symbol_name, m_lookup_name, NULL))
4594       return true;
4595
4596   return false;
4597 }
4598
4599 /* Starting from a search name, return the string that finds the upper
4600    bound of all strings that start with SEARCH_NAME in a sorted name
4601    list.  Returns the empty string to indicate that the upper bound is
4602    the end of the list.  */
4603
4604 static std::string
4605 make_sort_after_prefix_name (const char *search_name)
4606 {
4607   /* When looking to complete "func", we find the upper bound of all
4608      symbols that start with "func" by looking for where we'd insert
4609      the closest string that would follow "func" in lexicographical
4610      order.  Usually, that's "func"-with-last-character-incremented,
4611      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4612      will be UTF-8 multi-byte sequences, but we can't be certain.
4613      Especially mind the 0xff character, which is a valid character in
4614      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4615      rule out compilers allowing it in identifiers.  Note that
4616      conveniently, strcmp/strcasecmp are specified to compare
4617      characters interpreted as unsigned char.  So what we do is treat
4618      the whole string as a base 256 number composed of a sequence of
4619      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4620      to 0, and carries 1 to the following more-significant position.
4621      If the very first character in SEARCH_NAME ends up incremented
4622      and carries/overflows, then the upper bound is the end of the
4623      list.  The string after the empty string is also the empty
4624      string.
4625
4626      Some examples of this operation:
4627
4628        SEARCH_NAME  => "+1" RESULT
4629
4630        "abc"              => "abd"
4631        "ab\xff"           => "ac"
4632        "\xff" "a" "\xff"  => "\xff" "b"
4633        "\xff"             => ""
4634        "\xff\xff"         => ""
4635        ""                 => ""
4636
4637      Then, with these symbols for example:
4638
4639       func
4640       func1
4641       fund
4642
4643      completing "func" looks for symbols between "func" and
4644      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4645      which finds "func" and "func1", but not "fund".
4646
4647      And with:
4648
4649       funcÿ     (Latin1 'ÿ' [0xff])
4650       funcÿ1
4651       fund
4652
4653      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4654      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4655
4656      And with:
4657
4658       ÿÿ        (Latin1 'ÿ' [0xff])
4659       ÿÿ1
4660
4661      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4662      the end of the list.
4663   */
4664   std::string after = search_name;
4665   while (!after.empty () && (unsigned char) after.back () == 0xff)
4666     after.pop_back ();
4667   if (!after.empty ())
4668     after.back () = (unsigned char) after.back () + 1;
4669   return after;
4670 }
4671
4672 /* See declaration.  */
4673
4674 std::pair<std::vector<name_component>::const_iterator,
4675           std::vector<name_component>::const_iterator>
4676 mapped_index_base::find_name_components_bounds
4677   (const lookup_name_info &lookup_name_without_params) const
4678 {
4679   auto *name_cmp
4680     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4681
4682   const char *cplus
4683     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4684
4685   /* Comparison function object for lower_bound that matches against a
4686      given symbol name.  */
4687   auto lookup_compare_lower = [&] (const name_component &elem,
4688                                    const char *name)
4689     {
4690       const char *elem_qualified = this->symbol_name_at (elem.idx);
4691       const char *elem_name = elem_qualified + elem.name_offset;
4692       return name_cmp (elem_name, name) < 0;
4693     };
4694
4695   /* Comparison function object for upper_bound that matches against a
4696      given symbol name.  */
4697   auto lookup_compare_upper = [&] (const char *name,
4698                                    const name_component &elem)
4699     {
4700       const char *elem_qualified = this->symbol_name_at (elem.idx);
4701       const char *elem_name = elem_qualified + elem.name_offset;
4702       return name_cmp (name, elem_name) < 0;
4703     };
4704
4705   auto begin = this->name_components.begin ();
4706   auto end = this->name_components.end ();
4707
4708   /* Find the lower bound.  */
4709   auto lower = [&] ()
4710     {
4711       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4712         return begin;
4713       else
4714         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4715     } ();
4716
4717   /* Find the upper bound.  */
4718   auto upper = [&] ()
4719     {
4720       if (lookup_name_without_params.completion_mode ())
4721         {
4722           /* In completion mode, we want UPPER to point past all
4723              symbols names that have the same prefix.  I.e., with
4724              these symbols, and completing "func":
4725
4726               function        << lower bound
4727               function1
4728               other_function  << upper bound
4729
4730              We find the upper bound by looking for the insertion
4731              point of "func"-with-last-character-incremented,
4732              i.e. "fund".  */
4733           std::string after = make_sort_after_prefix_name (cplus);
4734           if (after.empty ())
4735             return end;
4736           return std::lower_bound (lower, end, after.c_str (),
4737                                    lookup_compare_lower);
4738         }
4739       else
4740         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4741     } ();
4742
4743   return {lower, upper};
4744 }
4745
4746 /* See declaration.  */
4747
4748 void
4749 mapped_index_base::build_name_components ()
4750 {
4751   if (!this->name_components.empty ())
4752     return;
4753
4754   this->name_components_casing = case_sensitivity;
4755   auto *name_cmp
4756     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4757
4758   /* The code below only knows how to break apart components of C++
4759      symbol names (and other languages that use '::' as
4760      namespace/module separator).  If we add support for wild matching
4761      to some language that uses some other operator (E.g., Ada, Go and
4762      D use '.'), then we'll need to try splitting the symbol name
4763      according to that language too.  Note that Ada does support wild
4764      matching, but doesn't currently support .gdb_index.  */
4765   auto count = this->symbol_name_count ();
4766   for (offset_type idx = 0; idx < count; idx++)
4767     {
4768       if (this->symbol_name_slot_invalid (idx))
4769         continue;
4770
4771       const char *name = this->symbol_name_at (idx);
4772
4773       /* Add each name component to the name component table.  */
4774       unsigned int previous_len = 0;
4775       for (unsigned int current_len = cp_find_first_component (name);
4776            name[current_len] != '\0';
4777            current_len += cp_find_first_component (name + current_len))
4778         {
4779           gdb_assert (name[current_len] == ':');
4780           this->name_components.push_back ({previous_len, idx});
4781           /* Skip the '::'.  */
4782           current_len += 2;
4783           previous_len = current_len;
4784         }
4785       this->name_components.push_back ({previous_len, idx});
4786     }
4787
4788   /* Sort name_components elements by name.  */
4789   auto name_comp_compare = [&] (const name_component &left,
4790                                 const name_component &right)
4791     {
4792       const char *left_qualified = this->symbol_name_at (left.idx);
4793       const char *right_qualified = this->symbol_name_at (right.idx);
4794
4795       const char *left_name = left_qualified + left.name_offset;
4796       const char *right_name = right_qualified + right.name_offset;
4797
4798       return name_cmp (left_name, right_name) < 0;
4799     };
4800
4801   std::sort (this->name_components.begin (),
4802              this->name_components.end (),
4803              name_comp_compare);
4804 }
4805
4806 /* Helper for dw2_expand_symtabs_matching that works with a
4807    mapped_index_base instead of the containing objfile.  This is split
4808    to a separate function in order to be able to unit test the
4809    name_components matching using a mock mapped_index_base.  For each
4810    symbol name that matches, calls MATCH_CALLBACK, passing it the
4811    symbol's index in the mapped_index_base symbol table.  */
4812
4813 static void
4814 dw2_expand_symtabs_matching_symbol
4815   (mapped_index_base &index,
4816    const lookup_name_info &lookup_name_in,
4817    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4818    enum search_domain kind,
4819    gdb::function_view<void (offset_type)> match_callback)
4820 {
4821   lookup_name_info lookup_name_without_params
4822     = lookup_name_in.make_ignore_params ();
4823   gdb_index_symbol_name_matcher lookup_name_matcher
4824     (lookup_name_without_params);
4825
4826   /* Build the symbol name component sorted vector, if we haven't
4827      yet.  */
4828   index.build_name_components ();
4829
4830   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4831
4832   /* Now for each symbol name in range, check to see if we have a name
4833      match, and if so, call the MATCH_CALLBACK callback.  */
4834
4835   /* The same symbol may appear more than once in the range though.
4836      E.g., if we're looking for symbols that complete "w", and we have
4837      a symbol named "w1::w2", we'll find the two name components for
4838      that same symbol in the range.  To be sure we only call the
4839      callback once per symbol, we first collect the symbol name
4840      indexes that matched in a temporary vector and ignore
4841      duplicates.  */
4842   std::vector<offset_type> matches;
4843   matches.reserve (std::distance (bounds.first, bounds.second));
4844
4845   for (; bounds.first != bounds.second; ++bounds.first)
4846     {
4847       const char *qualified = index.symbol_name_at (bounds.first->idx);
4848
4849       if (!lookup_name_matcher.matches (qualified)
4850           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4851         continue;
4852
4853       matches.push_back (bounds.first->idx);
4854     }
4855
4856   std::sort (matches.begin (), matches.end ());
4857
4858   /* Finally call the callback, once per match.  */
4859   ULONGEST prev = -1;
4860   for (offset_type idx : matches)
4861     {
4862       if (prev != idx)
4863         {
4864           match_callback (idx);
4865           prev = idx;
4866         }
4867     }
4868
4869   /* Above we use a type wider than idx's for 'prev', since 0 and
4870      (offset_type)-1 are both possible values.  */
4871   static_assert (sizeof (prev) > sizeof (offset_type), "");
4872 }
4873
4874 #if GDB_SELF_TEST
4875
4876 namespace selftests { namespace dw2_expand_symtabs_matching {
4877
4878 /* A mock .gdb_index/.debug_names-like name index table, enough to
4879    exercise dw2_expand_symtabs_matching_symbol, which works with the
4880    mapped_index_base interface.  Builds an index from the symbol list
4881    passed as parameter to the constructor.  */
4882 class mock_mapped_index : public mapped_index_base
4883 {
4884 public:
4885   mock_mapped_index (gdb::array_view<const char *> symbols)
4886     : m_symbol_table (symbols)
4887   {}
4888
4889   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4890
4891   /* Return the number of names in the symbol table.  */
4892   virtual size_t symbol_name_count () const
4893   {
4894     return m_symbol_table.size ();
4895   }
4896
4897   /* Get the name of the symbol at IDX in the symbol table.  */
4898   virtual const char *symbol_name_at (offset_type idx) const
4899   {
4900     return m_symbol_table[idx];
4901   }
4902
4903 private:
4904   gdb::array_view<const char *> m_symbol_table;
4905 };
4906
4907 /* Convenience function that converts a NULL pointer to a "<null>"
4908    string, to pass to print routines.  */
4909
4910 static const char *
4911 string_or_null (const char *str)
4912 {
4913   return str != NULL ? str : "<null>";
4914 }
4915
4916 /* Check if a lookup_name_info built from
4917    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4918    index.  EXPECTED_LIST is the list of expected matches, in expected
4919    matching order.  If no match expected, then an empty list is
4920    specified.  Returns true on success.  On failure prints a warning
4921    indicating the file:line that failed, and returns false.  */
4922
4923 static bool
4924 check_match (const char *file, int line,
4925              mock_mapped_index &mock_index,
4926              const char *name, symbol_name_match_type match_type,
4927              bool completion_mode,
4928              std::initializer_list<const char *> expected_list)
4929 {
4930   lookup_name_info lookup_name (name, match_type, completion_mode);
4931
4932   bool matched = true;
4933
4934   auto mismatch = [&] (const char *expected_str,
4935                        const char *got)
4936   {
4937     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4938                "expected=\"%s\", got=\"%s\"\n"),
4939              file, line,
4940              (match_type == symbol_name_match_type::FULL
4941               ? "FULL" : "WILD"),
4942              name, string_or_null (expected_str), string_or_null (got));
4943     matched = false;
4944   };
4945
4946   auto expected_it = expected_list.begin ();
4947   auto expected_end = expected_list.end ();
4948
4949   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4950                                       NULL, ALL_DOMAIN,
4951                                       [&] (offset_type idx)
4952   {
4953     const char *matched_name = mock_index.symbol_name_at (idx);
4954     const char *expected_str
4955       = expected_it == expected_end ? NULL : *expected_it++;
4956
4957     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4958       mismatch (expected_str, matched_name);
4959   });
4960
4961   const char *expected_str
4962   = expected_it == expected_end ? NULL : *expected_it++;
4963   if (expected_str != NULL)
4964     mismatch (expected_str, NULL);
4965
4966   return matched;
4967 }
4968
4969 /* The symbols added to the mock mapped_index for testing (in
4970    canonical form).  */
4971 static const char *test_symbols[] = {
4972   "function",
4973   "std::bar",
4974   "std::zfunction",
4975   "std::zfunction2",
4976   "w1::w2",
4977   "ns::foo<char*>",
4978   "ns::foo<int>",
4979   "ns::foo<long>",
4980   "ns2::tmpl<int>::foo2",
4981   "(anonymous namespace)::A::B::C",
4982
4983   /* These are used to check that the increment-last-char in the
4984      matching algorithm for completion doesn't match "t1_fund" when
4985      completing "t1_func".  */
4986   "t1_func",
4987   "t1_func1",
4988   "t1_fund",
4989   "t1_fund1",
4990
4991   /* A UTF-8 name with multi-byte sequences to make sure that
4992      cp-name-parser understands this as a single identifier ("função"
4993      is "function" in PT).  */
4994   u8"u8função",
4995
4996   /* \377 (0xff) is Latin1 'ÿ'.  */
4997   "yfunc\377",
4998
4999   /* \377 (0xff) is Latin1 'ÿ'.  */
5000   "\377",
5001   "\377\377123",
5002
5003   /* A name with all sorts of complications.  Starts with "z" to make
5004      it easier for the completion tests below.  */
5005 #define Z_SYM_NAME \
5006   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
5007     "::tuple<(anonymous namespace)::ui*, " \
5008     "std::default_delete<(anonymous namespace)::ui>, void>"
5009
5010   Z_SYM_NAME
5011 };
5012
5013 /* Returns true if the mapped_index_base::find_name_component_bounds
5014    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
5015    in completion mode.  */
5016
5017 static bool
5018 check_find_bounds_finds (mapped_index_base &index,
5019                          const char *search_name,
5020                          gdb::array_view<const char *> expected_syms)
5021 {
5022   lookup_name_info lookup_name (search_name,
5023                                 symbol_name_match_type::FULL, true);
5024
5025   auto bounds = index.find_name_components_bounds (lookup_name);
5026
5027   size_t distance = std::distance (bounds.first, bounds.second);
5028   if (distance != expected_syms.size ())
5029     return false;
5030
5031   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
5032     {
5033       auto nc_elem = bounds.first + exp_elem;
5034       const char *qualified = index.symbol_name_at (nc_elem->idx);
5035       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
5036         return false;
5037     }
5038
5039   return true;
5040 }
5041
5042 /* Test the lower-level mapped_index::find_name_component_bounds
5043    method.  */
5044
5045 static void
5046 test_mapped_index_find_name_component_bounds ()
5047 {
5048   mock_mapped_index mock_index (test_symbols);
5049
5050   mock_index.build_name_components ();
5051
5052   /* Test the lower-level mapped_index::find_name_component_bounds
5053      method in completion mode.  */
5054   {
5055     static const char *expected_syms[] = {
5056       "t1_func",
5057       "t1_func1",
5058     };
5059
5060     SELF_CHECK (check_find_bounds_finds (mock_index,
5061                                          "t1_func", expected_syms));
5062   }
5063
5064   /* Check that the increment-last-char in the name matching algorithm
5065      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
5066   {
5067     static const char *expected_syms1[] = {
5068       "\377",
5069       "\377\377123",
5070     };
5071     SELF_CHECK (check_find_bounds_finds (mock_index,
5072                                          "\377", expected_syms1));
5073
5074     static const char *expected_syms2[] = {
5075       "\377\377123",
5076     };
5077     SELF_CHECK (check_find_bounds_finds (mock_index,
5078                                          "\377\377", expected_syms2));
5079   }
5080 }
5081
5082 /* Test dw2_expand_symtabs_matching_symbol.  */
5083
5084 static void
5085 test_dw2_expand_symtabs_matching_symbol ()
5086 {
5087   mock_mapped_index mock_index (test_symbols);
5088
5089   /* We let all tests run until the end even if some fails, for debug
5090      convenience.  */
5091   bool any_mismatch = false;
5092
5093   /* Create the expected symbols list (an initializer_list).  Needed
5094      because lists have commas, and we need to pass them to CHECK,
5095      which is a macro.  */
5096 #define EXPECT(...) { __VA_ARGS__ }
5097
5098   /* Wrapper for check_match that passes down the current
5099      __FILE__/__LINE__.  */
5100 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
5101   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
5102                                 mock_index,                             \
5103                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
5104                                 EXPECTED_LIST)
5105
5106   /* Identity checks.  */
5107   for (const char *sym : test_symbols)
5108     {
5109       /* Should be able to match all existing symbols.  */
5110       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
5111                    EXPECT (sym));
5112
5113       /* Should be able to match all existing symbols with
5114          parameters.  */
5115       std::string with_params = std::string (sym) + "(int)";
5116       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5117                    EXPECT (sym));
5118
5119       /* Should be able to match all existing symbols with
5120          parameters and qualifiers.  */
5121       with_params = std::string (sym) + " ( int ) const";
5122       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5123                    EXPECT (sym));
5124
5125       /* This should really find sym, but cp-name-parser.y doesn't
5126          know about lvalue/rvalue qualifiers yet.  */
5127       with_params = std::string (sym) + " ( int ) &&";
5128       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
5129                    {});
5130     }
5131
5132   /* Check that the name matching algorithm for completion doesn't get
5133      confused with Latin1 'ÿ' / 0xff.  */
5134   {
5135     static const char str[] = "\377";
5136     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5137                  EXPECT ("\377", "\377\377123"));
5138   }
5139
5140   /* Check that the increment-last-char in the matching algorithm for
5141      completion doesn't match "t1_fund" when completing "t1_func".  */
5142   {
5143     static const char str[] = "t1_func";
5144     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
5145                  EXPECT ("t1_func", "t1_func1"));
5146   }
5147
5148   /* Check that completion mode works at each prefix of the expected
5149      symbol name.  */
5150   {
5151     static const char str[] = "function(int)";
5152     size_t len = strlen (str);
5153     std::string lookup;
5154
5155     for (size_t i = 1; i < len; i++)
5156       {
5157         lookup.assign (str, i);
5158         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5159                      EXPECT ("function"));
5160       }
5161   }
5162
5163   /* While "w" is a prefix of both components, the match function
5164      should still only be called once.  */
5165   {
5166     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
5167                  EXPECT ("w1::w2"));
5168     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
5169                  EXPECT ("w1::w2"));
5170   }
5171
5172   /* Same, with a "complicated" symbol.  */
5173   {
5174     static const char str[] = Z_SYM_NAME;
5175     size_t len = strlen (str);
5176     std::string lookup;
5177
5178     for (size_t i = 1; i < len; i++)
5179       {
5180         lookup.assign (str, i);
5181         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
5182                      EXPECT (Z_SYM_NAME));
5183       }
5184   }
5185
5186   /* In FULL mode, an incomplete symbol doesn't match.  */
5187   {
5188     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
5189                  {});
5190   }
5191
5192   /* A complete symbol with parameters matches any overload, since the
5193      index has no overload info.  */
5194   {
5195     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
5196                  EXPECT ("std::zfunction", "std::zfunction2"));
5197     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
5198                  EXPECT ("std::zfunction", "std::zfunction2"));
5199     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
5200                  EXPECT ("std::zfunction", "std::zfunction2"));
5201   }
5202
5203   /* Check that whitespace is ignored appropriately.  A symbol with a
5204      template argument list. */
5205   {
5206     static const char expected[] = "ns::foo<int>";
5207     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
5208                  EXPECT (expected));
5209     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
5210                  EXPECT (expected));
5211   }
5212
5213   /* Check that whitespace is ignored appropriately.  A symbol with a
5214      template argument list that includes a pointer.  */
5215   {
5216     static const char expected[] = "ns::foo<char*>";
5217     /* Try both completion and non-completion modes.  */
5218     static const bool completion_mode[2] = {false, true};
5219     for (size_t i = 0; i < 2; i++)
5220       {
5221         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
5222                      completion_mode[i], EXPECT (expected));
5223         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
5224                      completion_mode[i], EXPECT (expected));
5225
5226         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
5227                      completion_mode[i], EXPECT (expected));
5228         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
5229                      completion_mode[i], EXPECT (expected));
5230       }
5231   }
5232
5233   {
5234     /* Check method qualifiers are ignored.  */
5235     static const char expected[] = "ns::foo<char*>";
5236     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
5237                  symbol_name_match_type::FULL, true, EXPECT (expected));
5238     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
5239                  symbol_name_match_type::FULL, true, EXPECT (expected));
5240     CHECK_MATCH ("foo < char * >  ( int ) const",
5241                  symbol_name_match_type::WILD, true, EXPECT (expected));
5242     CHECK_MATCH ("foo < char * >  ( int ) &&",
5243                  symbol_name_match_type::WILD, true, EXPECT (expected));
5244   }
5245
5246   /* Test lookup names that don't match anything.  */
5247   {
5248     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
5249                  {});
5250
5251     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
5252                  {});
5253   }
5254
5255   /* Some wild matching tests, exercising "(anonymous namespace)",
5256      which should not be confused with a parameter list.  */
5257   {
5258     static const char *syms[] = {
5259       "A::B::C",
5260       "B::C",
5261       "C",
5262       "A :: B :: C ( int )",
5263       "B :: C ( int )",
5264       "C ( int )",
5265     };
5266
5267     for (const char *s : syms)
5268       {
5269         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
5270                      EXPECT ("(anonymous namespace)::A::B::C"));
5271       }
5272   }
5273
5274   {
5275     static const char expected[] = "ns2::tmpl<int>::foo2";
5276     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
5277                  EXPECT (expected));
5278     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
5279                  EXPECT (expected));
5280   }
5281
5282   SELF_CHECK (!any_mismatch);
5283
5284 #undef EXPECT
5285 #undef CHECK_MATCH
5286 }
5287
5288 static void
5289 run_test ()
5290 {
5291   test_mapped_index_find_name_component_bounds ();
5292   test_dw2_expand_symtabs_matching_symbol ();
5293 }
5294
5295 }} // namespace selftests::dw2_expand_symtabs_matching
5296
5297 #endif /* GDB_SELF_TEST */
5298
5299 /* If FILE_MATCHER is NULL or if PER_CU has
5300    dwarf2_per_cu_quick_data::MARK set (see
5301    dw_expand_symtabs_matching_file_matcher), expand the CU and call
5302    EXPANSION_NOTIFY on it.  */
5303
5304 static void
5305 dw2_expand_symtabs_matching_one
5306   (struct dwarf2_per_cu_data *per_cu,
5307    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5308    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
5309 {
5310   if (file_matcher == NULL || per_cu->v.quick->mark)
5311     {
5312       bool symtab_was_null
5313         = (per_cu->v.quick->compunit_symtab == NULL);
5314
5315       dw2_instantiate_symtab (per_cu);
5316
5317       if (expansion_notify != NULL
5318           && symtab_was_null
5319           && per_cu->v.quick->compunit_symtab != NULL)
5320         expansion_notify (per_cu->v.quick->compunit_symtab);
5321     }
5322 }
5323
5324 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5325    matched, to expand corresponding CUs that were marked.  IDX is the
5326    index of the symbol name that matched.  */
5327
5328 static void
5329 dw2_expand_marked_cus
5330   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5331    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5332    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5333    search_domain kind)
5334 {
5335   offset_type *vec, vec_len, vec_idx;
5336   bool global_seen = false;
5337   mapped_index &index = *dwarf2_per_objfile->index_table;
5338
5339   vec = (offset_type *) (index.constant_pool
5340                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5341   vec_len = MAYBE_SWAP (vec[0]);
5342   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5343     {
5344       struct dwarf2_per_cu_data *per_cu;
5345       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5346       /* This value is only valid for index versions >= 7.  */
5347       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5348       gdb_index_symbol_kind symbol_kind =
5349         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5350       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5351       /* Only check the symbol attributes if they're present.
5352          Indices prior to version 7 don't record them,
5353          and indices >= 7 may elide them for certain symbols
5354          (gold does this).  */
5355       int attrs_valid =
5356         (index.version >= 7
5357          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5358
5359       /* Work around gold/15646.  */
5360       if (attrs_valid)
5361         {
5362           if (!is_static && global_seen)
5363             continue;
5364           if (!is_static)
5365             global_seen = true;
5366         }
5367
5368       /* Only check the symbol's kind if it has one.  */
5369       if (attrs_valid)
5370         {
5371           switch (kind)
5372             {
5373             case VARIABLES_DOMAIN:
5374               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5375                 continue;
5376               break;
5377             case FUNCTIONS_DOMAIN:
5378               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5379                 continue;
5380               break;
5381             case TYPES_DOMAIN:
5382               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5383                 continue;
5384               break;
5385             default:
5386               break;
5387             }
5388         }
5389
5390       /* Don't crash on bad data.  */
5391       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5392                        + dwarf2_per_objfile->n_type_units))
5393         {
5394           complaint (&symfile_complaints,
5395                      _(".gdb_index entry has bad CU index"
5396                        " [in module %s]"),
5397                        objfile_name (dwarf2_per_objfile->objfile));
5398           continue;
5399         }
5400
5401       per_cu = dw2_get_cutu (dwarf2_per_objfile, cu_index);
5402       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5403                                        expansion_notify);
5404     }
5405 }
5406
5407 /* If FILE_MATCHER is non-NULL, set all the
5408    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5409    that match FILE_MATCHER.  */
5410
5411 static void
5412 dw_expand_symtabs_matching_file_matcher
5413   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5414    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5415 {
5416   if (file_matcher == NULL)
5417     return;
5418
5419   objfile *const objfile = dwarf2_per_objfile->objfile;
5420
5421   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5422                                             htab_eq_pointer,
5423                                             NULL, xcalloc, xfree));
5424   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5425                                                 htab_eq_pointer,
5426                                                 NULL, xcalloc, xfree));
5427
5428   /* The rule is CUs specify all the files, including those used by
5429      any TU, so there's no need to scan TUs here.  */
5430
5431   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5432     {
5433       int j;
5434       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5435       struct quick_file_names *file_data;
5436       void **slot;
5437
5438       QUIT;
5439
5440       per_cu->v.quick->mark = 0;
5441
5442       /* We only need to look at symtabs not already expanded.  */
5443       if (per_cu->v.quick->compunit_symtab)
5444         continue;
5445
5446       file_data = dw2_get_file_names (per_cu);
5447       if (file_data == NULL)
5448         continue;
5449
5450       if (htab_find (visited_not_found.get (), file_data) != NULL)
5451         continue;
5452       else if (htab_find (visited_found.get (), file_data) != NULL)
5453         {
5454           per_cu->v.quick->mark = 1;
5455           continue;
5456         }
5457
5458       for (j = 0; j < file_data->num_file_names; ++j)
5459         {
5460           const char *this_real_name;
5461
5462           if (file_matcher (file_data->file_names[j], false))
5463             {
5464               per_cu->v.quick->mark = 1;
5465               break;
5466             }
5467
5468           /* Before we invoke realpath, which can get expensive when many
5469              files are involved, do a quick comparison of the basenames.  */
5470           if (!basenames_may_differ
5471               && !file_matcher (lbasename (file_data->file_names[j]),
5472                                 true))
5473             continue;
5474
5475           this_real_name = dw2_get_real_path (objfile, file_data, j);
5476           if (file_matcher (this_real_name, false))
5477             {
5478               per_cu->v.quick->mark = 1;
5479               break;
5480             }
5481         }
5482
5483       slot = htab_find_slot (per_cu->v.quick->mark
5484                              ? visited_found.get ()
5485                              : visited_not_found.get (),
5486                              file_data, INSERT);
5487       *slot = file_data;
5488     }
5489 }
5490
5491 static void
5492 dw2_expand_symtabs_matching
5493   (struct objfile *objfile,
5494    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5495    const lookup_name_info &lookup_name,
5496    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5497    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5498    enum search_domain kind)
5499 {
5500   struct dwarf2_per_objfile *dwarf2_per_objfile
5501     = get_dwarf2_per_objfile (objfile);
5502
5503   /* index_table is NULL if OBJF_READNOW.  */
5504   if (!dwarf2_per_objfile->index_table)
5505     return;
5506
5507   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5508
5509   mapped_index &index = *dwarf2_per_objfile->index_table;
5510
5511   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5512                                       symbol_matcher,
5513                                       kind, [&] (offset_type idx)
5514     {
5515       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5516                              expansion_notify, kind);
5517     });
5518 }
5519
5520 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5521    symtab.  */
5522
5523 static struct compunit_symtab *
5524 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5525                                           CORE_ADDR pc)
5526 {
5527   int i;
5528
5529   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5530       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5531     return cust;
5532
5533   if (cust->includes == NULL)
5534     return NULL;
5535
5536   for (i = 0; cust->includes[i]; ++i)
5537     {
5538       struct compunit_symtab *s = cust->includes[i];
5539
5540       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5541       if (s != NULL)
5542         return s;
5543     }
5544
5545   return NULL;
5546 }
5547
5548 static struct compunit_symtab *
5549 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5550                                   struct bound_minimal_symbol msymbol,
5551                                   CORE_ADDR pc,
5552                                   struct obj_section *section,
5553                                   int warn_if_readin)
5554 {
5555   struct dwarf2_per_cu_data *data;
5556   struct compunit_symtab *result;
5557
5558   if (!objfile->psymtabs_addrmap)
5559     return NULL;
5560
5561   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5562                                                      pc);
5563   if (!data)
5564     return NULL;
5565
5566   if (warn_if_readin && data->v.quick->compunit_symtab)
5567     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5568              paddress (get_objfile_arch (objfile), pc));
5569
5570   result
5571     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5572                                                 pc);
5573   gdb_assert (result != NULL);
5574   return result;
5575 }
5576
5577 static void
5578 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5579                           void *data, int need_fullname)
5580 {
5581   struct dwarf2_per_objfile *dwarf2_per_objfile
5582     = get_dwarf2_per_objfile (objfile);
5583
5584   if (!dwarf2_per_objfile->filenames_cache)
5585     {
5586       dwarf2_per_objfile->filenames_cache.emplace ();
5587
5588       htab_up visited (htab_create_alloc (10,
5589                                           htab_hash_pointer, htab_eq_pointer,
5590                                           NULL, xcalloc, xfree));
5591
5592       /* The rule is CUs specify all the files, including those used
5593          by any TU, so there's no need to scan TUs here.  We can
5594          ignore file names coming from already-expanded CUs.  */
5595
5596       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5597         {
5598           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
5599
5600           if (per_cu->v.quick->compunit_symtab)
5601             {
5602               void **slot = htab_find_slot (visited.get (),
5603                                             per_cu->v.quick->file_names,
5604                                             INSERT);
5605
5606               *slot = per_cu->v.quick->file_names;
5607             }
5608         }
5609
5610       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5611         {
5612           dwarf2_per_cu_data *per_cu = dw2_get_cu (dwarf2_per_objfile, i);
5613           struct quick_file_names *file_data;
5614           void **slot;
5615
5616           /* We only need to look at symtabs not already expanded.  */
5617           if (per_cu->v.quick->compunit_symtab)
5618             continue;
5619
5620           file_data = dw2_get_file_names (per_cu);
5621           if (file_data == NULL)
5622             continue;
5623
5624           slot = htab_find_slot (visited.get (), file_data, INSERT);
5625           if (*slot)
5626             {
5627               /* Already visited.  */
5628               continue;
5629             }
5630           *slot = file_data;
5631
5632           for (int j = 0; j < file_data->num_file_names; ++j)
5633             {
5634               const char *filename = file_data->file_names[j];
5635               dwarf2_per_objfile->filenames_cache->seen (filename);
5636             }
5637         }
5638     }
5639
5640   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5641     {
5642       gdb::unique_xmalloc_ptr<char> this_real_name;
5643
5644       if (need_fullname)
5645         this_real_name = gdb_realpath (filename);
5646       (*fun) (filename, this_real_name.get (), data);
5647     });
5648 }
5649
5650 static int
5651 dw2_has_symbols (struct objfile *objfile)
5652 {
5653   return 1;
5654 }
5655
5656 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5657 {
5658   dw2_has_symbols,
5659   dw2_find_last_source_symtab,
5660   dw2_forget_cached_source_info,
5661   dw2_map_symtabs_matching_filename,
5662   dw2_lookup_symbol,
5663   dw2_print_stats,
5664   dw2_dump,
5665   dw2_relocate,
5666   dw2_expand_symtabs_for_function,
5667   dw2_expand_all_symtabs,
5668   dw2_expand_symtabs_with_fullname,
5669   dw2_map_matching_symbols,
5670   dw2_expand_symtabs_matching,
5671   dw2_find_pc_sect_compunit_symtab,
5672   NULL,
5673   dw2_map_symbol_filenames
5674 };
5675
5676 /* DWARF-5 debug_names reader.  */
5677
5678 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5679 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5680
5681 /* A helper function that reads the .debug_names section in SECTION
5682    and fills in MAP.  FILENAME is the name of the file containing the
5683    section; it is used for error reporting.
5684
5685    Returns true if all went well, false otherwise.  */
5686
5687 static bool
5688 read_debug_names_from_section (struct objfile *objfile,
5689                                const char *filename,
5690                                struct dwarf2_section_info *section,
5691                                mapped_debug_names &map)
5692 {
5693   if (dwarf2_section_empty_p (section))
5694     return false;
5695
5696   /* Older elfutils strip versions could keep the section in the main
5697      executable while splitting it for the separate debug info file.  */
5698   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5699     return false;
5700
5701   dwarf2_read_section (objfile, section);
5702
5703   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5704
5705   const gdb_byte *addr = section->buffer;
5706
5707   bfd *const abfd = get_section_bfd_owner (section);
5708
5709   unsigned int bytes_read;
5710   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5711   addr += bytes_read;
5712
5713   map.dwarf5_is_dwarf64 = bytes_read != 4;
5714   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5715   if (bytes_read + length != section->size)
5716     {
5717       /* There may be multiple per-CU indices.  */
5718       warning (_("Section .debug_names in %s length %s does not match "
5719                  "section length %s, ignoring .debug_names."),
5720                filename, plongest (bytes_read + length),
5721                pulongest (section->size));
5722       return false;
5723     }
5724
5725   /* The version number.  */
5726   uint16_t version = read_2_bytes (abfd, addr);
5727   addr += 2;
5728   if (version != 5)
5729     {
5730       warning (_("Section .debug_names in %s has unsupported version %d, "
5731                  "ignoring .debug_names."),
5732                filename, version);
5733       return false;
5734     }
5735
5736   /* Padding.  */
5737   uint16_t padding = read_2_bytes (abfd, addr);
5738   addr += 2;
5739   if (padding != 0)
5740     {
5741       warning (_("Section .debug_names in %s has unsupported padding %d, "
5742                  "ignoring .debug_names."),
5743                filename, padding);
5744       return false;
5745     }
5746
5747   /* comp_unit_count - The number of CUs in the CU list.  */
5748   map.cu_count = read_4_bytes (abfd, addr);
5749   addr += 4;
5750
5751   /* local_type_unit_count - The number of TUs in the local TU
5752      list.  */
5753   map.tu_count = read_4_bytes (abfd, addr);
5754   addr += 4;
5755
5756   /* foreign_type_unit_count - The number of TUs in the foreign TU
5757      list.  */
5758   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5759   addr += 4;
5760   if (foreign_tu_count != 0)
5761     {
5762       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5763                  "ignoring .debug_names."),
5764                filename, static_cast<unsigned long> (foreign_tu_count));
5765       return false;
5766     }
5767
5768   /* bucket_count - The number of hash buckets in the hash lookup
5769      table.  */
5770   map.bucket_count = read_4_bytes (abfd, addr);
5771   addr += 4;
5772
5773   /* name_count - The number of unique names in the index.  */
5774   map.name_count = read_4_bytes (abfd, addr);
5775   addr += 4;
5776
5777   /* abbrev_table_size - The size in bytes of the abbreviations
5778      table.  */
5779   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5780   addr += 4;
5781
5782   /* augmentation_string_size - The size in bytes of the augmentation
5783      string.  This value is rounded up to a multiple of 4.  */
5784   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5785   addr += 4;
5786   map.augmentation_is_gdb = ((augmentation_string_size
5787                               == sizeof (dwarf5_augmentation))
5788                              && memcmp (addr, dwarf5_augmentation,
5789                                         sizeof (dwarf5_augmentation)) == 0);
5790   augmentation_string_size += (-augmentation_string_size) & 3;
5791   addr += augmentation_string_size;
5792
5793   /* List of CUs */
5794   map.cu_table_reordered = addr;
5795   addr += map.cu_count * map.offset_size;
5796
5797   /* List of Local TUs */
5798   map.tu_table_reordered = addr;
5799   addr += map.tu_count * map.offset_size;
5800
5801   /* Hash Lookup Table */
5802   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5803   addr += map.bucket_count * 4;
5804   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5805   addr += map.name_count * 4;
5806
5807   /* Name Table */
5808   map.name_table_string_offs_reordered = addr;
5809   addr += map.name_count * map.offset_size;
5810   map.name_table_entry_offs_reordered = addr;
5811   addr += map.name_count * map.offset_size;
5812
5813   const gdb_byte *abbrev_table_start = addr;
5814   for (;;)
5815     {
5816       unsigned int bytes_read;
5817       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5818       addr += bytes_read;
5819       if (index_num == 0)
5820         break;
5821
5822       const auto insertpair
5823         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5824       if (!insertpair.second)
5825         {
5826           warning (_("Section .debug_names in %s has duplicate index %s, "
5827                      "ignoring .debug_names."),
5828                    filename, pulongest (index_num));
5829           return false;
5830         }
5831       mapped_debug_names::index_val &indexval = insertpair.first->second;
5832       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5833       addr += bytes_read;
5834
5835       for (;;)
5836         {
5837           mapped_debug_names::index_val::attr attr;
5838           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5839           addr += bytes_read;
5840           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5841           addr += bytes_read;
5842           if (attr.form == DW_FORM_implicit_const)
5843             {
5844               attr.implicit_const = read_signed_leb128 (abfd, addr,
5845                                                         &bytes_read);
5846               addr += bytes_read;
5847             }
5848           if (attr.dw_idx == 0 && attr.form == 0)
5849             break;
5850           indexval.attr_vec.push_back (std::move (attr));
5851         }
5852     }
5853   if (addr != abbrev_table_start + abbrev_table_size)
5854     {
5855       warning (_("Section .debug_names in %s has abbreviation_table "
5856                  "of size %zu vs. written as %u, ignoring .debug_names."),
5857                filename, addr - abbrev_table_start, abbrev_table_size);
5858       return false;
5859     }
5860   map.entry_pool = addr;
5861
5862   return true;
5863 }
5864
5865 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5866    list.  */
5867
5868 static void
5869 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5870                                   const mapped_debug_names &map,
5871                                   dwarf2_section_info &section,
5872                                   bool is_dwz, int base_offset)
5873 {
5874   sect_offset sect_off_prev;
5875   for (uint32_t i = 0; i <= map.cu_count; ++i)
5876     {
5877       sect_offset sect_off_next;
5878       if (i < map.cu_count)
5879         {
5880           sect_off_next
5881             = (sect_offset) (extract_unsigned_integer
5882                              (map.cu_table_reordered + i * map.offset_size,
5883                               map.offset_size,
5884                               map.dwarf5_byte_order));
5885         }
5886       else
5887         sect_off_next = (sect_offset) section.size;
5888       if (i >= 1)
5889         {
5890           const ULONGEST length = sect_off_next - sect_off_prev;
5891           dwarf2_per_objfile->all_comp_units[base_offset + (i - 1)]
5892             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5893                                          sect_off_prev, length);
5894         }
5895       sect_off_prev = sect_off_next;
5896     }
5897 }
5898
5899 /* Read the CU list from the mapped index, and use it to create all
5900    the CU objects for this dwarf2_per_objfile.  */
5901
5902 static void
5903 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5904                              const mapped_debug_names &map,
5905                              const mapped_debug_names &dwz_map)
5906 {
5907   struct objfile *objfile = dwarf2_per_objfile->objfile;
5908
5909   dwarf2_per_objfile->n_comp_units = map.cu_count + dwz_map.cu_count;
5910   dwarf2_per_objfile->all_comp_units
5911     = XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
5912                  dwarf2_per_objfile->n_comp_units);
5913
5914   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5915                                     dwarf2_per_objfile->info,
5916                                     false /* is_dwz */,
5917                                     0 /* base_offset */);
5918
5919   if (dwz_map.cu_count == 0)
5920     return;
5921
5922   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5923   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5924                                     true /* is_dwz */,
5925                                     map.cu_count /* base_offset */);
5926 }
5927
5928 /* Read .debug_names.  If everything went ok, initialize the "quick"
5929    elements of all the CUs and return true.  Otherwise, return false.  */
5930
5931 static bool
5932 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5933 {
5934   mapped_debug_names local_map (dwarf2_per_objfile);
5935   mapped_debug_names dwz_map (dwarf2_per_objfile);
5936   struct objfile *objfile = dwarf2_per_objfile->objfile;
5937
5938   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5939                                       &dwarf2_per_objfile->debug_names,
5940                                       local_map))
5941     return false;
5942
5943   /* Don't use the index if it's empty.  */
5944   if (local_map.name_count == 0)
5945     return false;
5946
5947   /* If there is a .dwz file, read it so we can get its CU list as
5948      well.  */
5949   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5950   if (dwz != NULL)
5951     {
5952       if (!read_debug_names_from_section (objfile,
5953                                           bfd_get_filename (dwz->dwz_bfd),
5954                                           &dwz->debug_names, dwz_map))
5955         {
5956           warning (_("could not read '.debug_names' section from %s; skipping"),
5957                    bfd_get_filename (dwz->dwz_bfd));
5958           return false;
5959         }
5960     }
5961
5962   create_cus_from_debug_names (dwarf2_per_objfile, local_map, dwz_map);
5963
5964   if (local_map.tu_count != 0)
5965     {
5966       /* We can only handle a single .debug_types when we have an
5967          index.  */
5968       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5969         return false;
5970
5971       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5972                                                 dwarf2_per_objfile->types, 0);
5973
5974       create_signatured_type_table_from_debug_names
5975         (dwarf2_per_objfile, local_map, section, &dwarf2_per_objfile->abbrev);
5976     }
5977
5978   create_addrmap_from_aranges (dwarf2_per_objfile,
5979                                &dwarf2_per_objfile->debug_aranges);
5980
5981   dwarf2_per_objfile->debug_names_table.reset
5982     (new mapped_debug_names (dwarf2_per_objfile));
5983   *dwarf2_per_objfile->debug_names_table = std::move (local_map);
5984   dwarf2_per_objfile->using_index = 1;
5985   dwarf2_per_objfile->quick_file_names_table =
5986     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5987
5988   return true;
5989 }
5990
5991 /* Symbol name hashing function as specified by DWARF-5.  */
5992
5993 static uint32_t
5994 dwarf5_djb_hash (const char *str_)
5995 {
5996   const unsigned char *str = (const unsigned char *) str_;
5997
5998   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
5999      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
6000
6001   uint32_t hash = 5381;
6002   while (int c = *str++)
6003     hash = hash * 33 + tolower (c);
6004   return hash;
6005 }
6006
6007 /* Type used to manage iterating over all CUs looking for a symbol for
6008    .debug_names.  */
6009
6010 class dw2_debug_names_iterator
6011 {
6012 public:
6013   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
6014      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
6015   dw2_debug_names_iterator (const mapped_debug_names &map,
6016                             bool want_specific_block,
6017                             block_enum block_index, domain_enum domain,
6018                             const char *name)
6019     : m_map (map), m_want_specific_block (want_specific_block),
6020       m_block_index (block_index), m_domain (domain),
6021       m_addr (find_vec_in_debug_names (map, name))
6022   {}
6023
6024   dw2_debug_names_iterator (const mapped_debug_names &map,
6025                             search_domain search, uint32_t namei)
6026     : m_map (map),
6027       m_search (search),
6028       m_addr (find_vec_in_debug_names (map, namei))
6029   {}
6030
6031   /* Return the next matching CU or NULL if there are no more.  */
6032   dwarf2_per_cu_data *next ();
6033
6034 private:
6035   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6036                                                   const char *name);
6037   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
6038                                                   uint32_t namei);
6039
6040   /* The internalized form of .debug_names.  */
6041   const mapped_debug_names &m_map;
6042
6043   /* If true, only look for symbols that match BLOCK_INDEX.  */
6044   const bool m_want_specific_block = false;
6045
6046   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
6047      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
6048      value.  */
6049   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
6050
6051   /* The kind of symbol we're looking for.  */
6052   const domain_enum m_domain = UNDEF_DOMAIN;
6053   const search_domain m_search = ALL_DOMAIN;
6054
6055   /* The list of CUs from the index entry of the symbol, or NULL if
6056      not found.  */
6057   const gdb_byte *m_addr;
6058 };
6059
6060 const char *
6061 mapped_debug_names::namei_to_name (uint32_t namei) const
6062 {
6063   const ULONGEST namei_string_offs
6064     = extract_unsigned_integer ((name_table_string_offs_reordered
6065                                  + namei * offset_size),
6066                                 offset_size,
6067                                 dwarf5_byte_order);
6068   return read_indirect_string_at_offset
6069     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
6070 }
6071
6072 /* Find a slot in .debug_names for the object named NAME.  If NAME is
6073    found, return pointer to its pool data.  If NAME cannot be found,
6074    return NULL.  */
6075
6076 const gdb_byte *
6077 dw2_debug_names_iterator::find_vec_in_debug_names
6078   (const mapped_debug_names &map, const char *name)
6079 {
6080   int (*cmp) (const char *, const char *);
6081
6082   if (current_language->la_language == language_cplus
6083       || current_language->la_language == language_fortran
6084       || current_language->la_language == language_d)
6085     {
6086       /* NAME is already canonical.  Drop any qualifiers as
6087          .debug_names does not contain any.  */
6088
6089       if (strchr (name, '(') != NULL)
6090         {
6091           gdb::unique_xmalloc_ptr<char> without_params
6092             = cp_remove_params (name);
6093
6094           if (without_params != NULL)
6095             {
6096               name = without_params.get();
6097             }
6098         }
6099     }
6100
6101   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
6102
6103   const uint32_t full_hash = dwarf5_djb_hash (name);
6104   uint32_t namei
6105     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6106                                 (map.bucket_table_reordered
6107                                  + (full_hash % map.bucket_count)), 4,
6108                                 map.dwarf5_byte_order);
6109   if (namei == 0)
6110     return NULL;
6111   --namei;
6112   if (namei >= map.name_count)
6113     {
6114       complaint (&symfile_complaints,
6115                  _("Wrong .debug_names with name index %u but name_count=%u "
6116                    "[in module %s]"),
6117                  namei, map.name_count,
6118                  objfile_name (map.dwarf2_per_objfile->objfile));
6119       return NULL;
6120     }
6121
6122   for (;;)
6123     {
6124       const uint32_t namei_full_hash
6125         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
6126                                     (map.hash_table_reordered + namei), 4,
6127                                     map.dwarf5_byte_order);
6128       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
6129         return NULL;
6130
6131       if (full_hash == namei_full_hash)
6132         {
6133           const char *const namei_string = map.namei_to_name (namei);
6134
6135 #if 0 /* An expensive sanity check.  */
6136           if (namei_full_hash != dwarf5_djb_hash (namei_string))
6137             {
6138               complaint (&symfile_complaints,
6139                          _("Wrong .debug_names hash for string at index %u "
6140                            "[in module %s]"),
6141                          namei, objfile_name (dwarf2_per_objfile->objfile));
6142               return NULL;
6143             }
6144 #endif
6145
6146           if (cmp (namei_string, name) == 0)
6147             {
6148               const ULONGEST namei_entry_offs
6149                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6150                                              + namei * map.offset_size),
6151                                             map.offset_size, map.dwarf5_byte_order);
6152               return map.entry_pool + namei_entry_offs;
6153             }
6154         }
6155
6156       ++namei;
6157       if (namei >= map.name_count)
6158         return NULL;
6159     }
6160 }
6161
6162 const gdb_byte *
6163 dw2_debug_names_iterator::find_vec_in_debug_names
6164   (const mapped_debug_names &map, uint32_t namei)
6165 {
6166   if (namei >= map.name_count)
6167     {
6168       complaint (&symfile_complaints,
6169                  _("Wrong .debug_names with name index %u but name_count=%u "
6170                    "[in module %s]"),
6171                  namei, map.name_count,
6172                  objfile_name (map.dwarf2_per_objfile->objfile));
6173       return NULL;
6174     }
6175
6176   const ULONGEST namei_entry_offs
6177     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
6178                                  + namei * map.offset_size),
6179                                 map.offset_size, map.dwarf5_byte_order);
6180   return map.entry_pool + namei_entry_offs;
6181 }
6182
6183 /* See dw2_debug_names_iterator.  */
6184
6185 dwarf2_per_cu_data *
6186 dw2_debug_names_iterator::next ()
6187 {
6188   if (m_addr == NULL)
6189     return NULL;
6190
6191   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
6192   struct objfile *objfile = dwarf2_per_objfile->objfile;
6193   bfd *const abfd = objfile->obfd;
6194
6195  again:
6196
6197   unsigned int bytes_read;
6198   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6199   m_addr += bytes_read;
6200   if (abbrev == 0)
6201     return NULL;
6202
6203   const auto indexval_it = m_map.abbrev_map.find (abbrev);
6204   if (indexval_it == m_map.abbrev_map.cend ())
6205     {
6206       complaint (&symfile_complaints,
6207                  _("Wrong .debug_names undefined abbrev code %s "
6208                    "[in module %s]"),
6209                  pulongest (abbrev), objfile_name (objfile));
6210       return NULL;
6211     }
6212   const mapped_debug_names::index_val &indexval = indexval_it->second;
6213   bool have_is_static = false;
6214   bool is_static;
6215   dwarf2_per_cu_data *per_cu = NULL;
6216   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
6217     {
6218       ULONGEST ull;
6219       switch (attr.form)
6220         {
6221         case DW_FORM_implicit_const:
6222           ull = attr.implicit_const;
6223           break;
6224         case DW_FORM_flag_present:
6225           ull = 1;
6226           break;
6227         case DW_FORM_udata:
6228           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
6229           m_addr += bytes_read;
6230           break;
6231         default:
6232           complaint (&symfile_complaints,
6233                      _("Unsupported .debug_names form %s [in module %s]"),
6234                      dwarf_form_name (attr.form),
6235                      objfile_name (objfile));
6236           return NULL;
6237         }
6238       switch (attr.dw_idx)
6239         {
6240         case DW_IDX_compile_unit:
6241           /* Don't crash on bad data.  */
6242           if (ull >= dwarf2_per_objfile->n_comp_units)
6243             {
6244               complaint (&symfile_complaints,
6245                          _(".debug_names entry has bad CU index %s"
6246                            " [in module %s]"),
6247                          pulongest (ull),
6248                          objfile_name (dwarf2_per_objfile->objfile));
6249               continue;
6250             }
6251           per_cu = dw2_get_cutu (dwarf2_per_objfile, ull);
6252           break;
6253         case DW_IDX_type_unit:
6254           /* Don't crash on bad data.  */
6255           if (ull >= dwarf2_per_objfile->n_type_units)
6256             {
6257               complaint (&symfile_complaints,
6258                          _(".debug_names entry has bad TU index %s"
6259                            " [in module %s]"),
6260                          pulongest (ull),
6261                          objfile_name (dwarf2_per_objfile->objfile));
6262               continue;
6263             }
6264           per_cu = dw2_get_cutu (dwarf2_per_objfile,
6265                                  dwarf2_per_objfile->n_comp_units + ull);
6266           break;
6267         case DW_IDX_GNU_internal:
6268           if (!m_map.augmentation_is_gdb)
6269             break;
6270           have_is_static = true;
6271           is_static = true;
6272           break;
6273         case DW_IDX_GNU_external:
6274           if (!m_map.augmentation_is_gdb)
6275             break;
6276           have_is_static = true;
6277           is_static = false;
6278           break;
6279         }
6280     }
6281
6282   /* Skip if already read in.  */
6283   if (per_cu->v.quick->compunit_symtab)
6284     goto again;
6285
6286   /* Check static vs global.  */
6287   if (have_is_static)
6288     {
6289       const bool want_static = m_block_index != GLOBAL_BLOCK;
6290       if (m_want_specific_block && want_static != is_static)
6291         goto again;
6292     }
6293
6294   /* Match dw2_symtab_iter_next, symbol_kind
6295      and debug_names::psymbol_tag.  */
6296   switch (m_domain)
6297     {
6298     case VAR_DOMAIN:
6299       switch (indexval.dwarf_tag)
6300         {
6301         case DW_TAG_variable:
6302         case DW_TAG_subprogram:
6303         /* Some types are also in VAR_DOMAIN.  */
6304         case DW_TAG_typedef:
6305         case DW_TAG_structure_type:
6306           break;
6307         default:
6308           goto again;
6309         }
6310       break;
6311     case STRUCT_DOMAIN:
6312       switch (indexval.dwarf_tag)
6313         {
6314         case DW_TAG_typedef:
6315         case DW_TAG_structure_type:
6316           break;
6317         default:
6318           goto again;
6319         }
6320       break;
6321     case LABEL_DOMAIN:
6322       switch (indexval.dwarf_tag)
6323         {
6324         case 0:
6325         case DW_TAG_variable:
6326           break;
6327         default:
6328           goto again;
6329         }
6330       break;
6331     default:
6332       break;
6333     }
6334
6335   /* Match dw2_expand_symtabs_matching, symbol_kind and
6336      debug_names::psymbol_tag.  */
6337   switch (m_search)
6338     {
6339     case VARIABLES_DOMAIN:
6340       switch (indexval.dwarf_tag)
6341         {
6342         case DW_TAG_variable:
6343           break;
6344         default:
6345           goto again;
6346         }
6347       break;
6348     case FUNCTIONS_DOMAIN:
6349       switch (indexval.dwarf_tag)
6350         {
6351         case DW_TAG_subprogram:
6352           break;
6353         default:
6354           goto again;
6355         }
6356       break;
6357     case TYPES_DOMAIN:
6358       switch (indexval.dwarf_tag)
6359         {
6360         case DW_TAG_typedef:
6361         case DW_TAG_structure_type:
6362           break;
6363         default:
6364           goto again;
6365         }
6366       break;
6367     default:
6368       break;
6369     }
6370
6371   return per_cu;
6372 }
6373
6374 static struct compunit_symtab *
6375 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6376                                const char *name, domain_enum domain)
6377 {
6378   const block_enum block_index = static_cast<block_enum> (block_index_int);
6379   struct dwarf2_per_objfile *dwarf2_per_objfile
6380     = get_dwarf2_per_objfile (objfile);
6381
6382   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6383   if (!mapp)
6384     {
6385       /* index is NULL if OBJF_READNOW.  */
6386       return NULL;
6387     }
6388   const auto &map = *mapp;
6389
6390   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6391                                  block_index, domain, name);
6392
6393   struct compunit_symtab *stab_best = NULL;
6394   struct dwarf2_per_cu_data *per_cu;
6395   while ((per_cu = iter.next ()) != NULL)
6396     {
6397       struct symbol *sym, *with_opaque = NULL;
6398       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
6399       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6400       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6401
6402       sym = block_find_symbol (block, name, domain,
6403                                block_find_non_opaque_type_preferred,
6404                                &with_opaque);
6405
6406       /* Some caution must be observed with overloaded functions and
6407          methods, since the index will not contain any overload
6408          information (but NAME might contain it).  */
6409
6410       if (sym != NULL
6411           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6412         return stab;
6413       if (with_opaque != NULL
6414           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6415         stab_best = stab;
6416
6417       /* Keep looking through other CUs.  */
6418     }
6419
6420   return stab_best;
6421 }
6422
6423 /* This dumps minimal information about .debug_names.  It is called
6424    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6425    uses this to verify that .debug_names has been loaded.  */
6426
6427 static void
6428 dw2_debug_names_dump (struct objfile *objfile)
6429 {
6430   struct dwarf2_per_objfile *dwarf2_per_objfile
6431     = get_dwarf2_per_objfile (objfile);
6432
6433   gdb_assert (dwarf2_per_objfile->using_index);
6434   printf_filtered (".debug_names:");
6435   if (dwarf2_per_objfile->debug_names_table)
6436     printf_filtered (" exists\n");
6437   else
6438     printf_filtered (" faked for \"readnow\"\n");
6439   printf_filtered ("\n");
6440 }
6441
6442 static void
6443 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6444                                              const char *func_name)
6445 {
6446   struct dwarf2_per_objfile *dwarf2_per_objfile
6447     = get_dwarf2_per_objfile (objfile);
6448
6449   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6450   if (dwarf2_per_objfile->debug_names_table)
6451     {
6452       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6453
6454       /* Note: It doesn't matter what we pass for block_index here.  */
6455       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6456                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6457
6458       struct dwarf2_per_cu_data *per_cu;
6459       while ((per_cu = iter.next ()) != NULL)
6460         dw2_instantiate_symtab (per_cu);
6461     }
6462 }
6463
6464 static void
6465 dw2_debug_names_expand_symtabs_matching
6466   (struct objfile *objfile,
6467    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6468    const lookup_name_info &lookup_name,
6469    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6470    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6471    enum search_domain kind)
6472 {
6473   struct dwarf2_per_objfile *dwarf2_per_objfile
6474     = get_dwarf2_per_objfile (objfile);
6475
6476   /* debug_names_table is NULL if OBJF_READNOW.  */
6477   if (!dwarf2_per_objfile->debug_names_table)
6478     return;
6479
6480   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6481
6482   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6483
6484   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6485                                       symbol_matcher,
6486                                       kind, [&] (offset_type namei)
6487     {
6488       /* The name was matched, now expand corresponding CUs that were
6489          marked.  */
6490       dw2_debug_names_iterator iter (map, kind, namei);
6491
6492       struct dwarf2_per_cu_data *per_cu;
6493       while ((per_cu = iter.next ()) != NULL)
6494         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6495                                          expansion_notify);
6496     });
6497 }
6498
6499 const struct quick_symbol_functions dwarf2_debug_names_functions =
6500 {
6501   dw2_has_symbols,
6502   dw2_find_last_source_symtab,
6503   dw2_forget_cached_source_info,
6504   dw2_map_symtabs_matching_filename,
6505   dw2_debug_names_lookup_symbol,
6506   dw2_print_stats,
6507   dw2_debug_names_dump,
6508   dw2_relocate,
6509   dw2_debug_names_expand_symtabs_for_function,
6510   dw2_expand_all_symtabs,
6511   dw2_expand_symtabs_with_fullname,
6512   dw2_map_matching_symbols,
6513   dw2_debug_names_expand_symtabs_matching,
6514   dw2_find_pc_sect_compunit_symtab,
6515   NULL,
6516   dw2_map_symbol_filenames
6517 };
6518
6519 /* See symfile.h.  */
6520
6521 bool
6522 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6523 {
6524   struct dwarf2_per_objfile *dwarf2_per_objfile
6525     = get_dwarf2_per_objfile (objfile);
6526
6527   /* If we're about to read full symbols, don't bother with the
6528      indices.  In this case we also don't care if some other debug
6529      format is making psymtabs, because they are all about to be
6530      expanded anyway.  */
6531   if ((objfile->flags & OBJF_READNOW))
6532     {
6533       int i;
6534
6535       dwarf2_per_objfile->using_index = 1;
6536       create_all_comp_units (dwarf2_per_objfile);
6537       create_all_type_units (dwarf2_per_objfile);
6538       dwarf2_per_objfile->quick_file_names_table =
6539         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
6540
6541       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
6542                        + dwarf2_per_objfile->n_type_units); ++i)
6543         {
6544           dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
6545
6546           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6547                                             struct dwarf2_per_cu_quick_data);
6548         }
6549
6550       /* Return 1 so that gdb sees the "quick" functions.  However,
6551          these functions will be no-ops because we will have expanded
6552          all symtabs.  */
6553       *index_kind = dw_index_kind::GDB_INDEX;
6554       return true;
6555     }
6556
6557   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6558     {
6559       *index_kind = dw_index_kind::DEBUG_NAMES;
6560       return true;
6561     }
6562
6563   if (dwarf2_read_index (objfile))
6564     {
6565       *index_kind = dw_index_kind::GDB_INDEX;
6566       return true;
6567     }
6568
6569   return false;
6570 }
6571
6572 \f
6573
6574 /* Build a partial symbol table.  */
6575
6576 void
6577 dwarf2_build_psymtabs (struct objfile *objfile)
6578 {
6579   struct dwarf2_per_objfile *dwarf2_per_objfile
6580     = get_dwarf2_per_objfile (objfile);
6581
6582   if (objfile->global_psymbols.capacity () == 0
6583       && objfile->static_psymbols.capacity () == 0)
6584     init_psymbol_list (objfile, 1024);
6585
6586   TRY
6587     {
6588       /* This isn't really ideal: all the data we allocate on the
6589          objfile's obstack is still uselessly kept around.  However,
6590          freeing it seems unsafe.  */
6591       psymtab_discarder psymtabs (objfile);
6592       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6593       psymtabs.keep ();
6594     }
6595   CATCH (except, RETURN_MASK_ERROR)
6596     {
6597       exception_print (gdb_stderr, except);
6598     }
6599   END_CATCH
6600 }
6601
6602 /* Return the total length of the CU described by HEADER.  */
6603
6604 static unsigned int
6605 get_cu_length (const struct comp_unit_head *header)
6606 {
6607   return header->initial_length_size + header->length;
6608 }
6609
6610 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6611
6612 static inline bool
6613 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6614 {
6615   sect_offset bottom = cu_header->sect_off;
6616   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6617
6618   return sect_off >= bottom && sect_off < top;
6619 }
6620
6621 /* Find the base address of the compilation unit for range lists and
6622    location lists.  It will normally be specified by DW_AT_low_pc.
6623    In DWARF-3 draft 4, the base address could be overridden by
6624    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6625    compilation units with discontinuous ranges.  */
6626
6627 static void
6628 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6629 {
6630   struct attribute *attr;
6631
6632   cu->base_known = 0;
6633   cu->base_address = 0;
6634
6635   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6636   if (attr)
6637     {
6638       cu->base_address = attr_value_as_address (attr);
6639       cu->base_known = 1;
6640     }
6641   else
6642     {
6643       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6644       if (attr)
6645         {
6646           cu->base_address = attr_value_as_address (attr);
6647           cu->base_known = 1;
6648         }
6649     }
6650 }
6651
6652 /* Read in the comp unit header information from the debug_info at info_ptr.
6653    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6654    NOTE: This leaves members offset, first_die_offset to be filled in
6655    by the caller.  */
6656
6657 static const gdb_byte *
6658 read_comp_unit_head (struct comp_unit_head *cu_header,
6659                      const gdb_byte *info_ptr,
6660                      struct dwarf2_section_info *section,
6661                      rcuh_kind section_kind)
6662 {
6663   int signed_addr;
6664   unsigned int bytes_read;
6665   const char *filename = get_section_file_name (section);
6666   bfd *abfd = get_section_bfd_owner (section);
6667
6668   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6669   cu_header->initial_length_size = bytes_read;
6670   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6671   info_ptr += bytes_read;
6672   cu_header->version = read_2_bytes (abfd, info_ptr);
6673   info_ptr += 2;
6674   if (cu_header->version < 5)
6675     switch (section_kind)
6676       {
6677       case rcuh_kind::COMPILE:
6678         cu_header->unit_type = DW_UT_compile;
6679         break;
6680       case rcuh_kind::TYPE:
6681         cu_header->unit_type = DW_UT_type;
6682         break;
6683       default:
6684         internal_error (__FILE__, __LINE__,
6685                         _("read_comp_unit_head: invalid section_kind"));
6686       }
6687   else
6688     {
6689       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6690                                                  (read_1_byte (abfd, info_ptr));
6691       info_ptr += 1;
6692       switch (cu_header->unit_type)
6693         {
6694         case DW_UT_compile:
6695           if (section_kind != rcuh_kind::COMPILE)
6696             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6697                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6698                    filename);
6699           break;
6700         case DW_UT_type:
6701           section_kind = rcuh_kind::TYPE;
6702           break;
6703         default:
6704           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6705                  "(is %d, should be %d or %d) [in module %s]"),
6706                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6707         }
6708
6709       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6710       info_ptr += 1;
6711     }
6712   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6713                                                           cu_header,
6714                                                           &bytes_read);
6715   info_ptr += bytes_read;
6716   if (cu_header->version < 5)
6717     {
6718       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6719       info_ptr += 1;
6720     }
6721   signed_addr = bfd_get_sign_extend_vma (abfd);
6722   if (signed_addr < 0)
6723     internal_error (__FILE__, __LINE__,
6724                     _("read_comp_unit_head: dwarf from non elf file"));
6725   cu_header->signed_addr_p = signed_addr;
6726
6727   if (section_kind == rcuh_kind::TYPE)
6728     {
6729       LONGEST type_offset;
6730
6731       cu_header->signature = read_8_bytes (abfd, info_ptr);
6732       info_ptr += 8;
6733
6734       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6735       info_ptr += bytes_read;
6736       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6737       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6738         error (_("Dwarf Error: Too big type_offset in compilation unit "
6739                "header (is %s) [in module %s]"), plongest (type_offset),
6740                filename);
6741     }
6742
6743   return info_ptr;
6744 }
6745
6746 /* Helper function that returns the proper abbrev section for
6747    THIS_CU.  */
6748
6749 static struct dwarf2_section_info *
6750 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6751 {
6752   struct dwarf2_section_info *abbrev;
6753   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6754
6755   if (this_cu->is_dwz)
6756     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6757   else
6758     abbrev = &dwarf2_per_objfile->abbrev;
6759
6760   return abbrev;
6761 }
6762
6763 /* Subroutine of read_and_check_comp_unit_head and
6764    read_and_check_type_unit_head to simplify them.
6765    Perform various error checking on the header.  */
6766
6767 static void
6768 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6769                             struct comp_unit_head *header,
6770                             struct dwarf2_section_info *section,
6771                             struct dwarf2_section_info *abbrev_section)
6772 {
6773   const char *filename = get_section_file_name (section);
6774
6775   if (header->version < 2 || header->version > 5)
6776     error (_("Dwarf Error: wrong version in compilation unit header "
6777            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
6778            filename);
6779
6780   if (to_underlying (header->abbrev_sect_off)
6781       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6782     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
6783            "(offset 0x%x + 6) [in module %s]"),
6784            to_underlying (header->abbrev_sect_off),
6785            to_underlying (header->sect_off),
6786            filename);
6787
6788   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6789      avoid potential 32-bit overflow.  */
6790   if (((ULONGEST) header->sect_off + get_cu_length (header))
6791       > section->size)
6792     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6793            "(offset 0x%x + 0) [in module %s]"),
6794            header->length, to_underlying (header->sect_off),
6795            filename);
6796 }
6797
6798 /* Read in a CU/TU header and perform some basic error checking.
6799    The contents of the header are stored in HEADER.
6800    The result is a pointer to the start of the first DIE.  */
6801
6802 static const gdb_byte *
6803 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6804                                struct comp_unit_head *header,
6805                                struct dwarf2_section_info *section,
6806                                struct dwarf2_section_info *abbrev_section,
6807                                const gdb_byte *info_ptr,
6808                                rcuh_kind section_kind)
6809 {
6810   const gdb_byte *beg_of_comp_unit = info_ptr;
6811
6812   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6813
6814   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6815
6816   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6817
6818   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6819                               abbrev_section);
6820
6821   return info_ptr;
6822 }
6823
6824 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6825
6826 static sect_offset
6827 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6828                     struct dwarf2_section_info *section,
6829                     sect_offset sect_off)
6830 {
6831   bfd *abfd = get_section_bfd_owner (section);
6832   const gdb_byte *info_ptr;
6833   unsigned int initial_length_size, offset_size;
6834   uint16_t version;
6835
6836   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6837   info_ptr = section->buffer + to_underlying (sect_off);
6838   read_initial_length (abfd, info_ptr, &initial_length_size);
6839   offset_size = initial_length_size == 4 ? 4 : 8;
6840   info_ptr += initial_length_size;
6841
6842   version = read_2_bytes (abfd, info_ptr);
6843   info_ptr += 2;
6844   if (version >= 5)
6845     {
6846       /* Skip unit type and address size.  */
6847       info_ptr += 2;
6848     }
6849
6850   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6851 }
6852
6853 /* Allocate a new partial symtab for file named NAME and mark this new
6854    partial symtab as being an include of PST.  */
6855
6856 static void
6857 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6858                                struct objfile *objfile)
6859 {
6860   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6861
6862   if (!IS_ABSOLUTE_PATH (subpst->filename))
6863     {
6864       /* It shares objfile->objfile_obstack.  */
6865       subpst->dirname = pst->dirname;
6866     }
6867
6868   subpst->textlow = 0;
6869   subpst->texthigh = 0;
6870
6871   subpst->dependencies
6872     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6873   subpst->dependencies[0] = pst;
6874   subpst->number_of_dependencies = 1;
6875
6876   subpst->globals_offset = 0;
6877   subpst->n_global_syms = 0;
6878   subpst->statics_offset = 0;
6879   subpst->n_static_syms = 0;
6880   subpst->compunit_symtab = NULL;
6881   subpst->read_symtab = pst->read_symtab;
6882   subpst->readin = 0;
6883
6884   /* No private part is necessary for include psymtabs.  This property
6885      can be used to differentiate between such include psymtabs and
6886      the regular ones.  */
6887   subpst->read_symtab_private = NULL;
6888 }
6889
6890 /* Read the Line Number Program data and extract the list of files
6891    included by the source file represented by PST.  Build an include
6892    partial symtab for each of these included files.  */
6893
6894 static void
6895 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6896                                struct die_info *die,
6897                                struct partial_symtab *pst)
6898 {
6899   line_header_up lh;
6900   struct attribute *attr;
6901
6902   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6903   if (attr)
6904     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6905   if (lh == NULL)
6906     return;  /* No linetable, so no includes.  */
6907
6908   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6909   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6910 }
6911
6912 static hashval_t
6913 hash_signatured_type (const void *item)
6914 {
6915   const struct signatured_type *sig_type
6916     = (const struct signatured_type *) item;
6917
6918   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6919   return sig_type->signature;
6920 }
6921
6922 static int
6923 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6924 {
6925   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6926   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6927
6928   return lhs->signature == rhs->signature;
6929 }
6930
6931 /* Allocate a hash table for signatured types.  */
6932
6933 static htab_t
6934 allocate_signatured_type_table (struct objfile *objfile)
6935 {
6936   return htab_create_alloc_ex (41,
6937                                hash_signatured_type,
6938                                eq_signatured_type,
6939                                NULL,
6940                                &objfile->objfile_obstack,
6941                                hashtab_obstack_allocate,
6942                                dummy_obstack_deallocate);
6943 }
6944
6945 /* A helper function to add a signatured type CU to a table.  */
6946
6947 static int
6948 add_signatured_type_cu_to_table (void **slot, void *datum)
6949 {
6950   struct signatured_type *sigt = (struct signatured_type *) *slot;
6951   struct signatured_type ***datap = (struct signatured_type ***) datum;
6952
6953   **datap = sigt;
6954   ++*datap;
6955
6956   return 1;
6957 }
6958
6959 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6960    and fill them into TYPES_HTAB.  It will process only type units,
6961    therefore DW_UT_type.  */
6962
6963 static void
6964 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6965                               struct dwo_file *dwo_file,
6966                               dwarf2_section_info *section, htab_t &types_htab,
6967                               rcuh_kind section_kind)
6968 {
6969   struct objfile *objfile = dwarf2_per_objfile->objfile;
6970   struct dwarf2_section_info *abbrev_section;
6971   bfd *abfd;
6972   const gdb_byte *info_ptr, *end_ptr;
6973
6974   abbrev_section = (dwo_file != NULL
6975                     ? &dwo_file->sections.abbrev
6976                     : &dwarf2_per_objfile->abbrev);
6977
6978   if (dwarf_read_debug)
6979     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6980                         get_section_name (section),
6981                         get_section_file_name (abbrev_section));
6982
6983   dwarf2_read_section (objfile, section);
6984   info_ptr = section->buffer;
6985
6986   if (info_ptr == NULL)
6987     return;
6988
6989   /* We can't set abfd until now because the section may be empty or
6990      not present, in which case the bfd is unknown.  */
6991   abfd = get_section_bfd_owner (section);
6992
6993   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6994      because we don't need to read any dies: the signature is in the
6995      header.  */
6996
6997   end_ptr = info_ptr + section->size;
6998   while (info_ptr < end_ptr)
6999     {
7000       struct signatured_type *sig_type;
7001       struct dwo_unit *dwo_tu;
7002       void **slot;
7003       const gdb_byte *ptr = info_ptr;
7004       struct comp_unit_head header;
7005       unsigned int length;
7006
7007       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
7008
7009       /* Initialize it due to a false compiler warning.  */
7010       header.signature = -1;
7011       header.type_cu_offset_in_tu = (cu_offset) -1;
7012
7013       /* We need to read the type's signature in order to build the hash
7014          table, but we don't need anything else just yet.  */
7015
7016       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
7017                                            abbrev_section, ptr, section_kind);
7018
7019       length = get_cu_length (&header);
7020
7021       /* Skip dummy type units.  */
7022       if (ptr >= info_ptr + length
7023           || peek_abbrev_code (abfd, ptr) == 0
7024           || header.unit_type != DW_UT_type)
7025         {
7026           info_ptr += length;
7027           continue;
7028         }
7029
7030       if (types_htab == NULL)
7031         {
7032           if (dwo_file)
7033             types_htab = allocate_dwo_unit_table (objfile);
7034           else
7035             types_htab = allocate_signatured_type_table (objfile);
7036         }
7037
7038       if (dwo_file)
7039         {
7040           sig_type = NULL;
7041           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7042                                    struct dwo_unit);
7043           dwo_tu->dwo_file = dwo_file;
7044           dwo_tu->signature = header.signature;
7045           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
7046           dwo_tu->section = section;
7047           dwo_tu->sect_off = sect_off;
7048           dwo_tu->length = length;
7049         }
7050       else
7051         {
7052           /* N.B.: type_offset is not usable if this type uses a DWO file.
7053              The real type_offset is in the DWO file.  */
7054           dwo_tu = NULL;
7055           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7056                                      struct signatured_type);
7057           sig_type->signature = header.signature;
7058           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
7059           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7060           sig_type->per_cu.is_debug_types = 1;
7061           sig_type->per_cu.section = section;
7062           sig_type->per_cu.sect_off = sect_off;
7063           sig_type->per_cu.length = length;
7064         }
7065
7066       slot = htab_find_slot (types_htab,
7067                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
7068                              INSERT);
7069       gdb_assert (slot != NULL);
7070       if (*slot != NULL)
7071         {
7072           sect_offset dup_sect_off;
7073
7074           if (dwo_file)
7075             {
7076               const struct dwo_unit *dup_tu
7077                 = (const struct dwo_unit *) *slot;
7078
7079               dup_sect_off = dup_tu->sect_off;
7080             }
7081           else
7082             {
7083               const struct signatured_type *dup_tu
7084                 = (const struct signatured_type *) *slot;
7085
7086               dup_sect_off = dup_tu->per_cu.sect_off;
7087             }
7088
7089           complaint (&symfile_complaints,
7090                      _("debug type entry at offset 0x%x is duplicate to"
7091                        " the entry at offset 0x%x, signature %s"),
7092                      to_underlying (sect_off), to_underlying (dup_sect_off),
7093                      hex_string (header.signature));
7094         }
7095       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
7096
7097       if (dwarf_read_debug > 1)
7098         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
7099                             to_underlying (sect_off),
7100                             hex_string (header.signature));
7101
7102       info_ptr += length;
7103     }
7104 }
7105
7106 /* Create the hash table of all entries in the .debug_types
7107    (or .debug_types.dwo) section(s).
7108    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
7109    otherwise it is NULL.
7110
7111    The result is a pointer to the hash table or NULL if there are no types.
7112
7113    Note: This function processes DWO files only, not DWP files.  */
7114
7115 static void
7116 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
7117                                struct dwo_file *dwo_file,
7118                                VEC (dwarf2_section_info_def) *types,
7119                                htab_t &types_htab)
7120 {
7121   int ix;
7122   struct dwarf2_section_info *section;
7123
7124   if (VEC_empty (dwarf2_section_info_def, types))
7125     return;
7126
7127   for (ix = 0;
7128        VEC_iterate (dwarf2_section_info_def, types, ix, section);
7129        ++ix)
7130     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
7131                                   types_htab, rcuh_kind::TYPE);
7132 }
7133
7134 /* Create the hash table of all entries in the .debug_types section,
7135    and initialize all_type_units.
7136    The result is zero if there is an error (e.g. missing .debug_types section),
7137    otherwise non-zero.  */
7138
7139 static int
7140 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
7141 {
7142   htab_t types_htab = NULL;
7143   struct signatured_type **iter;
7144
7145   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
7146                                 &dwarf2_per_objfile->info, types_htab,
7147                                 rcuh_kind::COMPILE);
7148   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
7149                                  dwarf2_per_objfile->types, types_htab);
7150   if (types_htab == NULL)
7151     {
7152       dwarf2_per_objfile->signatured_types = NULL;
7153       return 0;
7154     }
7155
7156   dwarf2_per_objfile->signatured_types = types_htab;
7157
7158   dwarf2_per_objfile->n_type_units
7159     = dwarf2_per_objfile->n_allocated_type_units
7160     = htab_elements (types_htab);
7161   dwarf2_per_objfile->all_type_units =
7162     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
7163   iter = &dwarf2_per_objfile->all_type_units[0];
7164   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
7165   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
7166               == dwarf2_per_objfile->n_type_units);
7167
7168   return 1;
7169 }
7170
7171 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
7172    If SLOT is non-NULL, it is the entry to use in the hash table.
7173    Otherwise we find one.  */
7174
7175 static struct signatured_type *
7176 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
7177                void **slot)
7178 {
7179   struct objfile *objfile = dwarf2_per_objfile->objfile;
7180   int n_type_units = dwarf2_per_objfile->n_type_units;
7181   struct signatured_type *sig_type;
7182
7183   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
7184   ++n_type_units;
7185   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
7186     {
7187       if (dwarf2_per_objfile->n_allocated_type_units == 0)
7188         dwarf2_per_objfile->n_allocated_type_units = 1;
7189       dwarf2_per_objfile->n_allocated_type_units *= 2;
7190       dwarf2_per_objfile->all_type_units
7191         = XRESIZEVEC (struct signatured_type *,
7192                       dwarf2_per_objfile->all_type_units,
7193                       dwarf2_per_objfile->n_allocated_type_units);
7194       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
7195     }
7196   dwarf2_per_objfile->n_type_units = n_type_units;
7197
7198   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7199                              struct signatured_type);
7200   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
7201   sig_type->signature = sig;
7202   sig_type->per_cu.is_debug_types = 1;
7203   if (dwarf2_per_objfile->using_index)
7204     {
7205       sig_type->per_cu.v.quick =
7206         OBSTACK_ZALLOC (&objfile->objfile_obstack,
7207                         struct dwarf2_per_cu_quick_data);
7208     }
7209
7210   if (slot == NULL)
7211     {
7212       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7213                              sig_type, INSERT);
7214     }
7215   gdb_assert (*slot == NULL);
7216   *slot = sig_type;
7217   /* The rest of sig_type must be filled in by the caller.  */
7218   return sig_type;
7219 }
7220
7221 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
7222    Fill in SIG_ENTRY with DWO_ENTRY.  */
7223
7224 static void
7225 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
7226                                   struct signatured_type *sig_entry,
7227                                   struct dwo_unit *dwo_entry)
7228 {
7229   /* Make sure we're not clobbering something we don't expect to.  */
7230   gdb_assert (! sig_entry->per_cu.queued);
7231   gdb_assert (sig_entry->per_cu.cu == NULL);
7232   if (dwarf2_per_objfile->using_index)
7233     {
7234       gdb_assert (sig_entry->per_cu.v.quick != NULL);
7235       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
7236     }
7237   else
7238       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
7239   gdb_assert (sig_entry->signature == dwo_entry->signature);
7240   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
7241   gdb_assert (sig_entry->type_unit_group == NULL);
7242   gdb_assert (sig_entry->dwo_unit == NULL);
7243
7244   sig_entry->per_cu.section = dwo_entry->section;
7245   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
7246   sig_entry->per_cu.length = dwo_entry->length;
7247   sig_entry->per_cu.reading_dwo_directly = 1;
7248   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
7249   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
7250   sig_entry->dwo_unit = dwo_entry;
7251 }
7252
7253 /* Subroutine of lookup_signatured_type.
7254    If we haven't read the TU yet, create the signatured_type data structure
7255    for a TU to be read in directly from a DWO file, bypassing the stub.
7256    This is the "Stay in DWO Optimization": When there is no DWP file and we're
7257    using .gdb_index, then when reading a CU we want to stay in the DWO file
7258    containing that CU.  Otherwise we could end up reading several other DWO
7259    files (due to comdat folding) to process the transitive closure of all the
7260    mentioned TUs, and that can be slow.  The current DWO file will have every
7261    type signature that it needs.
7262    We only do this for .gdb_index because in the psymtab case we already have
7263    to read all the DWOs to build the type unit groups.  */
7264
7265 static struct signatured_type *
7266 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7267 {
7268   struct dwarf2_per_objfile *dwarf2_per_objfile
7269     = cu->per_cu->dwarf2_per_objfile;
7270   struct objfile *objfile = dwarf2_per_objfile->objfile;
7271   struct dwo_file *dwo_file;
7272   struct dwo_unit find_dwo_entry, *dwo_entry;
7273   struct signatured_type find_sig_entry, *sig_entry;
7274   void **slot;
7275
7276   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7277
7278   /* If TU skeletons have been removed then we may not have read in any
7279      TUs yet.  */
7280   if (dwarf2_per_objfile->signatured_types == NULL)
7281     {
7282       dwarf2_per_objfile->signatured_types
7283         = allocate_signatured_type_table (objfile);
7284     }
7285
7286   /* We only ever need to read in one copy of a signatured type.
7287      Use the global signatured_types array to do our own comdat-folding
7288      of types.  If this is the first time we're reading this TU, and
7289      the TU has an entry in .gdb_index, replace the recorded data from
7290      .gdb_index with this TU.  */
7291
7292   find_sig_entry.signature = sig;
7293   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7294                          &find_sig_entry, INSERT);
7295   sig_entry = (struct signatured_type *) *slot;
7296
7297   /* We can get here with the TU already read, *or* in the process of being
7298      read.  Don't reassign the global entry to point to this DWO if that's
7299      the case.  Also note that if the TU is already being read, it may not
7300      have come from a DWO, the program may be a mix of Fission-compiled
7301      code and non-Fission-compiled code.  */
7302
7303   /* Have we already tried to read this TU?
7304      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7305      needn't exist in the global table yet).  */
7306   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
7307     return sig_entry;
7308
7309   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
7310      dwo_unit of the TU itself.  */
7311   dwo_file = cu->dwo_unit->dwo_file;
7312
7313   /* Ok, this is the first time we're reading this TU.  */
7314   if (dwo_file->tus == NULL)
7315     return NULL;
7316   find_dwo_entry.signature = sig;
7317   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
7318   if (dwo_entry == NULL)
7319     return NULL;
7320
7321   /* If the global table doesn't have an entry for this TU, add one.  */
7322   if (sig_entry == NULL)
7323     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7324
7325   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7326   sig_entry->per_cu.tu_read = 1;
7327   return sig_entry;
7328 }
7329
7330 /* Subroutine of lookup_signatured_type.
7331    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
7332    then try the DWP file.  If the TU stub (skeleton) has been removed then
7333    it won't be in .gdb_index.  */
7334
7335 static struct signatured_type *
7336 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7337 {
7338   struct dwarf2_per_objfile *dwarf2_per_objfile
7339     = cu->per_cu->dwarf2_per_objfile;
7340   struct objfile *objfile = dwarf2_per_objfile->objfile;
7341   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
7342   struct dwo_unit *dwo_entry;
7343   struct signatured_type find_sig_entry, *sig_entry;
7344   void **slot;
7345
7346   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7347   gdb_assert (dwp_file != NULL);
7348
7349   /* If TU skeletons have been removed then we may not have read in any
7350      TUs yet.  */
7351   if (dwarf2_per_objfile->signatured_types == NULL)
7352     {
7353       dwarf2_per_objfile->signatured_types
7354         = allocate_signatured_type_table (objfile);
7355     }
7356
7357   find_sig_entry.signature = sig;
7358   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7359                          &find_sig_entry, INSERT);
7360   sig_entry = (struct signatured_type *) *slot;
7361
7362   /* Have we already tried to read this TU?
7363      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7364      needn't exist in the global table yet).  */
7365   if (sig_entry != NULL)
7366     return sig_entry;
7367
7368   if (dwp_file->tus == NULL)
7369     return NULL;
7370   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7371                                       sig, 1 /* is_debug_types */);
7372   if (dwo_entry == NULL)
7373     return NULL;
7374
7375   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7376   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7377
7378   return sig_entry;
7379 }
7380
7381 /* Lookup a signature based type for DW_FORM_ref_sig8.
7382    Returns NULL if signature SIG is not present in the table.
7383    It is up to the caller to complain about this.  */
7384
7385 static struct signatured_type *
7386 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7387 {
7388   struct dwarf2_per_objfile *dwarf2_per_objfile
7389     = cu->per_cu->dwarf2_per_objfile;
7390
7391   if (cu->dwo_unit
7392       && dwarf2_per_objfile->using_index)
7393     {
7394       /* We're in a DWO/DWP file, and we're using .gdb_index.
7395          These cases require special processing.  */
7396       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7397         return lookup_dwo_signatured_type (cu, sig);
7398       else
7399         return lookup_dwp_signatured_type (cu, sig);
7400     }
7401   else
7402     {
7403       struct signatured_type find_entry, *entry;
7404
7405       if (dwarf2_per_objfile->signatured_types == NULL)
7406         return NULL;
7407       find_entry.signature = sig;
7408       entry = ((struct signatured_type *)
7409                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7410       return entry;
7411     }
7412 }
7413 \f
7414 /* Low level DIE reading support.  */
7415
7416 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7417
7418 static void
7419 init_cu_die_reader (struct die_reader_specs *reader,
7420                     struct dwarf2_cu *cu,
7421                     struct dwarf2_section_info *section,
7422                     struct dwo_file *dwo_file)
7423 {
7424   gdb_assert (section->readin && section->buffer != NULL);
7425   reader->abfd = get_section_bfd_owner (section);
7426   reader->cu = cu;
7427   reader->dwo_file = dwo_file;
7428   reader->die_section = section;
7429   reader->buffer = section->buffer;
7430   reader->buffer_end = section->buffer + section->size;
7431   reader->comp_dir = NULL;
7432 }
7433
7434 /* Subroutine of init_cutu_and_read_dies to simplify it.
7435    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7436    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7437    already.
7438
7439    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7440    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7441    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7442    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7443    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7444    STUB_COMP_DIR may be non-NULL.
7445    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7446    are filled in with the info of the DIE from the DWO file.
7447    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
7448    provided an abbrev table to use.
7449    The result is non-zero if a valid (non-dummy) DIE was found.  */
7450
7451 static int
7452 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7453                         struct dwo_unit *dwo_unit,
7454                         int abbrev_table_provided,
7455                         struct die_info *stub_comp_unit_die,
7456                         const char *stub_comp_dir,
7457                         struct die_reader_specs *result_reader,
7458                         const gdb_byte **result_info_ptr,
7459                         struct die_info **result_comp_unit_die,
7460                         int *result_has_children)
7461 {
7462   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7463   struct objfile *objfile = dwarf2_per_objfile->objfile;
7464   struct dwarf2_cu *cu = this_cu->cu;
7465   struct dwarf2_section_info *section;
7466   bfd *abfd;
7467   const gdb_byte *begin_info_ptr, *info_ptr;
7468   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7469   int i,num_extra_attrs;
7470   struct dwarf2_section_info *dwo_abbrev_section;
7471   struct attribute *attr;
7472   struct die_info *comp_unit_die;
7473
7474   /* At most one of these may be provided.  */
7475   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7476
7477   /* These attributes aren't processed until later:
7478      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7479      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7480      referenced later.  However, these attributes are found in the stub
7481      which we won't have later.  In order to not impose this complication
7482      on the rest of the code, we read them here and copy them to the
7483      DWO CU/TU die.  */
7484
7485   stmt_list = NULL;
7486   low_pc = NULL;
7487   high_pc = NULL;
7488   ranges = NULL;
7489   comp_dir = NULL;
7490
7491   if (stub_comp_unit_die != NULL)
7492     {
7493       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7494          DWO file.  */
7495       if (! this_cu->is_debug_types)
7496         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7497       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7498       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7499       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7500       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7501
7502       /* There should be a DW_AT_addr_base attribute here (if needed).
7503          We need the value before we can process DW_FORM_GNU_addr_index.  */
7504       cu->addr_base = 0;
7505       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7506       if (attr)
7507         cu->addr_base = DW_UNSND (attr);
7508
7509       /* There should be a DW_AT_ranges_base attribute here (if needed).
7510          We need the value before we can process DW_AT_ranges.  */
7511       cu->ranges_base = 0;
7512       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7513       if (attr)
7514         cu->ranges_base = DW_UNSND (attr);
7515     }
7516   else if (stub_comp_dir != NULL)
7517     {
7518       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7519       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7520       comp_dir->name = DW_AT_comp_dir;
7521       comp_dir->form = DW_FORM_string;
7522       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7523       DW_STRING (comp_dir) = stub_comp_dir;
7524     }
7525
7526   /* Set up for reading the DWO CU/TU.  */
7527   cu->dwo_unit = dwo_unit;
7528   section = dwo_unit->section;
7529   dwarf2_read_section (objfile, section);
7530   abfd = get_section_bfd_owner (section);
7531   begin_info_ptr = info_ptr = (section->buffer
7532                                + to_underlying (dwo_unit->sect_off));
7533   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7534   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
7535
7536   if (this_cu->is_debug_types)
7537     {
7538       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7539
7540       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7541                                                 &cu->header, section,
7542                                                 dwo_abbrev_section,
7543                                                 info_ptr, rcuh_kind::TYPE);
7544       /* This is not an assert because it can be caused by bad debug info.  */
7545       if (sig_type->signature != cu->header.signature)
7546         {
7547           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7548                    " TU at offset 0x%x [in module %s]"),
7549                  hex_string (sig_type->signature),
7550                  hex_string (cu->header.signature),
7551                  to_underlying (dwo_unit->sect_off),
7552                  bfd_get_filename (abfd));
7553         }
7554       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7555       /* For DWOs coming from DWP files, we don't know the CU length
7556          nor the type's offset in the TU until now.  */
7557       dwo_unit->length = get_cu_length (&cu->header);
7558       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7559
7560       /* Establish the type offset that can be used to lookup the type.
7561          For DWO files, we don't know it until now.  */
7562       sig_type->type_offset_in_section
7563         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7564     }
7565   else
7566     {
7567       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7568                                                 &cu->header, section,
7569                                                 dwo_abbrev_section,
7570                                                 info_ptr, rcuh_kind::COMPILE);
7571       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7572       /* For DWOs coming from DWP files, we don't know the CU length
7573          until now.  */
7574       dwo_unit->length = get_cu_length (&cu->header);
7575     }
7576
7577   /* Replace the CU's original abbrev table with the DWO's.
7578      Reminder: We can't read the abbrev table until we've read the header.  */
7579   if (abbrev_table_provided)
7580     {
7581       /* Don't free the provided abbrev table, the caller of
7582          init_cutu_and_read_dies owns it.  */
7583       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7584       /* Ensure the DWO abbrev table gets freed.  */
7585       make_cleanup (dwarf2_free_abbrev_table, cu);
7586     }
7587   else
7588     {
7589       dwarf2_free_abbrev_table (cu);
7590       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
7591       /* Leave any existing abbrev table cleanup as is.  */
7592     }
7593
7594   /* Read in the die, but leave space to copy over the attributes
7595      from the stub.  This has the benefit of simplifying the rest of
7596      the code - all the work to maintain the illusion of a single
7597      DW_TAG_{compile,type}_unit DIE is done here.  */
7598   num_extra_attrs = ((stmt_list != NULL)
7599                      + (low_pc != NULL)
7600                      + (high_pc != NULL)
7601                      + (ranges != NULL)
7602                      + (comp_dir != NULL));
7603   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7604                               result_has_children, num_extra_attrs);
7605
7606   /* Copy over the attributes from the stub to the DIE we just read in.  */
7607   comp_unit_die = *result_comp_unit_die;
7608   i = comp_unit_die->num_attrs;
7609   if (stmt_list != NULL)
7610     comp_unit_die->attrs[i++] = *stmt_list;
7611   if (low_pc != NULL)
7612     comp_unit_die->attrs[i++] = *low_pc;
7613   if (high_pc != NULL)
7614     comp_unit_die->attrs[i++] = *high_pc;
7615   if (ranges != NULL)
7616     comp_unit_die->attrs[i++] = *ranges;
7617   if (comp_dir != NULL)
7618     comp_unit_die->attrs[i++] = *comp_dir;
7619   comp_unit_die->num_attrs += num_extra_attrs;
7620
7621   if (dwarf_die_debug)
7622     {
7623       fprintf_unfiltered (gdb_stdlog,
7624                           "Read die from %s@0x%x of %s:\n",
7625                           get_section_name (section),
7626                           (unsigned) (begin_info_ptr - section->buffer),
7627                           bfd_get_filename (abfd));
7628       dump_die (comp_unit_die, dwarf_die_debug);
7629     }
7630
7631   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7632      TUs by skipping the stub and going directly to the entry in the DWO file.
7633      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7634      to get it via circuitous means.  Blech.  */
7635   if (comp_dir != NULL)
7636     result_reader->comp_dir = DW_STRING (comp_dir);
7637
7638   /* Skip dummy compilation units.  */
7639   if (info_ptr >= begin_info_ptr + dwo_unit->length
7640       || peek_abbrev_code (abfd, info_ptr) == 0)
7641     return 0;
7642
7643   *result_info_ptr = info_ptr;
7644   return 1;
7645 }
7646
7647 /* Subroutine of init_cutu_and_read_dies to simplify it.
7648    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7649    Returns NULL if the specified DWO unit cannot be found.  */
7650
7651 static struct dwo_unit *
7652 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7653                  struct die_info *comp_unit_die)
7654 {
7655   struct dwarf2_cu *cu = this_cu->cu;
7656   ULONGEST signature;
7657   struct dwo_unit *dwo_unit;
7658   const char *comp_dir, *dwo_name;
7659
7660   gdb_assert (cu != NULL);
7661
7662   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7663   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7664   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7665
7666   if (this_cu->is_debug_types)
7667     {
7668       struct signatured_type *sig_type;
7669
7670       /* Since this_cu is the first member of struct signatured_type,
7671          we can go from a pointer to one to a pointer to the other.  */
7672       sig_type = (struct signatured_type *) this_cu;
7673       signature = sig_type->signature;
7674       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7675     }
7676   else
7677     {
7678       struct attribute *attr;
7679
7680       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7681       if (! attr)
7682         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7683                  " [in module %s]"),
7684                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7685       signature = DW_UNSND (attr);
7686       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7687                                        signature);
7688     }
7689
7690   return dwo_unit;
7691 }
7692
7693 /* Subroutine of init_cutu_and_read_dies to simplify it.
7694    See it for a description of the parameters.
7695    Read a TU directly from a DWO file, bypassing the stub.
7696
7697    Note: This function could be a little bit simpler if we shared cleanups
7698    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
7699    to do, so we keep this function self-contained.  Or we could move this
7700    into our caller, but it's complex enough already.  */
7701
7702 static void
7703 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7704                            int use_existing_cu, int keep,
7705                            die_reader_func_ftype *die_reader_func,
7706                            void *data)
7707 {
7708   struct dwarf2_cu *cu;
7709   struct signatured_type *sig_type;
7710   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7711   struct die_reader_specs reader;
7712   const gdb_byte *info_ptr;
7713   struct die_info *comp_unit_die;
7714   int has_children;
7715   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7716
7717   /* Verify we can do the following downcast, and that we have the
7718      data we need.  */
7719   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7720   sig_type = (struct signatured_type *) this_cu;
7721   gdb_assert (sig_type->dwo_unit != NULL);
7722
7723   cleanups = make_cleanup (null_cleanup, NULL);
7724
7725   if (use_existing_cu && this_cu->cu != NULL)
7726     {
7727       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7728       cu = this_cu->cu;
7729       /* There's no need to do the rereading_dwo_cu handling that
7730          init_cutu_and_read_dies does since we don't read the stub.  */
7731     }
7732   else
7733     {
7734       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7735       gdb_assert (this_cu->cu == NULL);
7736       cu = XNEW (struct dwarf2_cu);
7737       init_one_comp_unit (cu, this_cu);
7738       /* If an error occurs while loading, release our storage.  */
7739       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7740     }
7741
7742   /* A future optimization, if needed, would be to use an existing
7743      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7744      could share abbrev tables.  */
7745
7746   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7747                               0 /* abbrev_table_provided */,
7748                               NULL /* stub_comp_unit_die */,
7749                               sig_type->dwo_unit->dwo_file->comp_dir,
7750                               &reader, &info_ptr,
7751                               &comp_unit_die, &has_children) == 0)
7752     {
7753       /* Dummy die.  */
7754       do_cleanups (cleanups);
7755       return;
7756     }
7757
7758   /* All the "real" work is done here.  */
7759   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7760
7761   /* This duplicates the code in init_cutu_and_read_dies,
7762      but the alternative is making the latter more complex.
7763      This function is only for the special case of using DWO files directly:
7764      no point in overly complicating the general case just to handle this.  */
7765   if (free_cu_cleanup != NULL)
7766     {
7767       if (keep)
7768         {
7769           /* We've successfully allocated this compilation unit.  Let our
7770              caller clean it up when finished with it.  */
7771           discard_cleanups (free_cu_cleanup);
7772
7773           /* We can only discard free_cu_cleanup and all subsequent cleanups.
7774              So we have to manually free the abbrev table.  */
7775           dwarf2_free_abbrev_table (cu);
7776
7777           /* Link this CU into read_in_chain.  */
7778           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7779           dwarf2_per_objfile->read_in_chain = this_cu;
7780         }
7781       else
7782         do_cleanups (free_cu_cleanup);
7783     }
7784
7785   do_cleanups (cleanups);
7786 }
7787
7788 /* Initialize a CU (or TU) and read its DIEs.
7789    If the CU defers to a DWO file, read the DWO file as well.
7790
7791    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7792    Otherwise the table specified in the comp unit header is read in and used.
7793    This is an optimization for when we already have the abbrev table.
7794
7795    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7796    Otherwise, a new CU is allocated with xmalloc.
7797
7798    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7799    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7800
7801    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7802    linker) then DIE_READER_FUNC will not get called.  */
7803
7804 static void
7805 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7806                          struct abbrev_table *abbrev_table,
7807                          int use_existing_cu, int keep,
7808                          die_reader_func_ftype *die_reader_func,
7809                          void *data)
7810 {
7811   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7812   struct objfile *objfile = dwarf2_per_objfile->objfile;
7813   struct dwarf2_section_info *section = this_cu->section;
7814   bfd *abfd = get_section_bfd_owner (section);
7815   struct dwarf2_cu *cu;
7816   const gdb_byte *begin_info_ptr, *info_ptr;
7817   struct die_reader_specs reader;
7818   struct die_info *comp_unit_die;
7819   int has_children;
7820   struct attribute *attr;
7821   struct cleanup *cleanups, *free_cu_cleanup = NULL;
7822   struct signatured_type *sig_type = NULL;
7823   struct dwarf2_section_info *abbrev_section;
7824   /* Non-zero if CU currently points to a DWO file and we need to
7825      reread it.  When this happens we need to reread the skeleton die
7826      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7827   int rereading_dwo_cu = 0;
7828
7829   if (dwarf_die_debug)
7830     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
7831                         this_cu->is_debug_types ? "type" : "comp",
7832                         to_underlying (this_cu->sect_off));
7833
7834   if (use_existing_cu)
7835     gdb_assert (keep);
7836
7837   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7838      file (instead of going through the stub), short-circuit all of this.  */
7839   if (this_cu->reading_dwo_directly)
7840     {
7841       /* Narrow down the scope of possibilities to have to understand.  */
7842       gdb_assert (this_cu->is_debug_types);
7843       gdb_assert (abbrev_table == NULL);
7844       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7845                                  die_reader_func, data);
7846       return;
7847     }
7848
7849   cleanups = make_cleanup (null_cleanup, NULL);
7850
7851   /* This is cheap if the section is already read in.  */
7852   dwarf2_read_section (objfile, section);
7853
7854   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7855
7856   abbrev_section = get_abbrev_section_for_cu (this_cu);
7857
7858   if (use_existing_cu && this_cu->cu != NULL)
7859     {
7860       cu = this_cu->cu;
7861       /* If this CU is from a DWO file we need to start over, we need to
7862          refetch the attributes from the skeleton CU.
7863          This could be optimized by retrieving those attributes from when we
7864          were here the first time: the previous comp_unit_die was stored in
7865          comp_unit_obstack.  But there's no data yet that we need this
7866          optimization.  */
7867       if (cu->dwo_unit != NULL)
7868         rereading_dwo_cu = 1;
7869     }
7870   else
7871     {
7872       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7873       gdb_assert (this_cu->cu == NULL);
7874       cu = XNEW (struct dwarf2_cu);
7875       init_one_comp_unit (cu, this_cu);
7876       /* If an error occurs while loading, release our storage.  */
7877       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
7878     }
7879
7880   /* Get the header.  */
7881   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7882     {
7883       /* We already have the header, there's no need to read it in again.  */
7884       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7885     }
7886   else
7887     {
7888       if (this_cu->is_debug_types)
7889         {
7890           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7891                                                     &cu->header, section,
7892                                                     abbrev_section, info_ptr,
7893                                                     rcuh_kind::TYPE);
7894
7895           /* Since per_cu is the first member of struct signatured_type,
7896              we can go from a pointer to one to a pointer to the other.  */
7897           sig_type = (struct signatured_type *) this_cu;
7898           gdb_assert (sig_type->signature == cu->header.signature);
7899           gdb_assert (sig_type->type_offset_in_tu
7900                       == cu->header.type_cu_offset_in_tu);
7901           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7902
7903           /* LENGTH has not been set yet for type units if we're
7904              using .gdb_index.  */
7905           this_cu->length = get_cu_length (&cu->header);
7906
7907           /* Establish the type offset that can be used to lookup the type.  */
7908           sig_type->type_offset_in_section =
7909             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7910
7911           this_cu->dwarf_version = cu->header.version;
7912         }
7913       else
7914         {
7915           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7916                                                     &cu->header, section,
7917                                                     abbrev_section,
7918                                                     info_ptr,
7919                                                     rcuh_kind::COMPILE);
7920
7921           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7922           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7923           this_cu->dwarf_version = cu->header.version;
7924         }
7925     }
7926
7927   /* Skip dummy compilation units.  */
7928   if (info_ptr >= begin_info_ptr + this_cu->length
7929       || peek_abbrev_code (abfd, info_ptr) == 0)
7930     {
7931       do_cleanups (cleanups);
7932       return;
7933     }
7934
7935   /* If we don't have them yet, read the abbrevs for this compilation unit.
7936      And if we need to read them now, make sure they're freed when we're
7937      done.  Note that it's important that if the CU had an abbrev table
7938      on entry we don't free it when we're done: Somewhere up the call stack
7939      it may be in use.  */
7940   if (abbrev_table != NULL)
7941     {
7942       gdb_assert (cu->abbrev_table == NULL);
7943       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7944       cu->abbrev_table = abbrev_table;
7945     }
7946   else if (cu->abbrev_table == NULL)
7947     {
7948       dwarf2_read_abbrevs (cu, abbrev_section);
7949       make_cleanup (dwarf2_free_abbrev_table, cu);
7950     }
7951   else if (rereading_dwo_cu)
7952     {
7953       dwarf2_free_abbrev_table (cu);
7954       dwarf2_read_abbrevs (cu, abbrev_section);
7955     }
7956
7957   /* Read the top level CU/TU die.  */
7958   init_cu_die_reader (&reader, cu, section, NULL);
7959   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7960
7961   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7962      from the DWO file.
7963      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7964      DWO CU, that this test will fail (the attribute will not be present).  */
7965   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7966   if (attr)
7967     {
7968       struct dwo_unit *dwo_unit;
7969       struct die_info *dwo_comp_unit_die;
7970
7971       if (has_children)
7972         {
7973           complaint (&symfile_complaints,
7974                      _("compilation unit with DW_AT_GNU_dwo_name"
7975                        " has children (offset 0x%x) [in module %s]"),
7976                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
7977         }
7978       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7979       if (dwo_unit != NULL)
7980         {
7981           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7982                                       abbrev_table != NULL,
7983                                       comp_unit_die, NULL,
7984                                       &reader, &info_ptr,
7985                                       &dwo_comp_unit_die, &has_children) == 0)
7986             {
7987               /* Dummy die.  */
7988               do_cleanups (cleanups);
7989               return;
7990             }
7991           comp_unit_die = dwo_comp_unit_die;
7992         }
7993       else
7994         {
7995           /* Yikes, we couldn't find the rest of the DIE, we only have
7996              the stub.  A complaint has already been logged.  There's
7997              not much more we can do except pass on the stub DIE to
7998              die_reader_func.  We don't want to throw an error on bad
7999              debug info.  */
8000         }
8001     }
8002
8003   /* All of the above is setup for this call.  Yikes.  */
8004   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8005
8006   /* Done, clean up.  */
8007   if (free_cu_cleanup != NULL)
8008     {
8009       if (keep)
8010         {
8011           /* We've successfully allocated this compilation unit.  Let our
8012              caller clean it up when finished with it.  */
8013           discard_cleanups (free_cu_cleanup);
8014
8015           /* We can only discard free_cu_cleanup and all subsequent cleanups.
8016              So we have to manually free the abbrev table.  */
8017           dwarf2_free_abbrev_table (cu);
8018
8019           /* Link this CU into read_in_chain.  */
8020           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
8021           dwarf2_per_objfile->read_in_chain = this_cu;
8022         }
8023       else
8024         do_cleanups (free_cu_cleanup);
8025     }
8026
8027   do_cleanups (cleanups);
8028 }
8029
8030 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
8031    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
8032    to have already done the lookup to find the DWO file).
8033
8034    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
8035    THIS_CU->is_debug_types, but nothing else.
8036
8037    We fill in THIS_CU->length.
8038
8039    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
8040    linker) then DIE_READER_FUNC will not get called.
8041
8042    THIS_CU->cu is always freed when done.
8043    This is done in order to not leave THIS_CU->cu in a state where we have
8044    to care whether it refers to the "main" CU or the DWO CU.  */
8045
8046 static void
8047 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
8048                                    struct dwo_file *dwo_file,
8049                                    die_reader_func_ftype *die_reader_func,
8050                                    void *data)
8051 {
8052   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
8053   struct objfile *objfile = dwarf2_per_objfile->objfile;
8054   struct dwarf2_section_info *section = this_cu->section;
8055   bfd *abfd = get_section_bfd_owner (section);
8056   struct dwarf2_section_info *abbrev_section;
8057   struct dwarf2_cu cu;
8058   const gdb_byte *begin_info_ptr, *info_ptr;
8059   struct die_reader_specs reader;
8060   struct cleanup *cleanups;
8061   struct die_info *comp_unit_die;
8062   int has_children;
8063
8064   if (dwarf_die_debug)
8065     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
8066                         this_cu->is_debug_types ? "type" : "comp",
8067                         to_underlying (this_cu->sect_off));
8068
8069   gdb_assert (this_cu->cu == NULL);
8070
8071   abbrev_section = (dwo_file != NULL
8072                     ? &dwo_file->sections.abbrev
8073                     : get_abbrev_section_for_cu (this_cu));
8074
8075   /* This is cheap if the section is already read in.  */
8076   dwarf2_read_section (objfile, section);
8077
8078   init_one_comp_unit (&cu, this_cu);
8079
8080   cleanups = make_cleanup (free_stack_comp_unit, &cu);
8081
8082   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
8083   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
8084                                             &cu.header, section,
8085                                             abbrev_section, info_ptr,
8086                                             (this_cu->is_debug_types
8087                                              ? rcuh_kind::TYPE
8088                                              : rcuh_kind::COMPILE));
8089
8090   this_cu->length = get_cu_length (&cu.header);
8091
8092   /* Skip dummy compilation units.  */
8093   if (info_ptr >= begin_info_ptr + this_cu->length
8094       || peek_abbrev_code (abfd, info_ptr) == 0)
8095     {
8096       do_cleanups (cleanups);
8097       return;
8098     }
8099
8100   dwarf2_read_abbrevs (&cu, abbrev_section);
8101   make_cleanup (dwarf2_free_abbrev_table, &cu);
8102
8103   init_cu_die_reader (&reader, &cu, section, dwo_file);
8104   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
8105
8106   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
8107
8108   do_cleanups (cleanups);
8109 }
8110
8111 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
8112    does not lookup the specified DWO file.
8113    This cannot be used to read DWO files.
8114
8115    THIS_CU->cu is always freed when done.
8116    This is done in order to not leave THIS_CU->cu in a state where we have
8117    to care whether it refers to the "main" CU or the DWO CU.
8118    We can revisit this if the data shows there's a performance issue.  */
8119
8120 static void
8121 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
8122                                 die_reader_func_ftype *die_reader_func,
8123                                 void *data)
8124 {
8125   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
8126 }
8127 \f
8128 /* Type Unit Groups.
8129
8130    Type Unit Groups are a way to collapse the set of all TUs (type units) into
8131    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
8132    so that all types coming from the same compilation (.o file) are grouped
8133    together.  A future step could be to put the types in the same symtab as
8134    the CU the types ultimately came from.  */
8135
8136 static hashval_t
8137 hash_type_unit_group (const void *item)
8138 {
8139   const struct type_unit_group *tu_group
8140     = (const struct type_unit_group *) item;
8141
8142   return hash_stmt_list_entry (&tu_group->hash);
8143 }
8144
8145 static int
8146 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
8147 {
8148   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
8149   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
8150
8151   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
8152 }
8153
8154 /* Allocate a hash table for type unit groups.  */
8155
8156 static htab_t
8157 allocate_type_unit_groups_table (struct objfile *objfile)
8158 {
8159   return htab_create_alloc_ex (3,
8160                                hash_type_unit_group,
8161                                eq_type_unit_group,
8162                                NULL,
8163                                &objfile->objfile_obstack,
8164                                hashtab_obstack_allocate,
8165                                dummy_obstack_deallocate);
8166 }
8167
8168 /* Type units that don't have DW_AT_stmt_list are grouped into their own
8169    partial symtabs.  We combine several TUs per psymtab to not let the size
8170    of any one psymtab grow too big.  */
8171 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
8172 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
8173
8174 /* Helper routine for get_type_unit_group.
8175    Create the type_unit_group object used to hold one or more TUs.  */
8176
8177 static struct type_unit_group *
8178 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
8179 {
8180   struct dwarf2_per_objfile *dwarf2_per_objfile
8181     = cu->per_cu->dwarf2_per_objfile;
8182   struct objfile *objfile = dwarf2_per_objfile->objfile;
8183   struct dwarf2_per_cu_data *per_cu;
8184   struct type_unit_group *tu_group;
8185
8186   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8187                              struct type_unit_group);
8188   per_cu = &tu_group->per_cu;
8189   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8190
8191   if (dwarf2_per_objfile->using_index)
8192     {
8193       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
8194                                         struct dwarf2_per_cu_quick_data);
8195     }
8196   else
8197     {
8198       unsigned int line_offset = to_underlying (line_offset_struct);
8199       struct partial_symtab *pst;
8200       char *name;
8201
8202       /* Give the symtab a useful name for debug purposes.  */
8203       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
8204         name = xstrprintf ("<type_units_%d>",
8205                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
8206       else
8207         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
8208
8209       pst = create_partial_symtab (per_cu, name);
8210       pst->anonymous = 1;
8211
8212       xfree (name);
8213     }
8214
8215   tu_group->hash.dwo_unit = cu->dwo_unit;
8216   tu_group->hash.line_sect_off = line_offset_struct;
8217
8218   return tu_group;
8219 }
8220
8221 /* Look up the type_unit_group for type unit CU, and create it if necessary.
8222    STMT_LIST is a DW_AT_stmt_list attribute.  */
8223
8224 static struct type_unit_group *
8225 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
8226 {
8227   struct dwarf2_per_objfile *dwarf2_per_objfile
8228     = cu->per_cu->dwarf2_per_objfile;
8229   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8230   struct type_unit_group *tu_group;
8231   void **slot;
8232   unsigned int line_offset;
8233   struct type_unit_group type_unit_group_for_lookup;
8234
8235   if (dwarf2_per_objfile->type_unit_groups == NULL)
8236     {
8237       dwarf2_per_objfile->type_unit_groups =
8238         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
8239     }
8240
8241   /* Do we need to create a new group, or can we use an existing one?  */
8242
8243   if (stmt_list)
8244     {
8245       line_offset = DW_UNSND (stmt_list);
8246       ++tu_stats->nr_symtab_sharers;
8247     }
8248   else
8249     {
8250       /* Ugh, no stmt_list.  Rare, but we have to handle it.
8251          We can do various things here like create one group per TU or
8252          spread them over multiple groups to split up the expansion work.
8253          To avoid worst case scenarios (too many groups or too large groups)
8254          we, umm, group them in bunches.  */
8255       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
8256                      | (tu_stats->nr_stmt_less_type_units
8257                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
8258       ++tu_stats->nr_stmt_less_type_units;
8259     }
8260
8261   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
8262   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
8263   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
8264                          &type_unit_group_for_lookup, INSERT);
8265   if (*slot != NULL)
8266     {
8267       tu_group = (struct type_unit_group *) *slot;
8268       gdb_assert (tu_group != NULL);
8269     }
8270   else
8271     {
8272       sect_offset line_offset_struct = (sect_offset) line_offset;
8273       tu_group = create_type_unit_group (cu, line_offset_struct);
8274       *slot = tu_group;
8275       ++tu_stats->nr_symtabs;
8276     }
8277
8278   return tu_group;
8279 }
8280 \f
8281 /* Partial symbol tables.  */
8282
8283 /* Create a psymtab named NAME and assign it to PER_CU.
8284
8285    The caller must fill in the following details:
8286    dirname, textlow, texthigh.  */
8287
8288 static struct partial_symtab *
8289 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
8290 {
8291   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
8292   struct partial_symtab *pst;
8293
8294   pst = start_psymtab_common (objfile, name, 0,
8295                               objfile->global_psymbols,
8296                               objfile->static_psymbols);
8297
8298   pst->psymtabs_addrmap_supported = 1;
8299
8300   /* This is the glue that links PST into GDB's symbol API.  */
8301   pst->read_symtab_private = per_cu;
8302   pst->read_symtab = dwarf2_read_symtab;
8303   per_cu->v.psymtab = pst;
8304
8305   return pst;
8306 }
8307
8308 /* The DATA object passed to process_psymtab_comp_unit_reader has this
8309    type.  */
8310
8311 struct process_psymtab_comp_unit_data
8312 {
8313   /* True if we are reading a DW_TAG_partial_unit.  */
8314
8315   int want_partial_unit;
8316
8317   /* The "pretend" language that is used if the CU doesn't declare a
8318      language.  */
8319
8320   enum language pretend_language;
8321 };
8322
8323 /* die_reader_func for process_psymtab_comp_unit.  */
8324
8325 static void
8326 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
8327                                   const gdb_byte *info_ptr,
8328                                   struct die_info *comp_unit_die,
8329                                   int has_children,
8330                                   void *data)
8331 {
8332   struct dwarf2_cu *cu = reader->cu;
8333   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
8334   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8335   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8336   CORE_ADDR baseaddr;
8337   CORE_ADDR best_lowpc = 0, best_highpc = 0;
8338   struct partial_symtab *pst;
8339   enum pc_bounds_kind cu_bounds_kind;
8340   const char *filename;
8341   struct process_psymtab_comp_unit_data *info
8342     = (struct process_psymtab_comp_unit_data *) data;
8343
8344   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
8345     return;
8346
8347   gdb_assert (! per_cu->is_debug_types);
8348
8349   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
8350
8351   cu->list_in_scope = &file_symbols;
8352
8353   /* Allocate a new partial symbol table structure.  */
8354   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
8355   if (filename == NULL)
8356     filename = "";
8357
8358   pst = create_partial_symtab (per_cu, filename);
8359
8360   /* This must be done before calling dwarf2_build_include_psymtabs.  */
8361   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
8362
8363   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8364
8365   dwarf2_find_base_address (comp_unit_die, cu);
8366
8367   /* Possibly set the default values of LOWPC and HIGHPC from
8368      `DW_AT_ranges'.  */
8369   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
8370                                          &best_highpc, cu, pst);
8371   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
8372     /* Store the contiguous range if it is not empty; it can be empty for
8373        CUs with no code.  */
8374     addrmap_set_empty (objfile->psymtabs_addrmap,
8375                        gdbarch_adjust_dwarf2_addr (gdbarch,
8376                                                    best_lowpc + baseaddr),
8377                        gdbarch_adjust_dwarf2_addr (gdbarch,
8378                                                    best_highpc + baseaddr) - 1,
8379                        pst);
8380
8381   /* Check if comp unit has_children.
8382      If so, read the rest of the partial symbols from this comp unit.
8383      If not, there's no more debug_info for this comp unit.  */
8384   if (has_children)
8385     {
8386       struct partial_die_info *first_die;
8387       CORE_ADDR lowpc, highpc;
8388
8389       lowpc = ((CORE_ADDR) -1);
8390       highpc = ((CORE_ADDR) 0);
8391
8392       first_die = load_partial_dies (reader, info_ptr, 1);
8393
8394       scan_partial_symbols (first_die, &lowpc, &highpc,
8395                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
8396
8397       /* If we didn't find a lowpc, set it to highpc to avoid
8398          complaints from `maint check'.  */
8399       if (lowpc == ((CORE_ADDR) -1))
8400         lowpc = highpc;
8401
8402       /* If the compilation unit didn't have an explicit address range,
8403          then use the information extracted from its child dies.  */
8404       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
8405         {
8406           best_lowpc = lowpc;
8407           best_highpc = highpc;
8408         }
8409     }
8410   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
8411   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
8412
8413   end_psymtab_common (objfile, pst);
8414
8415   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8416     {
8417       int i;
8418       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8419       struct dwarf2_per_cu_data *iter;
8420
8421       /* Fill in 'dependencies' here; we fill in 'users' in a
8422          post-pass.  */
8423       pst->number_of_dependencies = len;
8424       pst->dependencies =
8425         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8426       for (i = 0;
8427            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8428                         i, iter);
8429            ++i)
8430         pst->dependencies[i] = iter->v.psymtab;
8431
8432       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8433     }
8434
8435   /* Get the list of files included in the current compilation unit,
8436      and build a psymtab for each of them.  */
8437   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8438
8439   if (dwarf_read_debug)
8440     {
8441       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8442
8443       fprintf_unfiltered (gdb_stdlog,
8444                           "Psymtab for %s unit @0x%x: %s - %s"
8445                           ", %d global, %d static syms\n",
8446                           per_cu->is_debug_types ? "type" : "comp",
8447                           to_underlying (per_cu->sect_off),
8448                           paddress (gdbarch, pst->textlow),
8449                           paddress (gdbarch, pst->texthigh),
8450                           pst->n_global_syms, pst->n_static_syms);
8451     }
8452 }
8453
8454 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8455    Process compilation unit THIS_CU for a psymtab.  */
8456
8457 static void
8458 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8459                            int want_partial_unit,
8460                            enum language pretend_language)
8461 {
8462   /* If this compilation unit was already read in, free the
8463      cached copy in order to read it in again.  This is
8464      necessary because we skipped some symbols when we first
8465      read in the compilation unit (see load_partial_dies).
8466      This problem could be avoided, but the benefit is unclear.  */
8467   if (this_cu->cu != NULL)
8468     free_one_cached_comp_unit (this_cu);
8469
8470   if (this_cu->is_debug_types)
8471     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
8472                              NULL);
8473   else
8474     {
8475       process_psymtab_comp_unit_data info;
8476       info.want_partial_unit = want_partial_unit;
8477       info.pretend_language = pretend_language;
8478       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
8479                                process_psymtab_comp_unit_reader, &info);
8480     }
8481
8482   /* Age out any secondary CUs.  */
8483   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8484 }
8485
8486 /* Reader function for build_type_psymtabs.  */
8487
8488 static void
8489 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8490                             const gdb_byte *info_ptr,
8491                             struct die_info *type_unit_die,
8492                             int has_children,
8493                             void *data)
8494 {
8495   struct dwarf2_per_objfile *dwarf2_per_objfile
8496     = reader->cu->per_cu->dwarf2_per_objfile;
8497   struct objfile *objfile = dwarf2_per_objfile->objfile;
8498   struct dwarf2_cu *cu = reader->cu;
8499   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8500   struct signatured_type *sig_type;
8501   struct type_unit_group *tu_group;
8502   struct attribute *attr;
8503   struct partial_die_info *first_die;
8504   CORE_ADDR lowpc, highpc;
8505   struct partial_symtab *pst;
8506
8507   gdb_assert (data == NULL);
8508   gdb_assert (per_cu->is_debug_types);
8509   sig_type = (struct signatured_type *) per_cu;
8510
8511   if (! has_children)
8512     return;
8513
8514   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8515   tu_group = get_type_unit_group (cu, attr);
8516
8517   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8518
8519   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8520   cu->list_in_scope = &file_symbols;
8521   pst = create_partial_symtab (per_cu, "");
8522   pst->anonymous = 1;
8523
8524   first_die = load_partial_dies (reader, info_ptr, 1);
8525
8526   lowpc = (CORE_ADDR) -1;
8527   highpc = (CORE_ADDR) 0;
8528   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8529
8530   end_psymtab_common (objfile, pst);
8531 }
8532
8533 /* Struct used to sort TUs by their abbreviation table offset.  */
8534
8535 struct tu_abbrev_offset
8536 {
8537   struct signatured_type *sig_type;
8538   sect_offset abbrev_offset;
8539 };
8540
8541 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
8542
8543 static int
8544 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
8545 {
8546   const struct tu_abbrev_offset * const *a
8547     = (const struct tu_abbrev_offset * const*) ap;
8548   const struct tu_abbrev_offset * const *b
8549     = (const struct tu_abbrev_offset * const*) bp;
8550   sect_offset aoff = (*a)->abbrev_offset;
8551   sect_offset boff = (*b)->abbrev_offset;
8552
8553   return (aoff > boff) - (aoff < boff);
8554 }
8555
8556 /* Efficiently read all the type units.
8557    This does the bulk of the work for build_type_psymtabs.
8558
8559    The efficiency is because we sort TUs by the abbrev table they use and
8560    only read each abbrev table once.  In one program there are 200K TUs
8561    sharing 8K abbrev tables.
8562
8563    The main purpose of this function is to support building the
8564    dwarf2_per_objfile->type_unit_groups table.
8565    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8566    can collapse the search space by grouping them by stmt_list.
8567    The savings can be significant, in the same program from above the 200K TUs
8568    share 8K stmt_list tables.
8569
8570    FUNC is expected to call get_type_unit_group, which will create the
8571    struct type_unit_group if necessary and add it to
8572    dwarf2_per_objfile->type_unit_groups.  */
8573
8574 static void
8575 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8576 {
8577   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8578   struct cleanup *cleanups;
8579   struct abbrev_table *abbrev_table;
8580   sect_offset abbrev_offset;
8581   struct tu_abbrev_offset *sorted_by_abbrev;
8582   int i;
8583
8584   /* It's up to the caller to not call us multiple times.  */
8585   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8586
8587   if (dwarf2_per_objfile->n_type_units == 0)
8588     return;
8589
8590   /* TUs typically share abbrev tables, and there can be way more TUs than
8591      abbrev tables.  Sort by abbrev table to reduce the number of times we
8592      read each abbrev table in.
8593      Alternatives are to punt or to maintain a cache of abbrev tables.
8594      This is simpler and efficient enough for now.
8595
8596      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8597      symtab to use).  Typically TUs with the same abbrev offset have the same
8598      stmt_list value too so in practice this should work well.
8599
8600      The basic algorithm here is:
8601
8602       sort TUs by abbrev table
8603       for each TU with same abbrev table:
8604         read abbrev table if first user
8605         read TU top level DIE
8606           [IWBN if DWO skeletons had DW_AT_stmt_list]
8607         call FUNC  */
8608
8609   if (dwarf_read_debug)
8610     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8611
8612   /* Sort in a separate table to maintain the order of all_type_units
8613      for .gdb_index: TU indices directly index all_type_units.  */
8614   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
8615                               dwarf2_per_objfile->n_type_units);
8616   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8617     {
8618       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
8619
8620       sorted_by_abbrev[i].sig_type = sig_type;
8621       sorted_by_abbrev[i].abbrev_offset =
8622         read_abbrev_offset (dwarf2_per_objfile,
8623                             sig_type->per_cu.section,
8624                             sig_type->per_cu.sect_off);
8625     }
8626   cleanups = make_cleanup (xfree, sorted_by_abbrev);
8627   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
8628          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
8629
8630   abbrev_offset = (sect_offset) ~(unsigned) 0;
8631   abbrev_table = NULL;
8632   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
8633
8634   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
8635     {
8636       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
8637
8638       /* Switch to the next abbrev table if necessary.  */
8639       if (abbrev_table == NULL
8640           || tu->abbrev_offset != abbrev_offset)
8641         {
8642           if (abbrev_table != NULL)
8643             {
8644               abbrev_table_free (abbrev_table);
8645               /* Reset to NULL in case abbrev_table_read_table throws
8646                  an error: abbrev_table_free_cleanup will get called.  */
8647               abbrev_table = NULL;
8648             }
8649           abbrev_offset = tu->abbrev_offset;
8650           abbrev_table =
8651             abbrev_table_read_table (dwarf2_per_objfile,
8652                                      &dwarf2_per_objfile->abbrev,
8653                                      abbrev_offset);
8654           ++tu_stats->nr_uniq_abbrev_tables;
8655         }
8656
8657       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
8658                                build_type_psymtabs_reader, NULL);
8659     }
8660
8661   do_cleanups (cleanups);
8662 }
8663
8664 /* Print collected type unit statistics.  */
8665
8666 static void
8667 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8668 {
8669   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8670
8671   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8672   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
8673                       dwarf2_per_objfile->n_type_units);
8674   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8675                       tu_stats->nr_uniq_abbrev_tables);
8676   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8677                       tu_stats->nr_symtabs);
8678   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8679                       tu_stats->nr_symtab_sharers);
8680   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8681                       tu_stats->nr_stmt_less_type_units);
8682   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8683                       tu_stats->nr_all_type_units_reallocs);
8684 }
8685
8686 /* Traversal function for build_type_psymtabs.  */
8687
8688 static int
8689 build_type_psymtab_dependencies (void **slot, void *info)
8690 {
8691   struct dwarf2_per_objfile *dwarf2_per_objfile
8692     = (struct dwarf2_per_objfile *) info;
8693   struct objfile *objfile = dwarf2_per_objfile->objfile;
8694   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8695   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8696   struct partial_symtab *pst = per_cu->v.psymtab;
8697   int len = VEC_length (sig_type_ptr, tu_group->tus);
8698   struct signatured_type *iter;
8699   int i;
8700
8701   gdb_assert (len > 0);
8702   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8703
8704   pst->number_of_dependencies = len;
8705   pst->dependencies =
8706     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8707   for (i = 0;
8708        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8709        ++i)
8710     {
8711       gdb_assert (iter->per_cu.is_debug_types);
8712       pst->dependencies[i] = iter->per_cu.v.psymtab;
8713       iter->type_unit_group = tu_group;
8714     }
8715
8716   VEC_free (sig_type_ptr, tu_group->tus);
8717
8718   return 1;
8719 }
8720
8721 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8722    Build partial symbol tables for the .debug_types comp-units.  */
8723
8724 static void
8725 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8726 {
8727   if (! create_all_type_units (dwarf2_per_objfile))
8728     return;
8729
8730   build_type_psymtabs_1 (dwarf2_per_objfile);
8731 }
8732
8733 /* Traversal function for process_skeletonless_type_unit.
8734    Read a TU in a DWO file and build partial symbols for it.  */
8735
8736 static int
8737 process_skeletonless_type_unit (void **slot, void *info)
8738 {
8739   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8740   struct dwarf2_per_objfile *dwarf2_per_objfile
8741     = (struct dwarf2_per_objfile *) info;
8742   struct signatured_type find_entry, *entry;
8743
8744   /* If this TU doesn't exist in the global table, add it and read it in.  */
8745
8746   if (dwarf2_per_objfile->signatured_types == NULL)
8747     {
8748       dwarf2_per_objfile->signatured_types
8749         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8750     }
8751
8752   find_entry.signature = dwo_unit->signature;
8753   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8754                          INSERT);
8755   /* If we've already seen this type there's nothing to do.  What's happening
8756      is we're doing our own version of comdat-folding here.  */
8757   if (*slot != NULL)
8758     return 1;
8759
8760   /* This does the job that create_all_type_units would have done for
8761      this TU.  */
8762   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8763   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8764   *slot = entry;
8765
8766   /* This does the job that build_type_psymtabs_1 would have done.  */
8767   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
8768                            build_type_psymtabs_reader, NULL);
8769
8770   return 1;
8771 }
8772
8773 /* Traversal function for process_skeletonless_type_units.  */
8774
8775 static int
8776 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8777 {
8778   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8779
8780   if (dwo_file->tus != NULL)
8781     {
8782       htab_traverse_noresize (dwo_file->tus,
8783                               process_skeletonless_type_unit, info);
8784     }
8785
8786   return 1;
8787 }
8788
8789 /* Scan all TUs of DWO files, verifying we've processed them.
8790    This is needed in case a TU was emitted without its skeleton.
8791    Note: This can't be done until we know what all the DWO files are.  */
8792
8793 static void
8794 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8795 {
8796   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8797   if (get_dwp_file (dwarf2_per_objfile) == NULL
8798       && dwarf2_per_objfile->dwo_files != NULL)
8799     {
8800       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8801                               process_dwo_file_for_skeletonless_type_units,
8802                               dwarf2_per_objfile);
8803     }
8804 }
8805
8806 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8807
8808 static void
8809 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8810 {
8811   int i;
8812
8813   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8814     {
8815       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8816       struct partial_symtab *pst = per_cu->v.psymtab;
8817       int j;
8818
8819       if (pst == NULL)
8820         continue;
8821
8822       for (j = 0; j < pst->number_of_dependencies; ++j)
8823         {
8824           /* Set the 'user' field only if it is not already set.  */
8825           if (pst->dependencies[j]->user == NULL)
8826             pst->dependencies[j]->user = pst;
8827         }
8828     }
8829 }
8830
8831 /* Build the partial symbol table by doing a quick pass through the
8832    .debug_info and .debug_abbrev sections.  */
8833
8834 static void
8835 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8836 {
8837   struct cleanup *back_to;
8838   int i;
8839   struct objfile *objfile = dwarf2_per_objfile->objfile;
8840
8841   if (dwarf_read_debug)
8842     {
8843       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8844                           objfile_name (objfile));
8845     }
8846
8847   dwarf2_per_objfile->reading_partial_symbols = 1;
8848
8849   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8850
8851   /* Any cached compilation units will be linked by the per-objfile
8852      read_in_chain.  Make sure to free them when we're done.  */
8853   back_to = make_cleanup (free_cached_comp_units, dwarf2_per_objfile);
8854
8855   build_type_psymtabs (dwarf2_per_objfile);
8856
8857   create_all_comp_units (dwarf2_per_objfile);
8858
8859   /* Create a temporary address map on a temporary obstack.  We later
8860      copy this to the final obstack.  */
8861   auto_obstack temp_obstack;
8862
8863   scoped_restore save_psymtabs_addrmap
8864     = make_scoped_restore (&objfile->psymtabs_addrmap,
8865                            addrmap_create_mutable (&temp_obstack));
8866
8867   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
8868     {
8869       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (dwarf2_per_objfile, i);
8870
8871       process_psymtab_comp_unit (per_cu, 0, language_minimal);
8872     }
8873
8874   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8875   process_skeletonless_type_units (dwarf2_per_objfile);
8876
8877   /* Now that all TUs have been processed we can fill in the dependencies.  */
8878   if (dwarf2_per_objfile->type_unit_groups != NULL)
8879     {
8880       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8881                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8882     }
8883
8884   if (dwarf_read_debug)
8885     print_tu_stats (dwarf2_per_objfile);
8886
8887   set_partial_user (dwarf2_per_objfile);
8888
8889   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8890                                                     &objfile->objfile_obstack);
8891   /* At this point we want to keep the address map.  */
8892   save_psymtabs_addrmap.release ();
8893
8894   do_cleanups (back_to);
8895
8896   if (dwarf_read_debug)
8897     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8898                         objfile_name (objfile));
8899 }
8900
8901 /* die_reader_func for load_partial_comp_unit.  */
8902
8903 static void
8904 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8905                                const gdb_byte *info_ptr,
8906                                struct die_info *comp_unit_die,
8907                                int has_children,
8908                                void *data)
8909 {
8910   struct dwarf2_cu *cu = reader->cu;
8911
8912   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8913
8914   /* Check if comp unit has_children.
8915      If so, read the rest of the partial symbols from this comp unit.
8916      If not, there's no more debug_info for this comp unit.  */
8917   if (has_children)
8918     load_partial_dies (reader, info_ptr, 0);
8919 }
8920
8921 /* Load the partial DIEs for a secondary CU into memory.
8922    This is also used when rereading a primary CU with load_all_dies.  */
8923
8924 static void
8925 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8926 {
8927   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8928                            load_partial_comp_unit_reader, NULL);
8929 }
8930
8931 static void
8932 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8933                               struct dwarf2_section_info *section,
8934                               struct dwarf2_section_info *abbrev_section,
8935                               unsigned int is_dwz,
8936                               int *n_allocated,
8937                               int *n_comp_units,
8938                               struct dwarf2_per_cu_data ***all_comp_units)
8939 {
8940   const gdb_byte *info_ptr;
8941   struct objfile *objfile = dwarf2_per_objfile->objfile;
8942
8943   if (dwarf_read_debug)
8944     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8945                         get_section_name (section),
8946                         get_section_file_name (section));
8947
8948   dwarf2_read_section (objfile, section);
8949
8950   info_ptr = section->buffer;
8951
8952   while (info_ptr < section->buffer + section->size)
8953     {
8954       struct dwarf2_per_cu_data *this_cu;
8955
8956       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8957
8958       comp_unit_head cu_header;
8959       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8960                                      abbrev_section, info_ptr,
8961                                      rcuh_kind::COMPILE);
8962
8963       /* Save the compilation unit for later lookup.  */
8964       if (cu_header.unit_type != DW_UT_type)
8965         {
8966           this_cu = XOBNEW (&objfile->objfile_obstack,
8967                             struct dwarf2_per_cu_data);
8968           memset (this_cu, 0, sizeof (*this_cu));
8969         }
8970       else
8971         {
8972           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8973                                   struct signatured_type);
8974           memset (sig_type, 0, sizeof (*sig_type));
8975           sig_type->signature = cu_header.signature;
8976           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8977           this_cu = &sig_type->per_cu;
8978         }
8979       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8980       this_cu->sect_off = sect_off;
8981       this_cu->length = cu_header.length + cu_header.initial_length_size;
8982       this_cu->is_dwz = is_dwz;
8983       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8984       this_cu->section = section;
8985
8986       if (*n_comp_units == *n_allocated)
8987         {
8988           *n_allocated *= 2;
8989           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
8990                                         *all_comp_units, *n_allocated);
8991         }
8992       (*all_comp_units)[*n_comp_units] = this_cu;
8993       ++*n_comp_units;
8994
8995       info_ptr = info_ptr + this_cu->length;
8996     }
8997 }
8998
8999 /* Create a list of all compilation units in OBJFILE.
9000    This is only done for -readnow and building partial symtabs.  */
9001
9002 static void
9003 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
9004 {
9005   int n_allocated;
9006   int n_comp_units;
9007   struct dwarf2_per_cu_data **all_comp_units;
9008   struct dwz_file *dwz;
9009   struct objfile *objfile = dwarf2_per_objfile->objfile;
9010
9011   n_comp_units = 0;
9012   n_allocated = 10;
9013   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
9014
9015   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
9016                                 &dwarf2_per_objfile->abbrev, 0,
9017                                 &n_allocated, &n_comp_units, &all_comp_units);
9018
9019   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
9020   if (dwz != NULL)
9021     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
9022                                   1, &n_allocated, &n_comp_units,
9023                                   &all_comp_units);
9024
9025   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
9026                                                   struct dwarf2_per_cu_data *,
9027                                                   n_comp_units);
9028   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
9029           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
9030   xfree (all_comp_units);
9031   dwarf2_per_objfile->n_comp_units = n_comp_units;
9032 }
9033
9034 /* Process all loaded DIEs for compilation unit CU, starting at
9035    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
9036    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
9037    DW_AT_ranges).  See the comments of add_partial_subprogram on how
9038    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
9039
9040 static void
9041 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
9042                       CORE_ADDR *highpc, int set_addrmap,
9043                       struct dwarf2_cu *cu)
9044 {
9045   struct partial_die_info *pdi;
9046
9047   /* Now, march along the PDI's, descending into ones which have
9048      interesting children but skipping the children of the other ones,
9049      until we reach the end of the compilation unit.  */
9050
9051   pdi = first_die;
9052
9053   while (pdi != NULL)
9054     {
9055       fixup_partial_die (pdi, cu);
9056
9057       /* Anonymous namespaces or modules have no name but have interesting
9058          children, so we need to look at them.  Ditto for anonymous
9059          enums.  */
9060
9061       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
9062           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
9063           || pdi->tag == DW_TAG_imported_unit
9064           || pdi->tag == DW_TAG_inlined_subroutine)
9065         {
9066           switch (pdi->tag)
9067             {
9068             case DW_TAG_subprogram:
9069             case DW_TAG_inlined_subroutine:
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->per_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->per_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
9285     = cu->per_cu->dwarf2_per_objfile;
9286   struct objfile *objfile = dwarf2_per_objfile->objfile;
9287   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9288   CORE_ADDR addr = 0;
9289   const char *actual_name = NULL;
9290   CORE_ADDR baseaddr;
9291   char *built_actual_name;
9292
9293   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9294
9295   built_actual_name = partial_die_full_name (pdi, cu);
9296   if (built_actual_name != NULL)
9297     actual_name = built_actual_name;
9298
9299   if (actual_name == NULL)
9300     actual_name = pdi->name;
9301
9302   switch (pdi->tag)
9303     {
9304     case DW_TAG_inlined_subroutine:
9305     case DW_TAG_subprogram:
9306       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
9307       if (pdi->is_external || cu->language == language_ada)
9308         {
9309           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
9310              of the global scope.  But in Ada, we want to be able to access
9311              nested procedures globally.  So all Ada subprograms are stored
9312              in the global scope.  */
9313           add_psymbol_to_list (actual_name, strlen (actual_name),
9314                                built_actual_name != NULL,
9315                                VAR_DOMAIN, LOC_BLOCK,
9316                                &objfile->global_psymbols,
9317                                addr, cu->language, objfile);
9318         }
9319       else
9320         {
9321           add_psymbol_to_list (actual_name, strlen (actual_name),
9322                                built_actual_name != NULL,
9323                                VAR_DOMAIN, LOC_BLOCK,
9324                                &objfile->static_psymbols,
9325                                addr, cu->language, objfile);
9326         }
9327
9328       if (pdi->main_subprogram && actual_name != NULL)
9329         set_objfile_main_name (objfile, actual_name, cu->language);
9330       break;
9331     case DW_TAG_constant:
9332       {
9333         std::vector<partial_symbol *> *list;
9334
9335         if (pdi->is_external)
9336           list = &objfile->global_psymbols;
9337         else
9338           list = &objfile->static_psymbols;
9339         add_psymbol_to_list (actual_name, strlen (actual_name),
9340                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
9341                              list, 0, cu->language, objfile);
9342       }
9343       break;
9344     case DW_TAG_variable:
9345       if (pdi->d.locdesc)
9346         addr = decode_locdesc (pdi->d.locdesc, cu);
9347
9348       if (pdi->d.locdesc
9349           && addr == 0
9350           && !dwarf2_per_objfile->has_section_at_zero)
9351         {
9352           /* A global or static variable may also have been stripped
9353              out by the linker if unused, in which case its address
9354              will be nullified; do not add such variables into partial
9355              symbol table then.  */
9356         }
9357       else if (pdi->is_external)
9358         {
9359           /* Global Variable.
9360              Don't enter into the minimal symbol tables as there is
9361              a minimal symbol table entry from the ELF symbols already.
9362              Enter into partial symbol table if it has a location
9363              descriptor or a type.
9364              If the location descriptor is missing, new_symbol will create
9365              a LOC_UNRESOLVED symbol, the address of the variable will then
9366              be determined from the minimal symbol table whenever the variable
9367              is referenced.
9368              The address for the partial symbol table entry is not
9369              used by GDB, but it comes in handy for debugging partial symbol
9370              table building.  */
9371
9372           if (pdi->d.locdesc || pdi->has_type)
9373             add_psymbol_to_list (actual_name, strlen (actual_name),
9374                                  built_actual_name != NULL,
9375                                  VAR_DOMAIN, LOC_STATIC,
9376                                  &objfile->global_psymbols,
9377                                  addr + baseaddr,
9378                                  cu->language, objfile);
9379         }
9380       else
9381         {
9382           int has_loc = pdi->d.locdesc != NULL;
9383
9384           /* Static Variable.  Skip symbols whose value we cannot know (those
9385              without location descriptors or constant values).  */
9386           if (!has_loc && !pdi->has_const_value)
9387             {
9388               xfree (built_actual_name);
9389               return;
9390             }
9391
9392           add_psymbol_to_list (actual_name, strlen (actual_name),
9393                                built_actual_name != NULL,
9394                                VAR_DOMAIN, LOC_STATIC,
9395                                &objfile->static_psymbols,
9396                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
9397                                cu->language, objfile);
9398         }
9399       break;
9400     case DW_TAG_typedef:
9401     case DW_TAG_base_type:
9402     case DW_TAG_subrange_type:
9403       add_psymbol_to_list (actual_name, strlen (actual_name),
9404                            built_actual_name != NULL,
9405                            VAR_DOMAIN, LOC_TYPEDEF,
9406                            &objfile->static_psymbols,
9407                            0, cu->language, objfile);
9408       break;
9409     case DW_TAG_imported_declaration:
9410     case DW_TAG_namespace:
9411       add_psymbol_to_list (actual_name, strlen (actual_name),
9412                            built_actual_name != NULL,
9413                            VAR_DOMAIN, LOC_TYPEDEF,
9414                            &objfile->global_psymbols,
9415                            0, cu->language, objfile);
9416       break;
9417     case DW_TAG_module:
9418       add_psymbol_to_list (actual_name, strlen (actual_name),
9419                            built_actual_name != NULL,
9420                            MODULE_DOMAIN, LOC_TYPEDEF,
9421                            &objfile->global_psymbols,
9422                            0, cu->language, objfile);
9423       break;
9424     case DW_TAG_class_type:
9425     case DW_TAG_interface_type:
9426     case DW_TAG_structure_type:
9427     case DW_TAG_union_type:
9428     case DW_TAG_enumeration_type:
9429       /* Skip external references.  The DWARF standard says in the section
9430          about "Structure, Union, and Class Type Entries": "An incomplete
9431          structure, union or class type is represented by a structure,
9432          union or class entry that does not have a byte size attribute
9433          and that has a DW_AT_declaration attribute."  */
9434       if (!pdi->has_byte_size && pdi->is_declaration)
9435         {
9436           xfree (built_actual_name);
9437           return;
9438         }
9439
9440       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
9441          static vs. global.  */
9442       add_psymbol_to_list (actual_name, strlen (actual_name),
9443                            built_actual_name != NULL,
9444                            STRUCT_DOMAIN, LOC_TYPEDEF,
9445                            cu->language == language_cplus
9446                            ? &objfile->global_psymbols
9447                            : &objfile->static_psymbols,
9448                            0, cu->language, objfile);
9449
9450       break;
9451     case DW_TAG_enumerator:
9452       add_psymbol_to_list (actual_name, strlen (actual_name),
9453                            built_actual_name != NULL,
9454                            VAR_DOMAIN, LOC_CONST,
9455                            cu->language == language_cplus
9456                            ? &objfile->global_psymbols
9457                            : &objfile->static_psymbols,
9458                            0, cu->language, objfile);
9459       break;
9460     default:
9461       break;
9462     }
9463
9464   xfree (built_actual_name);
9465 }
9466
9467 /* Read a partial die corresponding to a namespace; also, add a symbol
9468    corresponding to that namespace to the symbol table.  NAMESPACE is
9469    the name of the enclosing namespace.  */
9470
9471 static void
9472 add_partial_namespace (struct partial_die_info *pdi,
9473                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9474                        int set_addrmap, struct dwarf2_cu *cu)
9475 {
9476   /* Add a symbol for the namespace.  */
9477
9478   add_partial_symbol (pdi, cu);
9479
9480   /* Now scan partial symbols in that namespace.  */
9481
9482   if (pdi->has_children)
9483     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9484 }
9485
9486 /* Read a partial die corresponding to a Fortran module.  */
9487
9488 static void
9489 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9490                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9491 {
9492   /* Add a symbol for the namespace.  */
9493
9494   add_partial_symbol (pdi, cu);
9495
9496   /* Now scan partial symbols in that module.  */
9497
9498   if (pdi->has_children)
9499     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9500 }
9501
9502 /* Read a partial die corresponding to a subprogram or an inlined
9503    subprogram and create a partial symbol for that subprogram.
9504    When the CU language allows it, this routine also defines a partial
9505    symbol for each nested subprogram that this subprogram contains.
9506    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9507    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9508
9509    PDI may also be a lexical block, in which case we simply search
9510    recursively for subprograms defined inside that lexical block.
9511    Again, this is only performed when the CU language allows this
9512    type of definitions.  */
9513
9514 static void
9515 add_partial_subprogram (struct partial_die_info *pdi,
9516                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9517                         int set_addrmap, struct dwarf2_cu *cu)
9518 {
9519   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9520     {
9521       if (pdi->has_pc_info)
9522         {
9523           if (pdi->lowpc < *lowpc)
9524             *lowpc = pdi->lowpc;
9525           if (pdi->highpc > *highpc)
9526             *highpc = pdi->highpc;
9527           if (set_addrmap)
9528             {
9529               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9530               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9531               CORE_ADDR baseaddr;
9532               CORE_ADDR highpc;
9533               CORE_ADDR lowpc;
9534
9535               baseaddr = ANOFFSET (objfile->section_offsets,
9536                                    SECT_OFF_TEXT (objfile));
9537               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9538                                                   pdi->lowpc + baseaddr);
9539               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9540                                                    pdi->highpc + baseaddr);
9541               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9542                                  cu->per_cu->v.psymtab);
9543             }
9544         }
9545
9546       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9547         {
9548           if (!pdi->is_declaration)
9549             /* Ignore subprogram DIEs that do not have a name, they are
9550                illegal.  Do not emit a complaint at this point, we will
9551                do so when we convert this psymtab into a symtab.  */
9552             if (pdi->name)
9553               add_partial_symbol (pdi, cu);
9554         }
9555     }
9556
9557   if (! pdi->has_children)
9558     return;
9559
9560   if (cu->language == language_ada)
9561     {
9562       pdi = pdi->die_child;
9563       while (pdi != NULL)
9564         {
9565           fixup_partial_die (pdi, cu);
9566           if (pdi->tag == DW_TAG_subprogram
9567               || pdi->tag == DW_TAG_inlined_subroutine
9568               || pdi->tag == DW_TAG_lexical_block)
9569             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9570           pdi = pdi->die_sibling;
9571         }
9572     }
9573 }
9574
9575 /* Read a partial die corresponding to an enumeration type.  */
9576
9577 static void
9578 add_partial_enumeration (struct partial_die_info *enum_pdi,
9579                          struct dwarf2_cu *cu)
9580 {
9581   struct partial_die_info *pdi;
9582
9583   if (enum_pdi->name != NULL)
9584     add_partial_symbol (enum_pdi, cu);
9585
9586   pdi = enum_pdi->die_child;
9587   while (pdi)
9588     {
9589       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9590         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
9591       else
9592         add_partial_symbol (pdi, cu);
9593       pdi = pdi->die_sibling;
9594     }
9595 }
9596
9597 /* Return the initial uleb128 in the die at INFO_PTR.  */
9598
9599 static unsigned int
9600 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9601 {
9602   unsigned int bytes_read;
9603
9604   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9605 }
9606
9607 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
9608    Return the corresponding abbrev, or NULL if the number is zero (indicating
9609    an empty DIE).  In either case *BYTES_READ will be set to the length of
9610    the initial number.  */
9611
9612 static struct abbrev_info *
9613 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
9614                  struct dwarf2_cu *cu)
9615 {
9616   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9617   unsigned int abbrev_number;
9618   struct abbrev_info *abbrev;
9619
9620   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9621
9622   if (abbrev_number == 0)
9623     return NULL;
9624
9625   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
9626   if (!abbrev)
9627     {
9628       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9629                " at offset 0x%x [in module %s]"),
9630              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9631              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
9632     }
9633
9634   return abbrev;
9635 }
9636
9637 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9638    Returns a pointer to the end of a series of DIEs, terminated by an empty
9639    DIE.  Any children of the skipped DIEs will also be skipped.  */
9640
9641 static const gdb_byte *
9642 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9643 {
9644   struct dwarf2_cu *cu = reader->cu;
9645   struct abbrev_info *abbrev;
9646   unsigned int bytes_read;
9647
9648   while (1)
9649     {
9650       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
9651       if (abbrev == NULL)
9652         return info_ptr + bytes_read;
9653       else
9654         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9655     }
9656 }
9657
9658 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9659    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9660    abbrev corresponding to that skipped uleb128 should be passed in
9661    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9662    children.  */
9663
9664 static const gdb_byte *
9665 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9666               struct abbrev_info *abbrev)
9667 {
9668   unsigned int bytes_read;
9669   struct attribute attr;
9670   bfd *abfd = reader->abfd;
9671   struct dwarf2_cu *cu = reader->cu;
9672   const gdb_byte *buffer = reader->buffer;
9673   const gdb_byte *buffer_end = reader->buffer_end;
9674   unsigned int form, i;
9675
9676   for (i = 0; i < abbrev->num_attrs; i++)
9677     {
9678       /* The only abbrev we care about is DW_AT_sibling.  */
9679       if (abbrev->attrs[i].name == DW_AT_sibling)
9680         {
9681           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9682           if (attr.form == DW_FORM_ref_addr)
9683             complaint (&symfile_complaints,
9684                        _("ignoring absolute DW_AT_sibling"));
9685           else
9686             {
9687               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9688               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9689
9690               if (sibling_ptr < info_ptr)
9691                 complaint (&symfile_complaints,
9692                            _("DW_AT_sibling points backwards"));
9693               else if (sibling_ptr > reader->buffer_end)
9694                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9695               else
9696                 return sibling_ptr;
9697             }
9698         }
9699
9700       /* If it isn't DW_AT_sibling, skip this attribute.  */
9701       form = abbrev->attrs[i].form;
9702     skip_attribute:
9703       switch (form)
9704         {
9705         case DW_FORM_ref_addr:
9706           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9707              and later it is offset sized.  */
9708           if (cu->header.version == 2)
9709             info_ptr += cu->header.addr_size;
9710           else
9711             info_ptr += cu->header.offset_size;
9712           break;
9713         case DW_FORM_GNU_ref_alt:
9714           info_ptr += cu->header.offset_size;
9715           break;
9716         case DW_FORM_addr:
9717           info_ptr += cu->header.addr_size;
9718           break;
9719         case DW_FORM_data1:
9720         case DW_FORM_ref1:
9721         case DW_FORM_flag:
9722           info_ptr += 1;
9723           break;
9724         case DW_FORM_flag_present:
9725         case DW_FORM_implicit_const:
9726           break;
9727         case DW_FORM_data2:
9728         case DW_FORM_ref2:
9729           info_ptr += 2;
9730           break;
9731         case DW_FORM_data4:
9732         case DW_FORM_ref4:
9733           info_ptr += 4;
9734           break;
9735         case DW_FORM_data8:
9736         case DW_FORM_ref8:
9737         case DW_FORM_ref_sig8:
9738           info_ptr += 8;
9739           break;
9740         case DW_FORM_data16:
9741           info_ptr += 16;
9742           break;
9743         case DW_FORM_string:
9744           read_direct_string (abfd, info_ptr, &bytes_read);
9745           info_ptr += bytes_read;
9746           break;
9747         case DW_FORM_sec_offset:
9748         case DW_FORM_strp:
9749         case DW_FORM_GNU_strp_alt:
9750           info_ptr += cu->header.offset_size;
9751           break;
9752         case DW_FORM_exprloc:
9753         case DW_FORM_block:
9754           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9755           info_ptr += bytes_read;
9756           break;
9757         case DW_FORM_block1:
9758           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9759           break;
9760         case DW_FORM_block2:
9761           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9762           break;
9763         case DW_FORM_block4:
9764           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9765           break;
9766         case DW_FORM_sdata:
9767         case DW_FORM_udata:
9768         case DW_FORM_ref_udata:
9769         case DW_FORM_GNU_addr_index:
9770         case DW_FORM_GNU_str_index:
9771           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9772           break;
9773         case DW_FORM_indirect:
9774           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9775           info_ptr += bytes_read;
9776           /* We need to continue parsing from here, so just go back to
9777              the top.  */
9778           goto skip_attribute;
9779
9780         default:
9781           error (_("Dwarf Error: Cannot handle %s "
9782                    "in DWARF reader [in module %s]"),
9783                  dwarf_form_name (form),
9784                  bfd_get_filename (abfd));
9785         }
9786     }
9787
9788   if (abbrev->has_children)
9789     return skip_children (reader, info_ptr);
9790   else
9791     return info_ptr;
9792 }
9793
9794 /* Locate ORIG_PDI's sibling.
9795    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9796
9797 static const gdb_byte *
9798 locate_pdi_sibling (const struct die_reader_specs *reader,
9799                     struct partial_die_info *orig_pdi,
9800                     const gdb_byte *info_ptr)
9801 {
9802   /* Do we know the sibling already?  */
9803
9804   if (orig_pdi->sibling)
9805     return orig_pdi->sibling;
9806
9807   /* Are there any children to deal with?  */
9808
9809   if (!orig_pdi->has_children)
9810     return info_ptr;
9811
9812   /* Skip the children the long way.  */
9813
9814   return skip_children (reader, info_ptr);
9815 }
9816
9817 /* Expand this partial symbol table into a full symbol table.  SELF is
9818    not NULL.  */
9819
9820 static void
9821 dwarf2_read_symtab (struct partial_symtab *self,
9822                     struct objfile *objfile)
9823 {
9824   struct dwarf2_per_objfile *dwarf2_per_objfile
9825     = get_dwarf2_per_objfile (objfile);
9826
9827   if (self->readin)
9828     {
9829       warning (_("bug: psymtab for %s is already read in."),
9830                self->filename);
9831     }
9832   else
9833     {
9834       if (info_verbose)
9835         {
9836           printf_filtered (_("Reading in symbols for %s..."),
9837                            self->filename);
9838           gdb_flush (gdb_stdout);
9839         }
9840
9841       /* If this psymtab is constructed from a debug-only objfile, the
9842          has_section_at_zero flag will not necessarily be correct.  We
9843          can get the correct value for this flag by looking at the data
9844          associated with the (presumably stripped) associated objfile.  */
9845       if (objfile->separate_debug_objfile_backlink)
9846         {
9847           struct dwarf2_per_objfile *dpo_backlink
9848             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9849
9850           dwarf2_per_objfile->has_section_at_zero
9851             = dpo_backlink->has_section_at_zero;
9852         }
9853
9854       dwarf2_per_objfile->reading_partial_symbols = 0;
9855
9856       psymtab_to_symtab_1 (self);
9857
9858       /* Finish up the debug error message.  */
9859       if (info_verbose)
9860         printf_filtered (_("done.\n"));
9861     }
9862
9863   process_cu_includes (dwarf2_per_objfile);
9864 }
9865 \f
9866 /* Reading in full CUs.  */
9867
9868 /* Add PER_CU to the queue.  */
9869
9870 static void
9871 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9872                  enum language pretend_language)
9873 {
9874   struct dwarf2_queue_item *item;
9875
9876   per_cu->queued = 1;
9877   item = XNEW (struct dwarf2_queue_item);
9878   item->per_cu = per_cu;
9879   item->pretend_language = pretend_language;
9880   item->next = NULL;
9881
9882   if (dwarf2_queue == NULL)
9883     dwarf2_queue = item;
9884   else
9885     dwarf2_queue_tail->next = item;
9886
9887   dwarf2_queue_tail = item;
9888 }
9889
9890 /* If PER_CU is not yet queued, add it to the queue.
9891    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9892    dependency.
9893    The result is non-zero if PER_CU was queued, otherwise the result is zero
9894    meaning either PER_CU is already queued or it is already loaded.
9895
9896    N.B. There is an invariant here that if a CU is queued then it is loaded.
9897    The caller is required to load PER_CU if we return non-zero.  */
9898
9899 static int
9900 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9901                        struct dwarf2_per_cu_data *per_cu,
9902                        enum language pretend_language)
9903 {
9904   /* We may arrive here during partial symbol reading, if we need full
9905      DIEs to process an unusual case (e.g. template arguments).  Do
9906      not queue PER_CU, just tell our caller to load its DIEs.  */
9907   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9908     {
9909       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9910         return 1;
9911       return 0;
9912     }
9913
9914   /* Mark the dependence relation so that we don't flush PER_CU
9915      too early.  */
9916   if (dependent_cu != NULL)
9917     dwarf2_add_dependence (dependent_cu, per_cu);
9918
9919   /* If it's already on the queue, we have nothing to do.  */
9920   if (per_cu->queued)
9921     return 0;
9922
9923   /* If the compilation unit is already loaded, just mark it as
9924      used.  */
9925   if (per_cu->cu != NULL)
9926     {
9927       per_cu->cu->last_used = 0;
9928       return 0;
9929     }
9930
9931   /* Add it to the queue.  */
9932   queue_comp_unit (per_cu, pretend_language);
9933
9934   return 1;
9935 }
9936
9937 /* Process the queue.  */
9938
9939 static void
9940 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9941 {
9942   struct dwarf2_queue_item *item, *next_item;
9943
9944   if (dwarf_read_debug)
9945     {
9946       fprintf_unfiltered (gdb_stdlog,
9947                           "Expanding one or more symtabs of objfile %s ...\n",
9948                           objfile_name (dwarf2_per_objfile->objfile));
9949     }
9950
9951   /* The queue starts out with one item, but following a DIE reference
9952      may load a new CU, adding it to the end of the queue.  */
9953   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9954     {
9955       if ((dwarf2_per_objfile->using_index
9956            ? !item->per_cu->v.quick->compunit_symtab
9957            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9958           /* Skip dummy CUs.  */
9959           && item->per_cu->cu != NULL)
9960         {
9961           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9962           unsigned int debug_print_threshold;
9963           char buf[100];
9964
9965           if (per_cu->is_debug_types)
9966             {
9967               struct signatured_type *sig_type =
9968                 (struct signatured_type *) per_cu;
9969
9970               sprintf (buf, "TU %s at offset 0x%x",
9971                        hex_string (sig_type->signature),
9972                        to_underlying (per_cu->sect_off));
9973               /* There can be 100s of TUs.
9974                  Only print them in verbose mode.  */
9975               debug_print_threshold = 2;
9976             }
9977           else
9978             {
9979               sprintf (buf, "CU at offset 0x%x",
9980                        to_underlying (per_cu->sect_off));
9981               debug_print_threshold = 1;
9982             }
9983
9984           if (dwarf_read_debug >= debug_print_threshold)
9985             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9986
9987           if (per_cu->is_debug_types)
9988             process_full_type_unit (per_cu, item->pretend_language);
9989           else
9990             process_full_comp_unit (per_cu, item->pretend_language);
9991
9992           if (dwarf_read_debug >= debug_print_threshold)
9993             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9994         }
9995
9996       item->per_cu->queued = 0;
9997       next_item = item->next;
9998       xfree (item);
9999     }
10000
10001   dwarf2_queue_tail = NULL;
10002
10003   if (dwarf_read_debug)
10004     {
10005       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
10006                           objfile_name (dwarf2_per_objfile->objfile));
10007     }
10008 }
10009
10010 /* Free all allocated queue entries.  This function only releases anything if
10011    an error was thrown; if the queue was processed then it would have been
10012    freed as we went along.  */
10013
10014 static void
10015 dwarf2_release_queue (void *dummy)
10016 {
10017   struct dwarf2_queue_item *item, *last;
10018
10019   item = dwarf2_queue;
10020   while (item)
10021     {
10022       /* Anything still marked queued is likely to be in an
10023          inconsistent state, so discard it.  */
10024       if (item->per_cu->queued)
10025         {
10026           if (item->per_cu->cu != NULL)
10027             free_one_cached_comp_unit (item->per_cu);
10028           item->per_cu->queued = 0;
10029         }
10030
10031       last = item;
10032       item = item->next;
10033       xfree (last);
10034     }
10035
10036   dwarf2_queue = dwarf2_queue_tail = NULL;
10037 }
10038
10039 /* Read in full symbols for PST, and anything it depends on.  */
10040
10041 static void
10042 psymtab_to_symtab_1 (struct partial_symtab *pst)
10043 {
10044   struct dwarf2_per_cu_data *per_cu;
10045   int i;
10046
10047   if (pst->readin)
10048     return;
10049
10050   for (i = 0; i < pst->number_of_dependencies; i++)
10051     if (!pst->dependencies[i]->readin
10052         && pst->dependencies[i]->user == NULL)
10053       {
10054         /* Inform about additional files that need to be read in.  */
10055         if (info_verbose)
10056           {
10057             /* FIXME: i18n: Need to make this a single string.  */
10058             fputs_filtered (" ", gdb_stdout);
10059             wrap_here ("");
10060             fputs_filtered ("and ", gdb_stdout);
10061             wrap_here ("");
10062             printf_filtered ("%s...", pst->dependencies[i]->filename);
10063             wrap_here ("");     /* Flush output.  */
10064             gdb_flush (gdb_stdout);
10065           }
10066         psymtab_to_symtab_1 (pst->dependencies[i]);
10067       }
10068
10069   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
10070
10071   if (per_cu == NULL)
10072     {
10073       /* It's an include file, no symbols to read for it.
10074          Everything is in the parent symtab.  */
10075       pst->readin = 1;
10076       return;
10077     }
10078
10079   dw2_do_instantiate_symtab (per_cu);
10080 }
10081
10082 /* Trivial hash function for die_info: the hash value of a DIE
10083    is its offset in .debug_info for this objfile.  */
10084
10085 static hashval_t
10086 die_hash (const void *item)
10087 {
10088   const struct die_info *die = (const struct die_info *) item;
10089
10090   return to_underlying (die->sect_off);
10091 }
10092
10093 /* Trivial comparison function for die_info structures: two DIEs
10094    are equal if they have the same offset.  */
10095
10096 static int
10097 die_eq (const void *item_lhs, const void *item_rhs)
10098 {
10099   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
10100   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
10101
10102   return die_lhs->sect_off == die_rhs->sect_off;
10103 }
10104
10105 /* die_reader_func for load_full_comp_unit.
10106    This is identical to read_signatured_type_reader,
10107    but is kept separate for now.  */
10108
10109 static void
10110 load_full_comp_unit_reader (const struct die_reader_specs *reader,
10111                             const gdb_byte *info_ptr,
10112                             struct die_info *comp_unit_die,
10113                             int has_children,
10114                             void *data)
10115 {
10116   struct dwarf2_cu *cu = reader->cu;
10117   enum language *language_ptr = (enum language *) data;
10118
10119   gdb_assert (cu->die_hash == NULL);
10120   cu->die_hash =
10121     htab_create_alloc_ex (cu->header.length / 12,
10122                           die_hash,
10123                           die_eq,
10124                           NULL,
10125                           &cu->comp_unit_obstack,
10126                           hashtab_obstack_allocate,
10127                           dummy_obstack_deallocate);
10128
10129   if (has_children)
10130     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
10131                                                   &info_ptr, comp_unit_die);
10132   cu->dies = comp_unit_die;
10133   /* comp_unit_die is not stored in die_hash, no need.  */
10134
10135   /* We try not to read any attributes in this function, because not
10136      all CUs needed for references have been loaded yet, and symbol
10137      table processing isn't initialized.  But we have to set the CU language,
10138      or we won't be able to build types correctly.
10139      Similarly, if we do not read the producer, we can not apply
10140      producer-specific interpretation.  */
10141   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
10142 }
10143
10144 /* Load the DIEs associated with PER_CU into memory.  */
10145
10146 static void
10147 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
10148                      enum language pretend_language)
10149 {
10150   gdb_assert (! this_cu->is_debug_types);
10151
10152   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
10153                            load_full_comp_unit_reader, &pretend_language);
10154 }
10155
10156 /* Add a DIE to the delayed physname list.  */
10157
10158 static void
10159 add_to_method_list (struct type *type, int fnfield_index, int index,
10160                     const char *name, struct die_info *die,
10161                     struct dwarf2_cu *cu)
10162 {
10163   struct delayed_method_info mi;
10164   mi.type = type;
10165   mi.fnfield_index = fnfield_index;
10166   mi.index = index;
10167   mi.name = name;
10168   mi.die = die;
10169   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
10170 }
10171
10172 /* A cleanup for freeing the delayed method list.  */
10173
10174 static void
10175 free_delayed_list (void *ptr)
10176 {
10177   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
10178   if (cu->method_list != NULL)
10179     {
10180       VEC_free (delayed_method_info, cu->method_list);
10181       cu->method_list = NULL;
10182     }
10183 }
10184
10185 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
10186    "const" / "volatile".  If so, decrements LEN by the length of the
10187    modifier and return true.  Otherwise return false.  */
10188
10189 template<size_t N>
10190 static bool
10191 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
10192 {
10193   size_t mod_len = sizeof (mod) - 1;
10194   if (len > mod_len && startswith (physname + (len - mod_len), mod))
10195     {
10196       len -= mod_len;
10197       return true;
10198     }
10199   return false;
10200 }
10201
10202 /* Compute the physnames of any methods on the CU's method list.
10203
10204    The computation of method physnames is delayed in order to avoid the
10205    (bad) condition that one of the method's formal parameters is of an as yet
10206    incomplete type.  */
10207
10208 static void
10209 compute_delayed_physnames (struct dwarf2_cu *cu)
10210 {
10211   int i;
10212   struct delayed_method_info *mi;
10213
10214   /* Only C++ delays computing physnames.  */
10215   if (VEC_empty (delayed_method_info, cu->method_list))
10216     return;
10217   gdb_assert (cu->language == language_cplus);
10218
10219   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
10220     {
10221       const char *physname;
10222       struct fn_fieldlist *fn_flp
10223         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
10224       physname = dwarf2_physname (mi->name, mi->die, cu);
10225       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
10226         = physname ? physname : "";
10227
10228       /* Since there's no tag to indicate whether a method is a
10229          const/volatile overload, extract that information out of the
10230          demangled name.  */
10231       if (physname != NULL)
10232         {
10233           size_t len = strlen (physname);
10234
10235           while (1)
10236             {
10237               if (physname[len] == ')') /* shortcut */
10238                 break;
10239               else if (check_modifier (physname, len, " const"))
10240                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
10241               else if (check_modifier (physname, len, " volatile"))
10242                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
10243               else
10244                 break;
10245             }
10246         }
10247     }
10248 }
10249
10250 /* Go objects should be embedded in a DW_TAG_module DIE,
10251    and it's not clear if/how imported objects will appear.
10252    To keep Go support simple until that's worked out,
10253    go back through what we've read and create something usable.
10254    We could do this while processing each DIE, and feels kinda cleaner,
10255    but that way is more invasive.
10256    This is to, for example, allow the user to type "p var" or "b main"
10257    without having to specify the package name, and allow lookups
10258    of module.object to work in contexts that use the expression
10259    parser.  */
10260
10261 static void
10262 fixup_go_packaging (struct dwarf2_cu *cu)
10263 {
10264   char *package_name = NULL;
10265   struct pending *list;
10266   int i;
10267
10268   for (list = global_symbols; list != NULL; list = list->next)
10269     {
10270       for (i = 0; i < list->nsyms; ++i)
10271         {
10272           struct symbol *sym = list->symbol[i];
10273
10274           if (SYMBOL_LANGUAGE (sym) == language_go
10275               && SYMBOL_CLASS (sym) == LOC_BLOCK)
10276             {
10277               char *this_package_name = go_symbol_package_name (sym);
10278
10279               if (this_package_name == NULL)
10280                 continue;
10281               if (package_name == NULL)
10282                 package_name = this_package_name;
10283               else
10284                 {
10285                   struct objfile *objfile
10286                     = cu->per_cu->dwarf2_per_objfile->objfile;
10287                   if (strcmp (package_name, this_package_name) != 0)
10288                     complaint (&symfile_complaints,
10289                                _("Symtab %s has objects from two different Go packages: %s and %s"),
10290                                (symbol_symtab (sym) != NULL
10291                                 ? symtab_to_filename_for_display
10292                                     (symbol_symtab (sym))
10293                                 : objfile_name (objfile)),
10294                                this_package_name, package_name);
10295                   xfree (this_package_name);
10296                 }
10297             }
10298         }
10299     }
10300
10301   if (package_name != NULL)
10302     {
10303       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10304       const char *saved_package_name
10305         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
10306                                         package_name,
10307                                         strlen (package_name));
10308       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
10309                                      saved_package_name);
10310       struct symbol *sym;
10311
10312       TYPE_TAG_NAME (type) = TYPE_NAME (type);
10313
10314       sym = allocate_symbol (objfile);
10315       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
10316       SYMBOL_SET_NAMES (sym, saved_package_name,
10317                         strlen (saved_package_name), 0, objfile);
10318       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
10319          e.g., "main" finds the "main" module and not C's main().  */
10320       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
10321       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
10322       SYMBOL_TYPE (sym) = type;
10323
10324       add_symbol_to_list (sym, &global_symbols);
10325
10326       xfree (package_name);
10327     }
10328 }
10329
10330 /* Return the symtab for PER_CU.  This works properly regardless of
10331    whether we're using the index or psymtabs.  */
10332
10333 static struct compunit_symtab *
10334 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10335 {
10336   return (per_cu->dwarf2_per_objfile->using_index
10337           ? per_cu->v.quick->compunit_symtab
10338           : per_cu->v.psymtab->compunit_symtab);
10339 }
10340
10341 /* A helper function for computing the list of all symbol tables
10342    included by PER_CU.  */
10343
10344 static void
10345 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10346                                 htab_t all_children, htab_t all_type_symtabs,
10347                                 struct dwarf2_per_cu_data *per_cu,
10348                                 struct compunit_symtab *immediate_parent)
10349 {
10350   void **slot;
10351   int ix;
10352   struct compunit_symtab *cust;
10353   struct dwarf2_per_cu_data *iter;
10354
10355   slot = htab_find_slot (all_children, per_cu, INSERT);
10356   if (*slot != NULL)
10357     {
10358       /* This inclusion and its children have been processed.  */
10359       return;
10360     }
10361
10362   *slot = per_cu;
10363   /* Only add a CU if it has a symbol table.  */
10364   cust = get_compunit_symtab (per_cu);
10365   if (cust != NULL)
10366     {
10367       /* If this is a type unit only add its symbol table if we haven't
10368          seen it yet (type unit per_cu's can share symtabs).  */
10369       if (per_cu->is_debug_types)
10370         {
10371           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10372           if (*slot == NULL)
10373             {
10374               *slot = cust;
10375               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10376               if (cust->user == NULL)
10377                 cust->user = immediate_parent;
10378             }
10379         }
10380       else
10381         {
10382           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10383           if (cust->user == NULL)
10384             cust->user = immediate_parent;
10385         }
10386     }
10387
10388   for (ix = 0;
10389        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10390        ++ix)
10391     {
10392       recursively_compute_inclusions (result, all_children,
10393                                       all_type_symtabs, iter, cust);
10394     }
10395 }
10396
10397 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10398    PER_CU.  */
10399
10400 static void
10401 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10402 {
10403   gdb_assert (! per_cu->is_debug_types);
10404
10405   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10406     {
10407       int ix, len;
10408       struct dwarf2_per_cu_data *per_cu_iter;
10409       struct compunit_symtab *compunit_symtab_iter;
10410       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10411       htab_t all_children, all_type_symtabs;
10412       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10413
10414       /* If we don't have a symtab, we can just skip this case.  */
10415       if (cust == NULL)
10416         return;
10417
10418       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10419                                         NULL, xcalloc, xfree);
10420       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10421                                             NULL, xcalloc, xfree);
10422
10423       for (ix = 0;
10424            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10425                         ix, per_cu_iter);
10426            ++ix)
10427         {
10428           recursively_compute_inclusions (&result_symtabs, all_children,
10429                                           all_type_symtabs, per_cu_iter,
10430                                           cust);
10431         }
10432
10433       /* Now we have a transitive closure of all the included symtabs.  */
10434       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10435       cust->includes
10436         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10437                      struct compunit_symtab *, len + 1);
10438       for (ix = 0;
10439            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10440                         compunit_symtab_iter);
10441            ++ix)
10442         cust->includes[ix] = compunit_symtab_iter;
10443       cust->includes[len] = NULL;
10444
10445       VEC_free (compunit_symtab_ptr, result_symtabs);
10446       htab_delete (all_children);
10447       htab_delete (all_type_symtabs);
10448     }
10449 }
10450
10451 /* Compute the 'includes' field for the symtabs of all the CUs we just
10452    read.  */
10453
10454 static void
10455 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10456 {
10457   int ix;
10458   struct dwarf2_per_cu_data *iter;
10459
10460   for (ix = 0;
10461        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
10462                     ix, iter);
10463        ++ix)
10464     {
10465       if (! iter->is_debug_types)
10466         compute_compunit_symtab_includes (iter);
10467     }
10468
10469   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
10470 }
10471
10472 /* Generate full symbol information for PER_CU, whose DIEs have
10473    already been loaded into memory.  */
10474
10475 static void
10476 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10477                         enum language pretend_language)
10478 {
10479   struct dwarf2_cu *cu = per_cu->cu;
10480   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10481   struct objfile *objfile = dwarf2_per_objfile->objfile;
10482   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10483   CORE_ADDR lowpc, highpc;
10484   struct compunit_symtab *cust;
10485   struct cleanup *delayed_list_cleanup;
10486   CORE_ADDR baseaddr;
10487   struct block *static_block;
10488   CORE_ADDR addr;
10489
10490   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10491
10492   buildsym_init ();
10493   scoped_free_pendings free_pending;
10494   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10495
10496   cu->list_in_scope = &file_symbols;
10497
10498   cu->language = pretend_language;
10499   cu->language_defn = language_def (cu->language);
10500
10501   /* Do line number decoding in read_file_scope () */
10502   process_die (cu->dies, cu);
10503
10504   /* For now fudge the Go package.  */
10505   if (cu->language == language_go)
10506     fixup_go_packaging (cu);
10507
10508   /* Now that we have processed all the DIEs in the CU, all the types 
10509      should be complete, and it should now be safe to compute all of the
10510      physnames.  */
10511   compute_delayed_physnames (cu);
10512   do_cleanups (delayed_list_cleanup);
10513
10514   /* Some compilers don't define a DW_AT_high_pc attribute for the
10515      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10516      it, by scanning the DIE's below the compilation unit.  */
10517   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10518
10519   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10520   static_block = end_symtab_get_static_block (addr, 0, 1);
10521
10522   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10523      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10524      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10525      addrmap to help ensure it has an accurate map of pc values belonging to
10526      this comp unit.  */
10527   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10528
10529   cust = end_symtab_from_static_block (static_block,
10530                                        SECT_OFF_TEXT (objfile), 0);
10531
10532   if (cust != NULL)
10533     {
10534       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10535
10536       /* Set symtab language to language from DW_AT_language.  If the
10537          compilation is from a C file generated by language preprocessors, do
10538          not set the language if it was already deduced by start_subfile.  */
10539       if (!(cu->language == language_c
10540             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10541         COMPUNIT_FILETABS (cust)->language = cu->language;
10542
10543       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10544          produce DW_AT_location with location lists but it can be possibly
10545          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10546          there were bugs in prologue debug info, fixed later in GCC-4.5
10547          by "unwind info for epilogues" patch (which is not directly related).
10548
10549          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10550          needed, it would be wrong due to missing DW_AT_producer there.
10551
10552          Still one can confuse GDB by using non-standard GCC compilation
10553          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10554          */ 
10555       if (cu->has_loclist && gcc_4_minor >= 5)
10556         cust->locations_valid = 1;
10557
10558       if (gcc_4_minor >= 5)
10559         cust->epilogue_unwind_valid = 1;
10560
10561       cust->call_site_htab = cu->call_site_htab;
10562     }
10563
10564   if (dwarf2_per_objfile->using_index)
10565     per_cu->v.quick->compunit_symtab = cust;
10566   else
10567     {
10568       struct partial_symtab *pst = per_cu->v.psymtab;
10569       pst->compunit_symtab = cust;
10570       pst->readin = 1;
10571     }
10572
10573   /* Push it for inclusion processing later.  */
10574   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
10575 }
10576
10577 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10578    already been loaded into memory.  */
10579
10580 static void
10581 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10582                         enum language pretend_language)
10583 {
10584   struct dwarf2_cu *cu = per_cu->cu;
10585   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10586   struct objfile *objfile = dwarf2_per_objfile->objfile;
10587   struct compunit_symtab *cust;
10588   struct cleanup *delayed_list_cleanup;
10589   struct signatured_type *sig_type;
10590
10591   gdb_assert (per_cu->is_debug_types);
10592   sig_type = (struct signatured_type *) per_cu;
10593
10594   buildsym_init ();
10595   scoped_free_pendings free_pending;
10596   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
10597
10598   cu->list_in_scope = &file_symbols;
10599
10600   cu->language = pretend_language;
10601   cu->language_defn = language_def (cu->language);
10602
10603   /* The symbol tables are set up in read_type_unit_scope.  */
10604   process_die (cu->dies, cu);
10605
10606   /* For now fudge the Go package.  */
10607   if (cu->language == language_go)
10608     fixup_go_packaging (cu);
10609
10610   /* Now that we have processed all the DIEs in the CU, all the types 
10611      should be complete, and it should now be safe to compute all of the
10612      physnames.  */
10613   compute_delayed_physnames (cu);
10614   do_cleanups (delayed_list_cleanup);
10615
10616   /* TUs share symbol tables.
10617      If this is the first TU to use this symtab, complete the construction
10618      of it with end_expandable_symtab.  Otherwise, complete the addition of
10619      this TU's symbols to the existing symtab.  */
10620   if (sig_type->type_unit_group->compunit_symtab == NULL)
10621     {
10622       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10623       sig_type->type_unit_group->compunit_symtab = cust;
10624
10625       if (cust != NULL)
10626         {
10627           /* Set symtab language to language from DW_AT_language.  If the
10628              compilation is from a C file generated by language preprocessors,
10629              do not set the language if it was already deduced by
10630              start_subfile.  */
10631           if (!(cu->language == language_c
10632                 && COMPUNIT_FILETABS (cust)->language != language_c))
10633             COMPUNIT_FILETABS (cust)->language = cu->language;
10634         }
10635     }
10636   else
10637     {
10638       augment_type_symtab ();
10639       cust = sig_type->type_unit_group->compunit_symtab;
10640     }
10641
10642   if (dwarf2_per_objfile->using_index)
10643     per_cu->v.quick->compunit_symtab = cust;
10644   else
10645     {
10646       struct partial_symtab *pst = per_cu->v.psymtab;
10647       pst->compunit_symtab = cust;
10648       pst->readin = 1;
10649     }
10650 }
10651
10652 /* Process an imported unit DIE.  */
10653
10654 static void
10655 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10656 {
10657   struct attribute *attr;
10658
10659   /* For now we don't handle imported units in type units.  */
10660   if (cu->per_cu->is_debug_types)
10661     {
10662       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10663                " supported in type units [in module %s]"),
10664              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10665     }
10666
10667   attr = dwarf2_attr (die, DW_AT_import, cu);
10668   if (attr != NULL)
10669     {
10670       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10671       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10672       dwarf2_per_cu_data *per_cu
10673         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10674                                             cu->per_cu->dwarf2_per_objfile);
10675
10676       /* If necessary, add it to the queue and load its DIEs.  */
10677       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10678         load_full_comp_unit (per_cu, cu->language);
10679
10680       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10681                      per_cu);
10682     }
10683 }
10684
10685 /* RAII object that represents a process_die scope: i.e.,
10686    starts/finishes processing a DIE.  */
10687 class process_die_scope
10688 {
10689 public:
10690   process_die_scope (die_info *die, dwarf2_cu *cu)
10691     : m_die (die), m_cu (cu)
10692   {
10693     /* We should only be processing DIEs not already in process.  */
10694     gdb_assert (!m_die->in_process);
10695     m_die->in_process = true;
10696   }
10697
10698   ~process_die_scope ()
10699   {
10700     m_die->in_process = false;
10701
10702     /* If we're done processing the DIE for the CU that owns the line
10703        header, we don't need the line header anymore.  */
10704     if (m_cu->line_header_die_owner == m_die)
10705       {
10706         delete m_cu->line_header;
10707         m_cu->line_header = NULL;
10708         m_cu->line_header_die_owner = NULL;
10709       }
10710   }
10711
10712 private:
10713   die_info *m_die;
10714   dwarf2_cu *m_cu;
10715 };
10716
10717 /* Process a die and its children.  */
10718
10719 static void
10720 process_die (struct die_info *die, struct dwarf2_cu *cu)
10721 {
10722   process_die_scope scope (die, cu);
10723
10724   switch (die->tag)
10725     {
10726     case DW_TAG_padding:
10727       break;
10728     case DW_TAG_compile_unit:
10729     case DW_TAG_partial_unit:
10730       read_file_scope (die, cu);
10731       break;
10732     case DW_TAG_type_unit:
10733       read_type_unit_scope (die, cu);
10734       break;
10735     case DW_TAG_subprogram:
10736     case DW_TAG_inlined_subroutine:
10737       read_func_scope (die, cu);
10738       break;
10739     case DW_TAG_lexical_block:
10740     case DW_TAG_try_block:
10741     case DW_TAG_catch_block:
10742       read_lexical_block_scope (die, cu);
10743       break;
10744     case DW_TAG_call_site:
10745     case DW_TAG_GNU_call_site:
10746       read_call_site_scope (die, cu);
10747       break;
10748     case DW_TAG_class_type:
10749     case DW_TAG_interface_type:
10750     case DW_TAG_structure_type:
10751     case DW_TAG_union_type:
10752       process_structure_scope (die, cu);
10753       break;
10754     case DW_TAG_enumeration_type:
10755       process_enumeration_scope (die, cu);
10756       break;
10757
10758     /* These dies have a type, but processing them does not create
10759        a symbol or recurse to process the children.  Therefore we can
10760        read them on-demand through read_type_die.  */
10761     case DW_TAG_subroutine_type:
10762     case DW_TAG_set_type:
10763     case DW_TAG_array_type:
10764     case DW_TAG_pointer_type:
10765     case DW_TAG_ptr_to_member_type:
10766     case DW_TAG_reference_type:
10767     case DW_TAG_rvalue_reference_type:
10768     case DW_TAG_string_type:
10769       break;
10770
10771     case DW_TAG_base_type:
10772     case DW_TAG_subrange_type:
10773     case DW_TAG_typedef:
10774       /* Add a typedef symbol for the type definition, if it has a
10775          DW_AT_name.  */
10776       new_symbol (die, read_type_die (die, cu), cu);
10777       break;
10778     case DW_TAG_common_block:
10779       read_common_block (die, cu);
10780       break;
10781     case DW_TAG_common_inclusion:
10782       break;
10783     case DW_TAG_namespace:
10784       cu->processing_has_namespace_info = 1;
10785       read_namespace (die, cu);
10786       break;
10787     case DW_TAG_module:
10788       cu->processing_has_namespace_info = 1;
10789       read_module (die, cu);
10790       break;
10791     case DW_TAG_imported_declaration:
10792       cu->processing_has_namespace_info = 1;
10793       if (read_namespace_alias (die, cu))
10794         break;
10795       /* The declaration is not a global namespace alias: fall through.  */
10796     case DW_TAG_imported_module:
10797       cu->processing_has_namespace_info = 1;
10798       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10799                                  || cu->language != language_fortran))
10800         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
10801                    dwarf_tag_name (die->tag));
10802       read_import_statement (die, cu);
10803       break;
10804
10805     case DW_TAG_imported_unit:
10806       process_imported_unit_die (die, cu);
10807       break;
10808
10809     case DW_TAG_variable:
10810       read_variable (die, cu);
10811       break;
10812
10813     default:
10814       new_symbol (die, NULL, cu);
10815       break;
10816     }
10817 }
10818 \f
10819 /* DWARF name computation.  */
10820
10821 /* A helper function for dwarf2_compute_name which determines whether DIE
10822    needs to have the name of the scope prepended to the name listed in the
10823    die.  */
10824
10825 static int
10826 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10827 {
10828   struct attribute *attr;
10829
10830   switch (die->tag)
10831     {
10832     case DW_TAG_namespace:
10833     case DW_TAG_typedef:
10834     case DW_TAG_class_type:
10835     case DW_TAG_interface_type:
10836     case DW_TAG_structure_type:
10837     case DW_TAG_union_type:
10838     case DW_TAG_enumeration_type:
10839     case DW_TAG_enumerator:
10840     case DW_TAG_subprogram:
10841     case DW_TAG_inlined_subroutine:
10842     case DW_TAG_member:
10843     case DW_TAG_imported_declaration:
10844       return 1;
10845
10846     case DW_TAG_variable:
10847     case DW_TAG_constant:
10848       /* We only need to prefix "globally" visible variables.  These include
10849          any variable marked with DW_AT_external or any variable that
10850          lives in a namespace.  [Variables in anonymous namespaces
10851          require prefixing, but they are not DW_AT_external.]  */
10852
10853       if (dwarf2_attr (die, DW_AT_specification, cu))
10854         {
10855           struct dwarf2_cu *spec_cu = cu;
10856
10857           return die_needs_namespace (die_specification (die, &spec_cu),
10858                                       spec_cu);
10859         }
10860
10861       attr = dwarf2_attr (die, DW_AT_external, cu);
10862       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10863           && die->parent->tag != DW_TAG_module)
10864         return 0;
10865       /* A variable in a lexical block of some kind does not need a
10866          namespace, even though in C++ such variables may be external
10867          and have a mangled name.  */
10868       if (die->parent->tag ==  DW_TAG_lexical_block
10869           || die->parent->tag ==  DW_TAG_try_block
10870           || die->parent->tag ==  DW_TAG_catch_block
10871           || die->parent->tag == DW_TAG_subprogram)
10872         return 0;
10873       return 1;
10874
10875     default:
10876       return 0;
10877     }
10878 }
10879
10880 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10881    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10882    defined for the given DIE.  */
10883
10884 static struct attribute *
10885 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10886 {
10887   struct attribute *attr;
10888
10889   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10890   if (attr == NULL)
10891     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10892
10893   return attr;
10894 }
10895
10896 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10897    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10898    defined for the given DIE.  */
10899
10900 static const char *
10901 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10902 {
10903   const char *linkage_name;
10904
10905   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10906   if (linkage_name == NULL)
10907     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10908
10909   return linkage_name;
10910 }
10911
10912 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10913    compute the physname for the object, which include a method's:
10914    - formal parameters (C++),
10915    - receiver type (Go),
10916
10917    The term "physname" is a bit confusing.
10918    For C++, for example, it is the demangled name.
10919    For Go, for example, it's the mangled name.
10920
10921    For Ada, return the DIE's linkage name rather than the fully qualified
10922    name.  PHYSNAME is ignored..
10923
10924    The result is allocated on the objfile_obstack and canonicalized.  */
10925
10926 static const char *
10927 dwarf2_compute_name (const char *name,
10928                      struct die_info *die, struct dwarf2_cu *cu,
10929                      int physname)
10930 {
10931   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10932
10933   if (name == NULL)
10934     name = dwarf2_name (die, cu);
10935
10936   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10937      but otherwise compute it by typename_concat inside GDB.
10938      FIXME: Actually this is not really true, or at least not always true.
10939      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10940      Fortran names because there is no mangling standard.  So new_symbol
10941      will set the demangled name to the result of dwarf2_full_name, and it is
10942      the demangled name that GDB uses if it exists.  */
10943   if (cu->language == language_ada
10944       || (cu->language == language_fortran && physname))
10945     {
10946       /* For Ada unit, we prefer the linkage name over the name, as
10947          the former contains the exported name, which the user expects
10948          to be able to reference.  Ideally, we want the user to be able
10949          to reference this entity using either natural or linkage name,
10950          but we haven't started looking at this enhancement yet.  */
10951       const char *linkage_name = dw2_linkage_name (die, cu);
10952
10953       if (linkage_name != NULL)
10954         return linkage_name;
10955     }
10956
10957   /* These are the only languages we know how to qualify names in.  */
10958   if (name != NULL
10959       && (cu->language == language_cplus
10960           || cu->language == language_fortran || cu->language == language_d
10961           || cu->language == language_rust))
10962     {
10963       if (die_needs_namespace (die, cu))
10964         {
10965           const char *prefix;
10966           const char *canonical_name = NULL;
10967
10968           string_file buf;
10969
10970           prefix = determine_prefix (die, cu);
10971           if (*prefix != '\0')
10972             {
10973               char *prefixed_name = typename_concat (NULL, prefix, name,
10974                                                      physname, cu);
10975
10976               buf.puts (prefixed_name);
10977               xfree (prefixed_name);
10978             }
10979           else
10980             buf.puts (name);
10981
10982           /* Template parameters may be specified in the DIE's DW_AT_name, or
10983              as children with DW_TAG_template_type_param or
10984              DW_TAG_value_type_param.  If the latter, add them to the name
10985              here.  If the name already has template parameters, then
10986              skip this step; some versions of GCC emit both, and
10987              it is more efficient to use the pre-computed name.
10988
10989              Something to keep in mind about this process: it is very
10990              unlikely, or in some cases downright impossible, to produce
10991              something that will match the mangled name of a function.
10992              If the definition of the function has the same debug info,
10993              we should be able to match up with it anyway.  But fallbacks
10994              using the minimal symbol, for instance to find a method
10995              implemented in a stripped copy of libstdc++, will not work.
10996              If we do not have debug info for the definition, we will have to
10997              match them up some other way.
10998
10999              When we do name matching there is a related problem with function
11000              templates; two instantiated function templates are allowed to
11001              differ only by their return types, which we do not add here.  */
11002
11003           if (cu->language == language_cplus && strchr (name, '<') == NULL)
11004             {
11005               struct attribute *attr;
11006               struct die_info *child;
11007               int first = 1;
11008
11009               die->building_fullname = 1;
11010
11011               for (child = die->child; child != NULL; child = child->sibling)
11012                 {
11013                   struct type *type;
11014                   LONGEST value;
11015                   const gdb_byte *bytes;
11016                   struct dwarf2_locexpr_baton *baton;
11017                   struct value *v;
11018
11019                   if (child->tag != DW_TAG_template_type_param
11020                       && child->tag != DW_TAG_template_value_param)
11021                     continue;
11022
11023                   if (first)
11024                     {
11025                       buf.puts ("<");
11026                       first = 0;
11027                     }
11028                   else
11029                     buf.puts (", ");
11030
11031                   attr = dwarf2_attr (child, DW_AT_type, cu);
11032                   if (attr == NULL)
11033                     {
11034                       complaint (&symfile_complaints,
11035                                  _("template parameter missing DW_AT_type"));
11036                       buf.puts ("UNKNOWN_TYPE");
11037                       continue;
11038                     }
11039                   type = die_type (child, cu);
11040
11041                   if (child->tag == DW_TAG_template_type_param)
11042                     {
11043                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
11044                       continue;
11045                     }
11046
11047                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
11048                   if (attr == NULL)
11049                     {
11050                       complaint (&symfile_complaints,
11051                                  _("template parameter missing "
11052                                    "DW_AT_const_value"));
11053                       buf.puts ("UNKNOWN_VALUE");
11054                       continue;
11055                     }
11056
11057                   dwarf2_const_value_attr (attr, type, name,
11058                                            &cu->comp_unit_obstack, cu,
11059                                            &value, &bytes, &baton);
11060
11061                   if (TYPE_NOSIGN (type))
11062                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
11063                        changed, this can use value_print instead.  */
11064                     c_printchar (value, type, &buf);
11065                   else
11066                     {
11067                       struct value_print_options opts;
11068
11069                       if (baton != NULL)
11070                         v = dwarf2_evaluate_loc_desc (type, NULL,
11071                                                       baton->data,
11072                                                       baton->size,
11073                                                       baton->per_cu);
11074                       else if (bytes != NULL)
11075                         {
11076                           v = allocate_value (type);
11077                           memcpy (value_contents_writeable (v), bytes,
11078                                   TYPE_LENGTH (type));
11079                         }
11080                       else
11081                         v = value_from_longest (type, value);
11082
11083                       /* Specify decimal so that we do not depend on
11084                          the radix.  */
11085                       get_formatted_print_options (&opts, 'd');
11086                       opts.raw = 1;
11087                       value_print (v, &buf, &opts);
11088                       release_value (v);
11089                       value_free (v);
11090                     }
11091                 }
11092
11093               die->building_fullname = 0;
11094
11095               if (!first)
11096                 {
11097                   /* Close the argument list, with a space if necessary
11098                      (nested templates).  */
11099                   if (!buf.empty () && buf.string ().back () == '>')
11100                     buf.puts (" >");
11101                   else
11102                     buf.puts (">");
11103                 }
11104             }
11105
11106           /* For C++ methods, append formal parameter type
11107              information, if PHYSNAME.  */
11108
11109           if (physname && die->tag == DW_TAG_subprogram
11110               && cu->language == language_cplus)
11111             {
11112               struct type *type = read_type_die (die, cu);
11113
11114               c_type_print_args (type, &buf, 1, cu->language,
11115                                  &type_print_raw_options);
11116
11117               if (cu->language == language_cplus)
11118                 {
11119                   /* Assume that an artificial first parameter is
11120                      "this", but do not crash if it is not.  RealView
11121                      marks unnamed (and thus unused) parameters as
11122                      artificial; there is no way to differentiate
11123                      the two cases.  */
11124                   if (TYPE_NFIELDS (type) > 0
11125                       && TYPE_FIELD_ARTIFICIAL (type, 0)
11126                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
11127                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
11128                                                                         0))))
11129                     buf.puts (" const");
11130                 }
11131             }
11132
11133           const std::string &intermediate_name = buf.string ();
11134
11135           if (cu->language == language_cplus)
11136             canonical_name
11137               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
11138                                           &objfile->per_bfd->storage_obstack);
11139
11140           /* If we only computed INTERMEDIATE_NAME, or if
11141              INTERMEDIATE_NAME is already canonical, then we need to
11142              copy it to the appropriate obstack.  */
11143           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
11144             name = ((const char *)
11145                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
11146                                    intermediate_name.c_str (),
11147                                    intermediate_name.length ()));
11148           else
11149             name = canonical_name;
11150         }
11151     }
11152
11153   return name;
11154 }
11155
11156 /* Return the fully qualified name of DIE, based on its DW_AT_name.
11157    If scope qualifiers are appropriate they will be added.  The result
11158    will be allocated on the storage_obstack, or NULL if the DIE does
11159    not have a name.  NAME may either be from a previous call to
11160    dwarf2_name or NULL.
11161
11162    The output string will be canonicalized (if C++).  */
11163
11164 static const char *
11165 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11166 {
11167   return dwarf2_compute_name (name, die, cu, 0);
11168 }
11169
11170 /* Construct a physname for the given DIE in CU.  NAME may either be
11171    from a previous call to dwarf2_name or NULL.  The result will be
11172    allocated on the objfile_objstack or NULL if the DIE does not have a
11173    name.
11174
11175    The output string will be canonicalized (if C++).  */
11176
11177 static const char *
11178 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
11179 {
11180   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11181   const char *retval, *mangled = NULL, *canon = NULL;
11182   int need_copy = 1;
11183
11184   /* In this case dwarf2_compute_name is just a shortcut not building anything
11185      on its own.  */
11186   if (!die_needs_namespace (die, cu))
11187     return dwarf2_compute_name (name, die, cu, 1);
11188
11189   mangled = dw2_linkage_name (die, cu);
11190
11191   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11192      See https://github.com/rust-lang/rust/issues/32925.  */
11193   if (cu->language == language_rust && mangled != NULL
11194       && strchr (mangled, '{') != NULL)
11195     mangled = NULL;
11196
11197   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11198      has computed.  */
11199   gdb::unique_xmalloc_ptr<char> demangled;
11200   if (mangled != NULL)
11201     {
11202       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
11203          type.  It is easier for GDB users to search for such functions as
11204          `name(params)' than `long name(params)'.  In such case the minimal
11205          symbol names do not match the full symbol names but for template
11206          functions there is never a need to look up their definition from their
11207          declaration so the only disadvantage remains the minimal symbol
11208          variant `long name(params)' does not have the proper inferior type.
11209          */
11210
11211       if (cu->language == language_go)
11212         {
11213           /* This is a lie, but we already lie to the caller new_symbol.
11214              new_symbol assumes we return the mangled name.
11215              This just undoes that lie until things are cleaned up.  */
11216         }
11217       else
11218         {
11219           demangled.reset (gdb_demangle (mangled,
11220                                          (DMGL_PARAMS | DMGL_ANSI
11221                                           | DMGL_RET_DROP)));
11222         }
11223       if (demangled)
11224         canon = demangled.get ();
11225       else
11226         {
11227           canon = mangled;
11228           need_copy = 0;
11229         }
11230     }
11231
11232   if (canon == NULL || check_physname)
11233     {
11234       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11235
11236       if (canon != NULL && strcmp (physname, canon) != 0)
11237         {
11238           /* It may not mean a bug in GDB.  The compiler could also
11239              compute DW_AT_linkage_name incorrectly.  But in such case
11240              GDB would need to be bug-to-bug compatible.  */
11241
11242           complaint (&symfile_complaints,
11243                      _("Computed physname <%s> does not match demangled <%s> "
11244                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
11245                      physname, canon, mangled, to_underlying (die->sect_off),
11246                      objfile_name (objfile));
11247
11248           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11249              is available here - over computed PHYSNAME.  It is safer
11250              against both buggy GDB and buggy compilers.  */
11251
11252           retval = canon;
11253         }
11254       else
11255         {
11256           retval = physname;
11257           need_copy = 0;
11258         }
11259     }
11260   else
11261     retval = canon;
11262
11263   if (need_copy)
11264     retval = ((const char *)
11265               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11266                              retval, strlen (retval)));
11267
11268   return retval;
11269 }
11270
11271 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11272    a new symbol for it.
11273
11274    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11275
11276 static int
11277 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11278 {
11279   struct attribute *attr;
11280
11281   /* If the die does not have a name, this is not a namespace
11282      alias.  */
11283   attr = dwarf2_attr (die, DW_AT_name, cu);
11284   if (attr != NULL)
11285     {
11286       int num;
11287       struct die_info *d = die;
11288       struct dwarf2_cu *imported_cu = cu;
11289
11290       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11291          keep inspecting DIEs until we hit the underlying import.  */
11292 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11293       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11294         {
11295           attr = dwarf2_attr (d, DW_AT_import, cu);
11296           if (attr == NULL)
11297             break;
11298
11299           d = follow_die_ref (d, attr, &imported_cu);
11300           if (d->tag != DW_TAG_imported_declaration)
11301             break;
11302         }
11303
11304       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11305         {
11306           complaint (&symfile_complaints,
11307                      _("DIE at 0x%x has too many recursively imported "
11308                        "declarations"), to_underlying (d->sect_off));
11309           return 0;
11310         }
11311
11312       if (attr != NULL)
11313         {
11314           struct type *type;
11315           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11316
11317           type = get_die_type_at_offset (sect_off, cu->per_cu);
11318           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11319             {
11320               /* This declaration is a global namespace alias.  Add
11321                  a symbol for it whose type is the aliased namespace.  */
11322               new_symbol (die, type, cu);
11323               return 1;
11324             }
11325         }
11326     }
11327
11328   return 0;
11329 }
11330
11331 /* Return the using directives repository (global or local?) to use in the
11332    current context for LANGUAGE.
11333
11334    For Ada, imported declarations can materialize renamings, which *may* be
11335    global.  However it is impossible (for now?) in DWARF to distinguish
11336    "external" imported declarations and "static" ones.  As all imported
11337    declarations seem to be static in all other languages, make them all CU-wide
11338    global only in Ada.  */
11339
11340 static struct using_direct **
11341 using_directives (enum language language)
11342 {
11343   if (language == language_ada && context_stack_depth == 0)
11344     return &global_using_directives;
11345   else
11346     return &local_using_directives;
11347 }
11348
11349 /* Read the import statement specified by the given die and record it.  */
11350
11351 static void
11352 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11353 {
11354   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11355   struct attribute *import_attr;
11356   struct die_info *imported_die, *child_die;
11357   struct dwarf2_cu *imported_cu;
11358   const char *imported_name;
11359   const char *imported_name_prefix;
11360   const char *canonical_name;
11361   const char *import_alias;
11362   const char *imported_declaration = NULL;
11363   const char *import_prefix;
11364   std::vector<const char *> excludes;
11365
11366   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11367   if (import_attr == NULL)
11368     {
11369       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11370                  dwarf_tag_name (die->tag));
11371       return;
11372     }
11373
11374   imported_cu = cu;
11375   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11376   imported_name = dwarf2_name (imported_die, imported_cu);
11377   if (imported_name == NULL)
11378     {
11379       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11380
11381         The import in the following code:
11382         namespace A
11383           {
11384             typedef int B;
11385           }
11386
11387         int main ()
11388           {
11389             using A::B;
11390             B b;
11391             return b;
11392           }
11393
11394         ...
11395          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11396             <52>   DW_AT_decl_file   : 1
11397             <53>   DW_AT_decl_line   : 6
11398             <54>   DW_AT_import      : <0x75>
11399          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11400             <59>   DW_AT_name        : B
11401             <5b>   DW_AT_decl_file   : 1
11402             <5c>   DW_AT_decl_line   : 2
11403             <5d>   DW_AT_type        : <0x6e>
11404         ...
11405          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11406             <76>   DW_AT_byte_size   : 4
11407             <77>   DW_AT_encoding    : 5        (signed)
11408
11409         imports the wrong die ( 0x75 instead of 0x58 ).
11410         This case will be ignored until the gcc bug is fixed.  */
11411       return;
11412     }
11413
11414   /* Figure out the local name after import.  */
11415   import_alias = dwarf2_name (die, cu);
11416
11417   /* Figure out where the statement is being imported to.  */
11418   import_prefix = determine_prefix (die, cu);
11419
11420   /* Figure out what the scope of the imported die is and prepend it
11421      to the name of the imported die.  */
11422   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11423
11424   if (imported_die->tag != DW_TAG_namespace
11425       && imported_die->tag != DW_TAG_module)
11426     {
11427       imported_declaration = imported_name;
11428       canonical_name = imported_name_prefix;
11429     }
11430   else if (strlen (imported_name_prefix) > 0)
11431     canonical_name = obconcat (&objfile->objfile_obstack,
11432                                imported_name_prefix,
11433                                (cu->language == language_d ? "." : "::"),
11434                                imported_name, (char *) NULL);
11435   else
11436     canonical_name = imported_name;
11437
11438   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11439     for (child_die = die->child; child_die && child_die->tag;
11440          child_die = sibling_die (child_die))
11441       {
11442         /* DWARF-4: A Fortran use statement with a “rename list” may be
11443            represented by an imported module entry with an import attribute
11444            referring to the module and owned entries corresponding to those
11445            entities that are renamed as part of being imported.  */
11446
11447         if (child_die->tag != DW_TAG_imported_declaration)
11448           {
11449             complaint (&symfile_complaints,
11450                        _("child DW_TAG_imported_declaration expected "
11451                          "- DIE at 0x%x [in module %s]"),
11452                        to_underlying (child_die->sect_off), objfile_name (objfile));
11453             continue;
11454           }
11455
11456         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11457         if (import_attr == NULL)
11458           {
11459             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
11460                        dwarf_tag_name (child_die->tag));
11461             continue;
11462           }
11463
11464         imported_cu = cu;
11465         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11466                                               &imported_cu);
11467         imported_name = dwarf2_name (imported_die, imported_cu);
11468         if (imported_name == NULL)
11469           {
11470             complaint (&symfile_complaints,
11471                        _("child DW_TAG_imported_declaration has unknown "
11472                          "imported name - DIE at 0x%x [in module %s]"),
11473                        to_underlying (child_die->sect_off), objfile_name (objfile));
11474             continue;
11475           }
11476
11477         excludes.push_back (imported_name);
11478
11479         process_die (child_die, cu);
11480       }
11481
11482   add_using_directive (using_directives (cu->language),
11483                        import_prefix,
11484                        canonical_name,
11485                        import_alias,
11486                        imported_declaration,
11487                        excludes,
11488                        0,
11489                        &objfile->objfile_obstack);
11490 }
11491
11492 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11493    types, but gives them a size of zero.  Starting with version 14,
11494    ICC is compatible with GCC.  */
11495
11496 static int
11497 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11498 {
11499   if (!cu->checked_producer)
11500     check_producer (cu);
11501
11502   return cu->producer_is_icc_lt_14;
11503 }
11504
11505 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11506    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11507    this, it was first present in GCC release 4.3.0.  */
11508
11509 static int
11510 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11511 {
11512   if (!cu->checked_producer)
11513     check_producer (cu);
11514
11515   return cu->producer_is_gcc_lt_4_3;
11516 }
11517
11518 static file_and_directory
11519 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11520 {
11521   file_and_directory res;
11522
11523   /* Find the filename.  Do not use dwarf2_name here, since the filename
11524      is not a source language identifier.  */
11525   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11526   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11527
11528   if (res.comp_dir == NULL
11529       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11530       && IS_ABSOLUTE_PATH (res.name))
11531     {
11532       res.comp_dir_storage = ldirname (res.name);
11533       if (!res.comp_dir_storage.empty ())
11534         res.comp_dir = res.comp_dir_storage.c_str ();
11535     }
11536   if (res.comp_dir != NULL)
11537     {
11538       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11539          directory, get rid of it.  */
11540       const char *cp = strchr (res.comp_dir, ':');
11541
11542       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11543         res.comp_dir = cp + 1;
11544     }
11545
11546   if (res.name == NULL)
11547     res.name = "<unknown>";
11548
11549   return res;
11550 }
11551
11552 /* Handle DW_AT_stmt_list for a compilation unit.
11553    DIE is the DW_TAG_compile_unit die for CU.
11554    COMP_DIR is the compilation directory.  LOWPC is passed to
11555    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11556
11557 static void
11558 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11559                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11560 {
11561   struct dwarf2_per_objfile *dwarf2_per_objfile
11562     = cu->per_cu->dwarf2_per_objfile;
11563   struct objfile *objfile = dwarf2_per_objfile->objfile;
11564   struct attribute *attr;
11565   struct line_header line_header_local;
11566   hashval_t line_header_local_hash;
11567   void **slot;
11568   int decode_mapping;
11569
11570   gdb_assert (! cu->per_cu->is_debug_types);
11571
11572   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11573   if (attr == NULL)
11574     return;
11575
11576   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11577
11578   /* The line header hash table is only created if needed (it exists to
11579      prevent redundant reading of the line table for partial_units).
11580      If we're given a partial_unit, we'll need it.  If we're given a
11581      compile_unit, then use the line header hash table if it's already
11582      created, but don't create one just yet.  */
11583
11584   if (dwarf2_per_objfile->line_header_hash == NULL
11585       && die->tag == DW_TAG_partial_unit)
11586     {
11587       dwarf2_per_objfile->line_header_hash
11588         = htab_create_alloc_ex (127, line_header_hash_voidp,
11589                                 line_header_eq_voidp,
11590                                 free_line_header_voidp,
11591                                 &objfile->objfile_obstack,
11592                                 hashtab_obstack_allocate,
11593                                 dummy_obstack_deallocate);
11594     }
11595
11596   line_header_local.sect_off = line_offset;
11597   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11598   line_header_local_hash = line_header_hash (&line_header_local);
11599   if (dwarf2_per_objfile->line_header_hash != NULL)
11600     {
11601       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11602                                        &line_header_local,
11603                                        line_header_local_hash, NO_INSERT);
11604
11605       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11606          is not present in *SLOT (since if there is something in *SLOT then
11607          it will be for a partial_unit).  */
11608       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11609         {
11610           gdb_assert (*slot != NULL);
11611           cu->line_header = (struct line_header *) *slot;
11612           return;
11613         }
11614     }
11615
11616   /* dwarf_decode_line_header does not yet provide sufficient information.
11617      We always have to call also dwarf_decode_lines for it.  */
11618   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11619   if (lh == NULL)
11620     return;
11621
11622   cu->line_header = lh.release ();
11623   cu->line_header_die_owner = die;
11624
11625   if (dwarf2_per_objfile->line_header_hash == NULL)
11626     slot = NULL;
11627   else
11628     {
11629       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11630                                        &line_header_local,
11631                                        line_header_local_hash, INSERT);
11632       gdb_assert (slot != NULL);
11633     }
11634   if (slot != NULL && *slot == NULL)
11635     {
11636       /* This newly decoded line number information unit will be owned
11637          by line_header_hash hash table.  */
11638       *slot = cu->line_header;
11639       cu->line_header_die_owner = NULL;
11640     }
11641   else
11642     {
11643       /* We cannot free any current entry in (*slot) as that struct line_header
11644          may be already used by multiple CUs.  Create only temporary decoded
11645          line_header for this CU - it may happen at most once for each line
11646          number information unit.  And if we're not using line_header_hash
11647          then this is what we want as well.  */
11648       gdb_assert (die->tag != DW_TAG_partial_unit);
11649     }
11650   decode_mapping = (die->tag != DW_TAG_partial_unit);
11651   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11652                       decode_mapping);
11653
11654 }
11655
11656 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11657
11658 static void
11659 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11660 {
11661   struct dwarf2_per_objfile *dwarf2_per_objfile
11662     = cu->per_cu->dwarf2_per_objfile;
11663   struct objfile *objfile = dwarf2_per_objfile->objfile;
11664   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11665   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11666   CORE_ADDR highpc = ((CORE_ADDR) 0);
11667   struct attribute *attr;
11668   struct die_info *child_die;
11669   CORE_ADDR baseaddr;
11670
11671   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11672
11673   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11674
11675   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11676      from finish_block.  */
11677   if (lowpc == ((CORE_ADDR) -1))
11678     lowpc = highpc;
11679   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11680
11681   file_and_directory fnd = find_file_and_directory (die, cu);
11682
11683   prepare_one_comp_unit (cu, die, cu->language);
11684
11685   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11686      standardised yet.  As a workaround for the language detection we fall
11687      back to the DW_AT_producer string.  */
11688   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11689     cu->language = language_opencl;
11690
11691   /* Similar hack for Go.  */
11692   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11693     set_cu_language (DW_LANG_Go, cu);
11694
11695   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11696
11697   /* Decode line number information if present.  We do this before
11698      processing child DIEs, so that the line header table is available
11699      for DW_AT_decl_file.  */
11700   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11701
11702   /* Process all dies in compilation unit.  */
11703   if (die->child != NULL)
11704     {
11705       child_die = die->child;
11706       while (child_die && child_die->tag)
11707         {
11708           process_die (child_die, cu);
11709           child_die = sibling_die (child_die);
11710         }
11711     }
11712
11713   /* Decode macro information, if present.  Dwarf 2 macro information
11714      refers to information in the line number info statement program
11715      header, so we can only read it if we've read the header
11716      successfully.  */
11717   attr = dwarf2_attr (die, DW_AT_macros, cu);
11718   if (attr == NULL)
11719     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11720   if (attr && cu->line_header)
11721     {
11722       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11723         complaint (&symfile_complaints,
11724                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11725
11726       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11727     }
11728   else
11729     {
11730       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11731       if (attr && cu->line_header)
11732         {
11733           unsigned int macro_offset = DW_UNSND (attr);
11734
11735           dwarf_decode_macros (cu, macro_offset, 0);
11736         }
11737     }
11738 }
11739
11740 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11741    Create the set of symtabs used by this TU, or if this TU is sharing
11742    symtabs with another TU and the symtabs have already been created
11743    then restore those symtabs in the line header.
11744    We don't need the pc/line-number mapping for type units.  */
11745
11746 static void
11747 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11748 {
11749   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11750   struct type_unit_group *tu_group;
11751   int first_time;
11752   struct attribute *attr;
11753   unsigned int i;
11754   struct signatured_type *sig_type;
11755
11756   gdb_assert (per_cu->is_debug_types);
11757   sig_type = (struct signatured_type *) per_cu;
11758
11759   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11760
11761   /* If we're using .gdb_index (includes -readnow) then
11762      per_cu->type_unit_group may not have been set up yet.  */
11763   if (sig_type->type_unit_group == NULL)
11764     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11765   tu_group = sig_type->type_unit_group;
11766
11767   /* If we've already processed this stmt_list there's no real need to
11768      do it again, we could fake it and just recreate the part we need
11769      (file name,index -> symtab mapping).  If data shows this optimization
11770      is useful we can do it then.  */
11771   first_time = tu_group->compunit_symtab == NULL;
11772
11773   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11774      debug info.  */
11775   line_header_up lh;
11776   if (attr != NULL)
11777     {
11778       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11779       lh = dwarf_decode_line_header (line_offset, cu);
11780     }
11781   if (lh == NULL)
11782     {
11783       if (first_time)
11784         dwarf2_start_symtab (cu, "", NULL, 0);
11785       else
11786         {
11787           gdb_assert (tu_group->symtabs == NULL);
11788           restart_symtab (tu_group->compunit_symtab, "", 0);
11789         }
11790       return;
11791     }
11792
11793   cu->line_header = lh.release ();
11794   cu->line_header_die_owner = die;
11795
11796   if (first_time)
11797     {
11798       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11799
11800       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11801          still initializing it, and our caller (a few levels up)
11802          process_full_type_unit still needs to know if this is the first
11803          time.  */
11804
11805       tu_group->num_symtabs = cu->line_header->file_names.size ();
11806       tu_group->symtabs = XNEWVEC (struct symtab *,
11807                                    cu->line_header->file_names.size ());
11808
11809       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11810         {
11811           file_entry &fe = cu->line_header->file_names[i];
11812
11813           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11814
11815           if (current_subfile->symtab == NULL)
11816             {
11817               /* NOTE: start_subfile will recognize when it's been
11818                  passed a file it has already seen.  So we can't
11819                  assume there's a simple mapping from
11820                  cu->line_header->file_names to subfiles, plus
11821                  cu->line_header->file_names may contain dups.  */
11822               current_subfile->symtab
11823                 = allocate_symtab (cust, current_subfile->name);
11824             }
11825
11826           fe.symtab = current_subfile->symtab;
11827           tu_group->symtabs[i] = fe.symtab;
11828         }
11829     }
11830   else
11831     {
11832       restart_symtab (tu_group->compunit_symtab, "", 0);
11833
11834       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11835         {
11836           file_entry &fe = cu->line_header->file_names[i];
11837
11838           fe.symtab = tu_group->symtabs[i];
11839         }
11840     }
11841
11842   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11843      so they don't have a "real" (so to speak) symtab anyway.
11844      There is later code that will assign the main symtab to all symbols
11845      that don't have one.  We need to handle the case of a symbol with a
11846      missing symtab (DW_AT_decl_file) anyway.  */
11847 }
11848
11849 /* Process DW_TAG_type_unit.
11850    For TUs we want to skip the first top level sibling if it's not the
11851    actual type being defined by this TU.  In this case the first top
11852    level sibling is there to provide context only.  */
11853
11854 static void
11855 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11856 {
11857   struct die_info *child_die;
11858
11859   prepare_one_comp_unit (cu, die, language_minimal);
11860
11861   /* Initialize (or reinitialize) the machinery for building symtabs.
11862      We do this before processing child DIEs, so that the line header table
11863      is available for DW_AT_decl_file.  */
11864   setup_type_unit_groups (die, cu);
11865
11866   if (die->child != NULL)
11867     {
11868       child_die = die->child;
11869       while (child_die && child_die->tag)
11870         {
11871           process_die (child_die, cu);
11872           child_die = sibling_die (child_die);
11873         }
11874     }
11875 }
11876 \f
11877 /* DWO/DWP files.
11878
11879    http://gcc.gnu.org/wiki/DebugFission
11880    http://gcc.gnu.org/wiki/DebugFissionDWP
11881
11882    To simplify handling of both DWO files ("object" files with the DWARF info)
11883    and DWP files (a file with the DWOs packaged up into one file), we treat
11884    DWP files as having a collection of virtual DWO files.  */
11885
11886 static hashval_t
11887 hash_dwo_file (const void *item)
11888 {
11889   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11890   hashval_t hash;
11891
11892   hash = htab_hash_string (dwo_file->dwo_name);
11893   if (dwo_file->comp_dir != NULL)
11894     hash += htab_hash_string (dwo_file->comp_dir);
11895   return hash;
11896 }
11897
11898 static int
11899 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11900 {
11901   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11902   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11903
11904   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11905     return 0;
11906   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11907     return lhs->comp_dir == rhs->comp_dir;
11908   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11909 }
11910
11911 /* Allocate a hash table for DWO files.  */
11912
11913 static htab_t
11914 allocate_dwo_file_hash_table (struct objfile *objfile)
11915 {
11916   return htab_create_alloc_ex (41,
11917                                hash_dwo_file,
11918                                eq_dwo_file,
11919                                NULL,
11920                                &objfile->objfile_obstack,
11921                                hashtab_obstack_allocate,
11922                                dummy_obstack_deallocate);
11923 }
11924
11925 /* Lookup DWO file DWO_NAME.  */
11926
11927 static void **
11928 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11929                       const char *dwo_name,
11930                       const char *comp_dir)
11931 {
11932   struct dwo_file find_entry;
11933   void **slot;
11934
11935   if (dwarf2_per_objfile->dwo_files == NULL)
11936     dwarf2_per_objfile->dwo_files
11937       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11938
11939   memset (&find_entry, 0, sizeof (find_entry));
11940   find_entry.dwo_name = dwo_name;
11941   find_entry.comp_dir = comp_dir;
11942   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11943
11944   return slot;
11945 }
11946
11947 static hashval_t
11948 hash_dwo_unit (const void *item)
11949 {
11950   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11951
11952   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11953   return dwo_unit->signature;
11954 }
11955
11956 static int
11957 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11958 {
11959   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11960   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11961
11962   /* The signature is assumed to be unique within the DWO file.
11963      So while object file CU dwo_id's always have the value zero,
11964      that's OK, assuming each object file DWO file has only one CU,
11965      and that's the rule for now.  */
11966   return lhs->signature == rhs->signature;
11967 }
11968
11969 /* Allocate a hash table for DWO CUs,TUs.
11970    There is one of these tables for each of CUs,TUs for each DWO file.  */
11971
11972 static htab_t
11973 allocate_dwo_unit_table (struct objfile *objfile)
11974 {
11975   /* Start out with a pretty small number.
11976      Generally DWO files contain only one CU and maybe some TUs.  */
11977   return htab_create_alloc_ex (3,
11978                                hash_dwo_unit,
11979                                eq_dwo_unit,
11980                                NULL,
11981                                &objfile->objfile_obstack,
11982                                hashtab_obstack_allocate,
11983                                dummy_obstack_deallocate);
11984 }
11985
11986 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11987
11988 struct create_dwo_cu_data
11989 {
11990   struct dwo_file *dwo_file;
11991   struct dwo_unit dwo_unit;
11992 };
11993
11994 /* die_reader_func for create_dwo_cu.  */
11995
11996 static void
11997 create_dwo_cu_reader (const struct die_reader_specs *reader,
11998                       const gdb_byte *info_ptr,
11999                       struct die_info *comp_unit_die,
12000                       int has_children,
12001                       void *datap)
12002 {
12003   struct dwarf2_cu *cu = reader->cu;
12004   sect_offset sect_off = cu->per_cu->sect_off;
12005   struct dwarf2_section_info *section = cu->per_cu->section;
12006   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
12007   struct dwo_file *dwo_file = data->dwo_file;
12008   struct dwo_unit *dwo_unit = &data->dwo_unit;
12009   struct attribute *attr;
12010
12011   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
12012   if (attr == NULL)
12013     {
12014       complaint (&symfile_complaints,
12015                  _("Dwarf Error: debug entry at offset 0x%x is missing"
12016                    " its dwo_id [in module %s]"),
12017                  to_underlying (sect_off), dwo_file->dwo_name);
12018       return;
12019     }
12020
12021   dwo_unit->dwo_file = dwo_file;
12022   dwo_unit->signature = DW_UNSND (attr);
12023   dwo_unit->section = section;
12024   dwo_unit->sect_off = sect_off;
12025   dwo_unit->length = cu->per_cu->length;
12026
12027   if (dwarf_read_debug)
12028     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
12029                         to_underlying (sect_off),
12030                         hex_string (dwo_unit->signature));
12031 }
12032
12033 /* Create the dwo_units for the CUs in a DWO_FILE.
12034    Note: This function processes DWO files only, not DWP files.  */
12035
12036 static void
12037 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12038                        struct dwo_file &dwo_file, dwarf2_section_info &section,
12039                        htab_t &cus_htab)
12040 {
12041   struct objfile *objfile = dwarf2_per_objfile->objfile;
12042   const gdb_byte *info_ptr, *end_ptr;
12043
12044   dwarf2_read_section (objfile, &section);
12045   info_ptr = section.buffer;
12046
12047   if (info_ptr == NULL)
12048     return;
12049
12050   if (dwarf_read_debug)
12051     {
12052       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
12053                           get_section_name (&section),
12054                           get_section_file_name (&section));
12055     }
12056
12057   end_ptr = info_ptr + section.size;
12058   while (info_ptr < end_ptr)
12059     {
12060       struct dwarf2_per_cu_data per_cu;
12061       struct create_dwo_cu_data create_dwo_cu_data;
12062       struct dwo_unit *dwo_unit;
12063       void **slot;
12064       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
12065
12066       memset (&create_dwo_cu_data.dwo_unit, 0,
12067               sizeof (create_dwo_cu_data.dwo_unit));
12068       memset (&per_cu, 0, sizeof (per_cu));
12069       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
12070       per_cu.is_debug_types = 0;
12071       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
12072       per_cu.section = &section;
12073       create_dwo_cu_data.dwo_file = &dwo_file;
12074
12075       init_cutu_and_read_dies_no_follow (
12076           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
12077       info_ptr += per_cu.length;
12078
12079       // If the unit could not be parsed, skip it.
12080       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
12081         continue;
12082
12083       if (cus_htab == NULL)
12084         cus_htab = allocate_dwo_unit_table (objfile);
12085
12086       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12087       *dwo_unit = create_dwo_cu_data.dwo_unit;
12088       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
12089       gdb_assert (slot != NULL);
12090       if (*slot != NULL)
12091         {
12092           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
12093           sect_offset dup_sect_off = dup_cu->sect_off;
12094
12095           complaint (&symfile_complaints,
12096                      _("debug cu entry at offset 0x%x is duplicate to"
12097                        " the entry at offset 0x%x, signature %s"),
12098                      to_underlying (sect_off), to_underlying (dup_sect_off),
12099                      hex_string (dwo_unit->signature));
12100         }
12101       *slot = (void *)dwo_unit;
12102     }
12103 }
12104
12105 /* DWP file .debug_{cu,tu}_index section format:
12106    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
12107
12108    DWP Version 1:
12109
12110    Both index sections have the same format, and serve to map a 64-bit
12111    signature to a set of section numbers.  Each section begins with a header,
12112    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
12113    indexes, and a pool of 32-bit section numbers.  The index sections will be
12114    aligned at 8-byte boundaries in the file.
12115
12116    The index section header consists of:
12117
12118     V, 32 bit version number
12119     -, 32 bits unused
12120     N, 32 bit number of compilation units or type units in the index
12121     M, 32 bit number of slots in the hash table
12122
12123    Numbers are recorded using the byte order of the application binary.
12124
12125    The hash table begins at offset 16 in the section, and consists of an array
12126    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
12127    order of the application binary).  Unused slots in the hash table are 0.
12128    (We rely on the extreme unlikeliness of a signature being exactly 0.)
12129
12130    The parallel table begins immediately after the hash table
12131    (at offset 16 + 8 * M from the beginning of the section), and consists of an
12132    array of 32-bit indexes (using the byte order of the application binary),
12133    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
12134    table contains a 32-bit index into the pool of section numbers.  For unused
12135    hash table slots, the corresponding entry in the parallel table will be 0.
12136
12137    The pool of section numbers begins immediately following the hash table
12138    (at offset 16 + 12 * M from the beginning of the section).  The pool of
12139    section numbers consists of an array of 32-bit words (using the byte order
12140    of the application binary).  Each item in the array is indexed starting
12141    from 0.  The hash table entry provides the index of the first section
12142    number in the set.  Additional section numbers in the set follow, and the
12143    set is terminated by a 0 entry (section number 0 is not used in ELF).
12144
12145    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
12146    section must be the first entry in the set, and the .debug_abbrev.dwo must
12147    be the second entry. Other members of the set may follow in any order.
12148
12149    ---
12150
12151    DWP Version 2:
12152
12153    DWP Version 2 combines all the .debug_info, etc. sections into one,
12154    and the entries in the index tables are now offsets into these sections.
12155    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
12156    section.
12157
12158    Index Section Contents:
12159     Header
12160     Hash Table of Signatures   dwp_hash_table.hash_table
12161     Parallel Table of Indices  dwp_hash_table.unit_table
12162     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
12163     Table of Section Sizes     dwp_hash_table.v2.sizes
12164
12165    The index section header consists of:
12166
12167     V, 32 bit version number
12168     L, 32 bit number of columns in the table of section offsets
12169     N, 32 bit number of compilation units or type units in the index
12170     M, 32 bit number of slots in the hash table
12171
12172    Numbers are recorded using the byte order of the application binary.
12173
12174    The hash table has the same format as version 1.
12175    The parallel table of indices has the same format as version 1,
12176    except that the entries are origin-1 indices into the table of sections
12177    offsets and the table of section sizes.
12178
12179    The table of offsets begins immediately following the parallel table
12180    (at offset 16 + 12 * M from the beginning of the section).  The table is
12181    a two-dimensional array of 32-bit words (using the byte order of the
12182    application binary), with L columns and N+1 rows, in row-major order.
12183    Each row in the array is indexed starting from 0.  The first row provides
12184    a key to the remaining rows: each column in this row provides an identifier
12185    for a debug section, and the offsets in the same column of subsequent rows
12186    refer to that section.  The section identifiers are:
12187
12188     DW_SECT_INFO         1  .debug_info.dwo
12189     DW_SECT_TYPES        2  .debug_types.dwo
12190     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12191     DW_SECT_LINE         4  .debug_line.dwo
12192     DW_SECT_LOC          5  .debug_loc.dwo
12193     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12194     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12195     DW_SECT_MACRO        8  .debug_macro.dwo
12196
12197    The offsets provided by the CU and TU index sections are the base offsets
12198    for the contributions made by each CU or TU to the corresponding section
12199    in the package file.  Each CU and TU header contains an abbrev_offset
12200    field, used to find the abbreviations table for that CU or TU within the
12201    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12202    be interpreted as relative to the base offset given in the index section.
12203    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12204    should be interpreted as relative to the base offset for .debug_line.dwo,
12205    and offsets into other debug sections obtained from DWARF attributes should
12206    also be interpreted as relative to the corresponding base offset.
12207
12208    The table of sizes begins immediately following the table of offsets.
12209    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12210    with L columns and N rows, in row-major order.  Each row in the array is
12211    indexed starting from 1 (row 0 is shared by the two tables).
12212
12213    ---
12214
12215    Hash table lookup is handled the same in version 1 and 2:
12216
12217    We assume that N and M will not exceed 2^32 - 1.
12218    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12219
12220    Given a 64-bit compilation unit signature or a type signature S, an entry
12221    in the hash table is located as follows:
12222
12223    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12224       the low-order k bits all set to 1.
12225
12226    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12227
12228    3) If the hash table entry at index H matches the signature, use that
12229       entry.  If the hash table entry at index H is unused (all zeroes),
12230       terminate the search: the signature is not present in the table.
12231
12232    4) Let H = (H + H') modulo M. Repeat at Step 3.
12233
12234    Because M > N and H' and M are relatively prime, the search is guaranteed
12235    to stop at an unused slot or find the match.  */
12236
12237 /* Create a hash table to map DWO IDs to their CU/TU entry in
12238    .debug_{info,types}.dwo in DWP_FILE.
12239    Returns NULL if there isn't one.
12240    Note: This function processes DWP files only, not DWO files.  */
12241
12242 static struct dwp_hash_table *
12243 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12244                        struct dwp_file *dwp_file, int is_debug_types)
12245 {
12246   struct objfile *objfile = dwarf2_per_objfile->objfile;
12247   bfd *dbfd = dwp_file->dbfd;
12248   const gdb_byte *index_ptr, *index_end;
12249   struct dwarf2_section_info *index;
12250   uint32_t version, nr_columns, nr_units, nr_slots;
12251   struct dwp_hash_table *htab;
12252
12253   if (is_debug_types)
12254     index = &dwp_file->sections.tu_index;
12255   else
12256     index = &dwp_file->sections.cu_index;
12257
12258   if (dwarf2_section_empty_p (index))
12259     return NULL;
12260   dwarf2_read_section (objfile, index);
12261
12262   index_ptr = index->buffer;
12263   index_end = index_ptr + index->size;
12264
12265   version = read_4_bytes (dbfd, index_ptr);
12266   index_ptr += 4;
12267   if (version == 2)
12268     nr_columns = read_4_bytes (dbfd, index_ptr);
12269   else
12270     nr_columns = 0;
12271   index_ptr += 4;
12272   nr_units = read_4_bytes (dbfd, index_ptr);
12273   index_ptr += 4;
12274   nr_slots = read_4_bytes (dbfd, index_ptr);
12275   index_ptr += 4;
12276
12277   if (version != 1 && version != 2)
12278     {
12279       error (_("Dwarf Error: unsupported DWP file version (%s)"
12280                " [in module %s]"),
12281              pulongest (version), dwp_file->name);
12282     }
12283   if (nr_slots != (nr_slots & -nr_slots))
12284     {
12285       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12286                " is not power of 2 [in module %s]"),
12287              pulongest (nr_slots), dwp_file->name);
12288     }
12289
12290   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12291   htab->version = version;
12292   htab->nr_columns = nr_columns;
12293   htab->nr_units = nr_units;
12294   htab->nr_slots = nr_slots;
12295   htab->hash_table = index_ptr;
12296   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12297
12298   /* Exit early if the table is empty.  */
12299   if (nr_slots == 0 || nr_units == 0
12300       || (version == 2 && nr_columns == 0))
12301     {
12302       /* All must be zero.  */
12303       if (nr_slots != 0 || nr_units != 0
12304           || (version == 2 && nr_columns != 0))
12305         {
12306           complaint (&symfile_complaints,
12307                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
12308                        " all zero [in modules %s]"),
12309                      dwp_file->name);
12310         }
12311       return htab;
12312     }
12313
12314   if (version == 1)
12315     {
12316       htab->section_pool.v1.indices =
12317         htab->unit_table + sizeof (uint32_t) * nr_slots;
12318       /* It's harder to decide whether the section is too small in v1.
12319          V1 is deprecated anyway so we punt.  */
12320     }
12321   else
12322     {
12323       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12324       int *ids = htab->section_pool.v2.section_ids;
12325       /* Reverse map for error checking.  */
12326       int ids_seen[DW_SECT_MAX + 1];
12327       int i;
12328
12329       if (nr_columns < 2)
12330         {
12331           error (_("Dwarf Error: bad DWP hash table, too few columns"
12332                    " in section table [in module %s]"),
12333                  dwp_file->name);
12334         }
12335       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12336         {
12337           error (_("Dwarf Error: bad DWP hash table, too many columns"
12338                    " in section table [in module %s]"),
12339                  dwp_file->name);
12340         }
12341       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12342       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12343       for (i = 0; i < nr_columns; ++i)
12344         {
12345           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12346
12347           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12348             {
12349               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12350                        " in section table [in module %s]"),
12351                      id, dwp_file->name);
12352             }
12353           if (ids_seen[id] != -1)
12354             {
12355               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12356                        " id %d in section table [in module %s]"),
12357                      id, dwp_file->name);
12358             }
12359           ids_seen[id] = i;
12360           ids[i] = id;
12361         }
12362       /* Must have exactly one info or types section.  */
12363       if (((ids_seen[DW_SECT_INFO] != -1)
12364            + (ids_seen[DW_SECT_TYPES] != -1))
12365           != 1)
12366         {
12367           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12368                    " DWO info/types section [in module %s]"),
12369                  dwp_file->name);
12370         }
12371       /* Must have an abbrev section.  */
12372       if (ids_seen[DW_SECT_ABBREV] == -1)
12373         {
12374           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12375                    " section [in module %s]"),
12376                  dwp_file->name);
12377         }
12378       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12379       htab->section_pool.v2.sizes =
12380         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12381                                          * nr_units * nr_columns);
12382       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12383                                           * nr_units * nr_columns))
12384           > index_end)
12385         {
12386           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12387                    " [in module %s]"),
12388                  dwp_file->name);
12389         }
12390     }
12391
12392   return htab;
12393 }
12394
12395 /* Update SECTIONS with the data from SECTP.
12396
12397    This function is like the other "locate" section routines that are
12398    passed to bfd_map_over_sections, but in this context the sections to
12399    read comes from the DWP V1 hash table, not the full ELF section table.
12400
12401    The result is non-zero for success, or zero if an error was found.  */
12402
12403 static int
12404 locate_v1_virtual_dwo_sections (asection *sectp,
12405                                 struct virtual_v1_dwo_sections *sections)
12406 {
12407   const struct dwop_section_names *names = &dwop_section_names;
12408
12409   if (section_is_p (sectp->name, &names->abbrev_dwo))
12410     {
12411       /* There can be only one.  */
12412       if (sections->abbrev.s.section != NULL)
12413         return 0;
12414       sections->abbrev.s.section = sectp;
12415       sections->abbrev.size = bfd_get_section_size (sectp);
12416     }
12417   else if (section_is_p (sectp->name, &names->info_dwo)
12418            || section_is_p (sectp->name, &names->types_dwo))
12419     {
12420       /* There can be only one.  */
12421       if (sections->info_or_types.s.section != NULL)
12422         return 0;
12423       sections->info_or_types.s.section = sectp;
12424       sections->info_or_types.size = bfd_get_section_size (sectp);
12425     }
12426   else if (section_is_p (sectp->name, &names->line_dwo))
12427     {
12428       /* There can be only one.  */
12429       if (sections->line.s.section != NULL)
12430         return 0;
12431       sections->line.s.section = sectp;
12432       sections->line.size = bfd_get_section_size (sectp);
12433     }
12434   else if (section_is_p (sectp->name, &names->loc_dwo))
12435     {
12436       /* There can be only one.  */
12437       if (sections->loc.s.section != NULL)
12438         return 0;
12439       sections->loc.s.section = sectp;
12440       sections->loc.size = bfd_get_section_size (sectp);
12441     }
12442   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12443     {
12444       /* There can be only one.  */
12445       if (sections->macinfo.s.section != NULL)
12446         return 0;
12447       sections->macinfo.s.section = sectp;
12448       sections->macinfo.size = bfd_get_section_size (sectp);
12449     }
12450   else if (section_is_p (sectp->name, &names->macro_dwo))
12451     {
12452       /* There can be only one.  */
12453       if (sections->macro.s.section != NULL)
12454         return 0;
12455       sections->macro.s.section = sectp;
12456       sections->macro.size = bfd_get_section_size (sectp);
12457     }
12458   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12459     {
12460       /* There can be only one.  */
12461       if (sections->str_offsets.s.section != NULL)
12462         return 0;
12463       sections->str_offsets.s.section = sectp;
12464       sections->str_offsets.size = bfd_get_section_size (sectp);
12465     }
12466   else
12467     {
12468       /* No other kind of section is valid.  */
12469       return 0;
12470     }
12471
12472   return 1;
12473 }
12474
12475 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12476    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12477    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12478    This is for DWP version 1 files.  */
12479
12480 static struct dwo_unit *
12481 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12482                            struct dwp_file *dwp_file,
12483                            uint32_t unit_index,
12484                            const char *comp_dir,
12485                            ULONGEST signature, int is_debug_types)
12486 {
12487   struct objfile *objfile = dwarf2_per_objfile->objfile;
12488   const struct dwp_hash_table *dwp_htab =
12489     is_debug_types ? dwp_file->tus : dwp_file->cus;
12490   bfd *dbfd = dwp_file->dbfd;
12491   const char *kind = is_debug_types ? "TU" : "CU";
12492   struct dwo_file *dwo_file;
12493   struct dwo_unit *dwo_unit;
12494   struct virtual_v1_dwo_sections sections;
12495   void **dwo_file_slot;
12496   int i;
12497
12498   gdb_assert (dwp_file->version == 1);
12499
12500   if (dwarf_read_debug)
12501     {
12502       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12503                           kind,
12504                           pulongest (unit_index), hex_string (signature),
12505                           dwp_file->name);
12506     }
12507
12508   /* Fetch the sections of this DWO unit.
12509      Put a limit on the number of sections we look for so that bad data
12510      doesn't cause us to loop forever.  */
12511
12512 #define MAX_NR_V1_DWO_SECTIONS \
12513   (1 /* .debug_info or .debug_types */ \
12514    + 1 /* .debug_abbrev */ \
12515    + 1 /* .debug_line */ \
12516    + 1 /* .debug_loc */ \
12517    + 1 /* .debug_str_offsets */ \
12518    + 1 /* .debug_macro or .debug_macinfo */ \
12519    + 1 /* trailing zero */)
12520
12521   memset (&sections, 0, sizeof (sections));
12522
12523   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12524     {
12525       asection *sectp;
12526       uint32_t section_nr =
12527         read_4_bytes (dbfd,
12528                       dwp_htab->section_pool.v1.indices
12529                       + (unit_index + i) * sizeof (uint32_t));
12530
12531       if (section_nr == 0)
12532         break;
12533       if (section_nr >= dwp_file->num_sections)
12534         {
12535           error (_("Dwarf Error: bad DWP hash table, section number too large"
12536                    " [in module %s]"),
12537                  dwp_file->name);
12538         }
12539
12540       sectp = dwp_file->elf_sections[section_nr];
12541       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12542         {
12543           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12544                    " [in module %s]"),
12545                  dwp_file->name);
12546         }
12547     }
12548
12549   if (i < 2
12550       || dwarf2_section_empty_p (&sections.info_or_types)
12551       || dwarf2_section_empty_p (&sections.abbrev))
12552     {
12553       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12554                " [in module %s]"),
12555              dwp_file->name);
12556     }
12557   if (i == MAX_NR_V1_DWO_SECTIONS)
12558     {
12559       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12560                " [in module %s]"),
12561              dwp_file->name);
12562     }
12563
12564   /* It's easier for the rest of the code if we fake a struct dwo_file and
12565      have dwo_unit "live" in that.  At least for now.
12566
12567      The DWP file can be made up of a random collection of CUs and TUs.
12568      However, for each CU + set of TUs that came from the same original DWO
12569      file, we can combine them back into a virtual DWO file to save space
12570      (fewer struct dwo_file objects to allocate).  Remember that for really
12571      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12572
12573   std::string virtual_dwo_name =
12574     string_printf ("virtual-dwo/%d-%d-%d-%d",
12575                    get_section_id (&sections.abbrev),
12576                    get_section_id (&sections.line),
12577                    get_section_id (&sections.loc),
12578                    get_section_id (&sections.str_offsets));
12579   /* Can we use an existing virtual DWO file?  */
12580   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12581                                         virtual_dwo_name.c_str (),
12582                                         comp_dir);
12583   /* Create one if necessary.  */
12584   if (*dwo_file_slot == NULL)
12585     {
12586       if (dwarf_read_debug)
12587         {
12588           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12589                               virtual_dwo_name.c_str ());
12590         }
12591       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12592       dwo_file->dwo_name
12593         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12594                                         virtual_dwo_name.c_str (),
12595                                         virtual_dwo_name.size ());
12596       dwo_file->comp_dir = comp_dir;
12597       dwo_file->sections.abbrev = sections.abbrev;
12598       dwo_file->sections.line = sections.line;
12599       dwo_file->sections.loc = sections.loc;
12600       dwo_file->sections.macinfo = sections.macinfo;
12601       dwo_file->sections.macro = sections.macro;
12602       dwo_file->sections.str_offsets = sections.str_offsets;
12603       /* The "str" section is global to the entire DWP file.  */
12604       dwo_file->sections.str = dwp_file->sections.str;
12605       /* The info or types section is assigned below to dwo_unit,
12606          there's no need to record it in dwo_file.
12607          Also, we can't simply record type sections in dwo_file because
12608          we record a pointer into the vector in dwo_unit.  As we collect more
12609          types we'll grow the vector and eventually have to reallocate space
12610          for it, invalidating all copies of pointers into the previous
12611          contents.  */
12612       *dwo_file_slot = dwo_file;
12613     }
12614   else
12615     {
12616       if (dwarf_read_debug)
12617         {
12618           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12619                               virtual_dwo_name.c_str ());
12620         }
12621       dwo_file = (struct dwo_file *) *dwo_file_slot;
12622     }
12623
12624   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12625   dwo_unit->dwo_file = dwo_file;
12626   dwo_unit->signature = signature;
12627   dwo_unit->section =
12628     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12629   *dwo_unit->section = sections.info_or_types;
12630   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12631
12632   return dwo_unit;
12633 }
12634
12635 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12636    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12637    piece within that section used by a TU/CU, return a virtual section
12638    of just that piece.  */
12639
12640 static struct dwarf2_section_info
12641 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12642                        struct dwarf2_section_info *section,
12643                        bfd_size_type offset, bfd_size_type size)
12644 {
12645   struct dwarf2_section_info result;
12646   asection *sectp;
12647
12648   gdb_assert (section != NULL);
12649   gdb_assert (!section->is_virtual);
12650
12651   memset (&result, 0, sizeof (result));
12652   result.s.containing_section = section;
12653   result.is_virtual = 1;
12654
12655   if (size == 0)
12656     return result;
12657
12658   sectp = get_section_bfd_section (section);
12659
12660   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12661      bounds of the real section.  This is a pretty-rare event, so just
12662      flag an error (easier) instead of a warning and trying to cope.  */
12663   if (sectp == NULL
12664       || offset + size > bfd_get_section_size (sectp))
12665     {
12666       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12667                " in section %s [in module %s]"),
12668              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12669              objfile_name (dwarf2_per_objfile->objfile));
12670     }
12671
12672   result.virtual_offset = offset;
12673   result.size = size;
12674   return result;
12675 }
12676
12677 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12678    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12679    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12680    This is for DWP version 2 files.  */
12681
12682 static struct dwo_unit *
12683 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12684                            struct dwp_file *dwp_file,
12685                            uint32_t unit_index,
12686                            const char *comp_dir,
12687                            ULONGEST signature, int is_debug_types)
12688 {
12689   struct objfile *objfile = dwarf2_per_objfile->objfile;
12690   const struct dwp_hash_table *dwp_htab =
12691     is_debug_types ? dwp_file->tus : dwp_file->cus;
12692   bfd *dbfd = dwp_file->dbfd;
12693   const char *kind = is_debug_types ? "TU" : "CU";
12694   struct dwo_file *dwo_file;
12695   struct dwo_unit *dwo_unit;
12696   struct virtual_v2_dwo_sections sections;
12697   void **dwo_file_slot;
12698   int i;
12699
12700   gdb_assert (dwp_file->version == 2);
12701
12702   if (dwarf_read_debug)
12703     {
12704       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12705                           kind,
12706                           pulongest (unit_index), hex_string (signature),
12707                           dwp_file->name);
12708     }
12709
12710   /* Fetch the section offsets of this DWO unit.  */
12711
12712   memset (&sections, 0, sizeof (sections));
12713
12714   for (i = 0; i < dwp_htab->nr_columns; ++i)
12715     {
12716       uint32_t offset = read_4_bytes (dbfd,
12717                                       dwp_htab->section_pool.v2.offsets
12718                                       + (((unit_index - 1) * dwp_htab->nr_columns
12719                                           + i)
12720                                          * sizeof (uint32_t)));
12721       uint32_t size = read_4_bytes (dbfd,
12722                                     dwp_htab->section_pool.v2.sizes
12723                                     + (((unit_index - 1) * dwp_htab->nr_columns
12724                                         + i)
12725                                        * sizeof (uint32_t)));
12726
12727       switch (dwp_htab->section_pool.v2.section_ids[i])
12728         {
12729         case DW_SECT_INFO:
12730         case DW_SECT_TYPES:
12731           sections.info_or_types_offset = offset;
12732           sections.info_or_types_size = size;
12733           break;
12734         case DW_SECT_ABBREV:
12735           sections.abbrev_offset = offset;
12736           sections.abbrev_size = size;
12737           break;
12738         case DW_SECT_LINE:
12739           sections.line_offset = offset;
12740           sections.line_size = size;
12741           break;
12742         case DW_SECT_LOC:
12743           sections.loc_offset = offset;
12744           sections.loc_size = size;
12745           break;
12746         case DW_SECT_STR_OFFSETS:
12747           sections.str_offsets_offset = offset;
12748           sections.str_offsets_size = size;
12749           break;
12750         case DW_SECT_MACINFO:
12751           sections.macinfo_offset = offset;
12752           sections.macinfo_size = size;
12753           break;
12754         case DW_SECT_MACRO:
12755           sections.macro_offset = offset;
12756           sections.macro_size = size;
12757           break;
12758         }
12759     }
12760
12761   /* It's easier for the rest of the code if we fake a struct dwo_file and
12762      have dwo_unit "live" in that.  At least for now.
12763
12764      The DWP file can be made up of a random collection of CUs and TUs.
12765      However, for each CU + set of TUs that came from the same original DWO
12766      file, we can combine them back into a virtual DWO file to save space
12767      (fewer struct dwo_file objects to allocate).  Remember that for really
12768      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12769
12770   std::string virtual_dwo_name =
12771     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12772                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12773                    (long) (sections.line_size ? sections.line_offset : 0),
12774                    (long) (sections.loc_size ? sections.loc_offset : 0),
12775                    (long) (sections.str_offsets_size
12776                            ? sections.str_offsets_offset : 0));
12777   /* Can we use an existing virtual DWO file?  */
12778   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12779                                         virtual_dwo_name.c_str (),
12780                                         comp_dir);
12781   /* Create one if necessary.  */
12782   if (*dwo_file_slot == NULL)
12783     {
12784       if (dwarf_read_debug)
12785         {
12786           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12787                               virtual_dwo_name.c_str ());
12788         }
12789       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12790       dwo_file->dwo_name
12791         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12792                                         virtual_dwo_name.c_str (),
12793                                         virtual_dwo_name.size ());
12794       dwo_file->comp_dir = comp_dir;
12795       dwo_file->sections.abbrev =
12796         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12797                                sections.abbrev_offset, sections.abbrev_size);
12798       dwo_file->sections.line =
12799         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12800                                sections.line_offset, sections.line_size);
12801       dwo_file->sections.loc =
12802         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12803                                sections.loc_offset, sections.loc_size);
12804       dwo_file->sections.macinfo =
12805         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12806                                sections.macinfo_offset, sections.macinfo_size);
12807       dwo_file->sections.macro =
12808         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12809                                sections.macro_offset, sections.macro_size);
12810       dwo_file->sections.str_offsets =
12811         create_dwp_v2_section (dwarf2_per_objfile,
12812                                &dwp_file->sections.str_offsets,
12813                                sections.str_offsets_offset,
12814                                sections.str_offsets_size);
12815       /* The "str" section is global to the entire DWP file.  */
12816       dwo_file->sections.str = dwp_file->sections.str;
12817       /* The info or types section is assigned below to dwo_unit,
12818          there's no need to record it in dwo_file.
12819          Also, we can't simply record type sections in dwo_file because
12820          we record a pointer into the vector in dwo_unit.  As we collect more
12821          types we'll grow the vector and eventually have to reallocate space
12822          for it, invalidating all copies of pointers into the previous
12823          contents.  */
12824       *dwo_file_slot = dwo_file;
12825     }
12826   else
12827     {
12828       if (dwarf_read_debug)
12829         {
12830           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12831                               virtual_dwo_name.c_str ());
12832         }
12833       dwo_file = (struct dwo_file *) *dwo_file_slot;
12834     }
12835
12836   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12837   dwo_unit->dwo_file = dwo_file;
12838   dwo_unit->signature = signature;
12839   dwo_unit->section =
12840     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12841   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12842                                               is_debug_types
12843                                               ? &dwp_file->sections.types
12844                                               : &dwp_file->sections.info,
12845                                               sections.info_or_types_offset,
12846                                               sections.info_or_types_size);
12847   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12848
12849   return dwo_unit;
12850 }
12851
12852 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12853    Returns NULL if the signature isn't found.  */
12854
12855 static struct dwo_unit *
12856 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12857                         struct dwp_file *dwp_file, const char *comp_dir,
12858                         ULONGEST signature, int is_debug_types)
12859 {
12860   const struct dwp_hash_table *dwp_htab =
12861     is_debug_types ? dwp_file->tus : dwp_file->cus;
12862   bfd *dbfd = dwp_file->dbfd;
12863   uint32_t mask = dwp_htab->nr_slots - 1;
12864   uint32_t hash = signature & mask;
12865   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12866   unsigned int i;
12867   void **slot;
12868   struct dwo_unit find_dwo_cu;
12869
12870   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12871   find_dwo_cu.signature = signature;
12872   slot = htab_find_slot (is_debug_types
12873                          ? dwp_file->loaded_tus
12874                          : dwp_file->loaded_cus,
12875                          &find_dwo_cu, INSERT);
12876
12877   if (*slot != NULL)
12878     return (struct dwo_unit *) *slot;
12879
12880   /* Use a for loop so that we don't loop forever on bad debug info.  */
12881   for (i = 0; i < dwp_htab->nr_slots; ++i)
12882     {
12883       ULONGEST signature_in_table;
12884
12885       signature_in_table =
12886         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12887       if (signature_in_table == signature)
12888         {
12889           uint32_t unit_index =
12890             read_4_bytes (dbfd,
12891                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12892
12893           if (dwp_file->version == 1)
12894             {
12895               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12896                                                  dwp_file, unit_index,
12897                                                  comp_dir, signature,
12898                                                  is_debug_types);
12899             }
12900           else
12901             {
12902               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12903                                                  dwp_file, unit_index,
12904                                                  comp_dir, signature,
12905                                                  is_debug_types);
12906             }
12907           return (struct dwo_unit *) *slot;
12908         }
12909       if (signature_in_table == 0)
12910         return NULL;
12911       hash = (hash + hash2) & mask;
12912     }
12913
12914   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12915            " [in module %s]"),
12916          dwp_file->name);
12917 }
12918
12919 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12920    Open the file specified by FILE_NAME and hand it off to BFD for
12921    preliminary analysis.  Return a newly initialized bfd *, which
12922    includes a canonicalized copy of FILE_NAME.
12923    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12924    SEARCH_CWD is true if the current directory is to be searched.
12925    It will be searched before debug-file-directory.
12926    If successful, the file is added to the bfd include table of the
12927    objfile's bfd (see gdb_bfd_record_inclusion).
12928    If unable to find/open the file, return NULL.
12929    NOTE: This function is derived from symfile_bfd_open.  */
12930
12931 static gdb_bfd_ref_ptr
12932 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12933                     const char *file_name, int is_dwp, int search_cwd)
12934 {
12935   int desc, flags;
12936   char *absolute_name;
12937   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12938      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12939      to debug_file_directory.  */
12940   char *search_path;
12941   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12942
12943   if (search_cwd)
12944     {
12945       if (*debug_file_directory != '\0')
12946         search_path = concat (".", dirname_separator_string,
12947                               debug_file_directory, (char *) NULL);
12948       else
12949         search_path = xstrdup (".");
12950     }
12951   else
12952     search_path = xstrdup (debug_file_directory);
12953
12954   flags = OPF_RETURN_REALPATH;
12955   if (is_dwp)
12956     flags |= OPF_SEARCH_IN_PATH;
12957   desc = openp (search_path, flags, file_name,
12958                 O_RDONLY | O_BINARY, &absolute_name);
12959   xfree (search_path);
12960   if (desc < 0)
12961     return NULL;
12962
12963   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
12964   xfree (absolute_name);
12965   if (sym_bfd == NULL)
12966     return NULL;
12967   bfd_set_cacheable (sym_bfd.get (), 1);
12968
12969   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12970     return NULL;
12971
12972   /* Success.  Record the bfd as having been included by the objfile's bfd.
12973      This is important because things like demangled_names_hash lives in the
12974      objfile's per_bfd space and may have references to things like symbol
12975      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12976   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12977
12978   return sym_bfd;
12979 }
12980
12981 /* Try to open DWO file FILE_NAME.
12982    COMP_DIR is the DW_AT_comp_dir attribute.
12983    The result is the bfd handle of the file.
12984    If there is a problem finding or opening the file, return NULL.
12985    Upon success, the canonicalized path of the file is stored in the bfd,
12986    same as symfile_bfd_open.  */
12987
12988 static gdb_bfd_ref_ptr
12989 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12990                const char *file_name, const char *comp_dir)
12991 {
12992   if (IS_ABSOLUTE_PATH (file_name))
12993     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12994                                0 /*is_dwp*/, 0 /*search_cwd*/);
12995
12996   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12997
12998   if (comp_dir != NULL)
12999     {
13000       char *path_to_try = concat (comp_dir, SLASH_STRING,
13001                                   file_name, (char *) NULL);
13002
13003       /* NOTE: If comp_dir is a relative path, this will also try the
13004          search path, which seems useful.  */
13005       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
13006                                                 path_to_try,
13007                                                 0 /*is_dwp*/,
13008                                                 1 /*search_cwd*/));
13009       xfree (path_to_try);
13010       if (abfd != NULL)
13011         return abfd;
13012     }
13013
13014   /* That didn't work, try debug-file-directory, which, despite its name,
13015      is a list of paths.  */
13016
13017   if (*debug_file_directory == '\0')
13018     return NULL;
13019
13020   return try_open_dwop_file (dwarf2_per_objfile, file_name,
13021                              0 /*is_dwp*/, 1 /*search_cwd*/);
13022 }
13023
13024 /* This function is mapped across the sections and remembers the offset and
13025    size of each of the DWO debugging sections we are interested in.  */
13026
13027 static void
13028 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
13029 {
13030   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
13031   const struct dwop_section_names *names = &dwop_section_names;
13032
13033   if (section_is_p (sectp->name, &names->abbrev_dwo))
13034     {
13035       dwo_sections->abbrev.s.section = sectp;
13036       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
13037     }
13038   else if (section_is_p (sectp->name, &names->info_dwo))
13039     {
13040       dwo_sections->info.s.section = sectp;
13041       dwo_sections->info.size = bfd_get_section_size (sectp);
13042     }
13043   else if (section_is_p (sectp->name, &names->line_dwo))
13044     {
13045       dwo_sections->line.s.section = sectp;
13046       dwo_sections->line.size = bfd_get_section_size (sectp);
13047     }
13048   else if (section_is_p (sectp->name, &names->loc_dwo))
13049     {
13050       dwo_sections->loc.s.section = sectp;
13051       dwo_sections->loc.size = bfd_get_section_size (sectp);
13052     }
13053   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13054     {
13055       dwo_sections->macinfo.s.section = sectp;
13056       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
13057     }
13058   else if (section_is_p (sectp->name, &names->macro_dwo))
13059     {
13060       dwo_sections->macro.s.section = sectp;
13061       dwo_sections->macro.size = bfd_get_section_size (sectp);
13062     }
13063   else if (section_is_p (sectp->name, &names->str_dwo))
13064     {
13065       dwo_sections->str.s.section = sectp;
13066       dwo_sections->str.size = bfd_get_section_size (sectp);
13067     }
13068   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13069     {
13070       dwo_sections->str_offsets.s.section = sectp;
13071       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
13072     }
13073   else if (section_is_p (sectp->name, &names->types_dwo))
13074     {
13075       struct dwarf2_section_info type_section;
13076
13077       memset (&type_section, 0, sizeof (type_section));
13078       type_section.s.section = sectp;
13079       type_section.size = bfd_get_section_size (sectp);
13080       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
13081                      &type_section);
13082     }
13083 }
13084
13085 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
13086    by PER_CU.  This is for the non-DWP case.
13087    The result is NULL if DWO_NAME can't be found.  */
13088
13089 static struct dwo_file *
13090 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
13091                         const char *dwo_name, const char *comp_dir)
13092 {
13093   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
13094   struct objfile *objfile = dwarf2_per_objfile->objfile;
13095   struct dwo_file *dwo_file;
13096   struct cleanup *cleanups;
13097
13098   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
13099   if (dbfd == NULL)
13100     {
13101       if (dwarf_read_debug)
13102         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
13103       return NULL;
13104     }
13105   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
13106   dwo_file->dwo_name = dwo_name;
13107   dwo_file->comp_dir = comp_dir;
13108   dwo_file->dbfd = dbfd.release ();
13109
13110   free_dwo_file_cleanup_data *cleanup_data = XNEW (free_dwo_file_cleanup_data);
13111   cleanup_data->dwo_file = dwo_file;
13112   cleanup_data->dwarf2_per_objfile = dwarf2_per_objfile;
13113
13114   cleanups = make_cleanup (free_dwo_file_cleanup, cleanup_data);
13115
13116   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
13117                          &dwo_file->sections);
13118
13119   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
13120                          dwo_file->cus);
13121
13122   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file,
13123                                  dwo_file->sections.types, dwo_file->tus);
13124
13125   discard_cleanups (cleanups);
13126
13127   if (dwarf_read_debug)
13128     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
13129
13130   return dwo_file;
13131 }
13132
13133 /* This function is mapped across the sections and remembers the offset and
13134    size of each of the DWP debugging sections common to version 1 and 2 that
13135    we are interested in.  */
13136
13137 static void
13138 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
13139                                    void *dwp_file_ptr)
13140 {
13141   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13142   const struct dwop_section_names *names = &dwop_section_names;
13143   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13144
13145   /* Record the ELF section number for later lookup: this is what the
13146      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13147   gdb_assert (elf_section_nr < dwp_file->num_sections);
13148   dwp_file->elf_sections[elf_section_nr] = sectp;
13149
13150   /* Look for specific sections that we need.  */
13151   if (section_is_p (sectp->name, &names->str_dwo))
13152     {
13153       dwp_file->sections.str.s.section = sectp;
13154       dwp_file->sections.str.size = bfd_get_section_size (sectp);
13155     }
13156   else if (section_is_p (sectp->name, &names->cu_index))
13157     {
13158       dwp_file->sections.cu_index.s.section = sectp;
13159       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
13160     }
13161   else if (section_is_p (sectp->name, &names->tu_index))
13162     {
13163       dwp_file->sections.tu_index.s.section = sectp;
13164       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
13165     }
13166 }
13167
13168 /* This function is mapped across the sections and remembers the offset and
13169    size of each of the DWP version 2 debugging sections that we are interested
13170    in.  This is split into a separate function because we don't know if we
13171    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13172
13173 static void
13174 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13175 {
13176   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13177   const struct dwop_section_names *names = &dwop_section_names;
13178   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13179
13180   /* Record the ELF section number for later lookup: this is what the
13181      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13182   gdb_assert (elf_section_nr < dwp_file->num_sections);
13183   dwp_file->elf_sections[elf_section_nr] = sectp;
13184
13185   /* Look for specific sections that we need.  */
13186   if (section_is_p (sectp->name, &names->abbrev_dwo))
13187     {
13188       dwp_file->sections.abbrev.s.section = sectp;
13189       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13190     }
13191   else if (section_is_p (sectp->name, &names->info_dwo))
13192     {
13193       dwp_file->sections.info.s.section = sectp;
13194       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13195     }
13196   else if (section_is_p (sectp->name, &names->line_dwo))
13197     {
13198       dwp_file->sections.line.s.section = sectp;
13199       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13200     }
13201   else if (section_is_p (sectp->name, &names->loc_dwo))
13202     {
13203       dwp_file->sections.loc.s.section = sectp;
13204       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13205     }
13206   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13207     {
13208       dwp_file->sections.macinfo.s.section = sectp;
13209       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13210     }
13211   else if (section_is_p (sectp->name, &names->macro_dwo))
13212     {
13213       dwp_file->sections.macro.s.section = sectp;
13214       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13215     }
13216   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13217     {
13218       dwp_file->sections.str_offsets.s.section = sectp;
13219       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13220     }
13221   else if (section_is_p (sectp->name, &names->types_dwo))
13222     {
13223       dwp_file->sections.types.s.section = sectp;
13224       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13225     }
13226 }
13227
13228 /* Hash function for dwp_file loaded CUs/TUs.  */
13229
13230 static hashval_t
13231 hash_dwp_loaded_cutus (const void *item)
13232 {
13233   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13234
13235   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13236   return dwo_unit->signature;
13237 }
13238
13239 /* Equality function for dwp_file loaded CUs/TUs.  */
13240
13241 static int
13242 eq_dwp_loaded_cutus (const void *a, const void *b)
13243 {
13244   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13245   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13246
13247   return dua->signature == dub->signature;
13248 }
13249
13250 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13251
13252 static htab_t
13253 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13254 {
13255   return htab_create_alloc_ex (3,
13256                                hash_dwp_loaded_cutus,
13257                                eq_dwp_loaded_cutus,
13258                                NULL,
13259                                &objfile->objfile_obstack,
13260                                hashtab_obstack_allocate,
13261                                dummy_obstack_deallocate);
13262 }
13263
13264 /* Try to open DWP file FILE_NAME.
13265    The result is the bfd handle of the file.
13266    If there is a problem finding or opening the file, return NULL.
13267    Upon success, the canonicalized path of the file is stored in the bfd,
13268    same as symfile_bfd_open.  */
13269
13270 static gdb_bfd_ref_ptr
13271 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13272                const char *file_name)
13273 {
13274   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13275                                             1 /*is_dwp*/,
13276                                             1 /*search_cwd*/));
13277   if (abfd != NULL)
13278     return abfd;
13279
13280   /* Work around upstream bug 15652.
13281      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13282      [Whether that's a "bug" is debatable, but it is getting in our way.]
13283      We have no real idea where the dwp file is, because gdb's realpath-ing
13284      of the executable's path may have discarded the needed info.
13285      [IWBN if the dwp file name was recorded in the executable, akin to
13286      .gnu_debuglink, but that doesn't exist yet.]
13287      Strip the directory from FILE_NAME and search again.  */
13288   if (*debug_file_directory != '\0')
13289     {
13290       /* Don't implicitly search the current directory here.
13291          If the user wants to search "." to handle this case,
13292          it must be added to debug-file-directory.  */
13293       return try_open_dwop_file (dwarf2_per_objfile,
13294                                  lbasename (file_name), 1 /*is_dwp*/,
13295                                  0 /*search_cwd*/);
13296     }
13297
13298   return NULL;
13299 }
13300
13301 /* Initialize the use of the DWP file for the current objfile.
13302    By convention the name of the DWP file is ${objfile}.dwp.
13303    The result is NULL if it can't be found.  */
13304
13305 static struct dwp_file *
13306 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13307 {
13308   struct objfile *objfile = dwarf2_per_objfile->objfile;
13309   struct dwp_file *dwp_file;
13310
13311   /* Try to find first .dwp for the binary file before any symbolic links
13312      resolving.  */
13313
13314   /* If the objfile is a debug file, find the name of the real binary
13315      file and get the name of dwp file from there.  */
13316   std::string dwp_name;
13317   if (objfile->separate_debug_objfile_backlink != NULL)
13318     {
13319       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13320       const char *backlink_basename = lbasename (backlink->original_name);
13321
13322       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13323     }
13324   else
13325     dwp_name = objfile->original_name;
13326
13327   dwp_name += ".dwp";
13328
13329   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13330   if (dbfd == NULL
13331       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13332     {
13333       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13334       dwp_name = objfile_name (objfile);
13335       dwp_name += ".dwp";
13336       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13337     }
13338
13339   if (dbfd == NULL)
13340     {
13341       if (dwarf_read_debug)
13342         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13343       return NULL;
13344     }
13345   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
13346   dwp_file->name = bfd_get_filename (dbfd.get ());
13347   dwp_file->dbfd = dbfd.release ();
13348
13349   /* +1: section 0 is unused */
13350   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13351   dwp_file->elf_sections =
13352     OBSTACK_CALLOC (&objfile->objfile_obstack,
13353                     dwp_file->num_sections, asection *);
13354
13355   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
13356                          dwp_file);
13357
13358   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 0);
13359
13360   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file, 1);
13361
13362   /* The DWP file version is stored in the hash table.  Oh well.  */
13363   if (dwp_file->cus && dwp_file->tus
13364       && dwp_file->cus->version != dwp_file->tus->version)
13365     {
13366       /* Technically speaking, we should try to limp along, but this is
13367          pretty bizarre.  We use pulongest here because that's the established
13368          portability solution (e.g, we cannot use %u for uint32_t).  */
13369       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13370                " TU version %s [in DWP file %s]"),
13371              pulongest (dwp_file->cus->version),
13372              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13373     }
13374
13375   if (dwp_file->cus)
13376     dwp_file->version = dwp_file->cus->version;
13377   else if (dwp_file->tus)
13378     dwp_file->version = dwp_file->tus->version;
13379   else
13380     dwp_file->version = 2;
13381
13382   if (dwp_file->version == 2)
13383     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
13384                            dwp_file);
13385
13386   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13387   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13388
13389   if (dwarf_read_debug)
13390     {
13391       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13392       fprintf_unfiltered (gdb_stdlog,
13393                           "    %s CUs, %s TUs\n",
13394                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13395                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13396     }
13397
13398   return dwp_file;
13399 }
13400
13401 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13402
13403 static struct dwp_file *
13404 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13405 {
13406   if (! dwarf2_per_objfile->dwp_checked)
13407     {
13408       dwarf2_per_objfile->dwp_file
13409         = open_and_init_dwp_file (dwarf2_per_objfile);
13410       dwarf2_per_objfile->dwp_checked = 1;
13411     }
13412   return dwarf2_per_objfile->dwp_file;
13413 }
13414
13415 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13416    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13417    or in the DWP file for the objfile, referenced by THIS_UNIT.
13418    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13419    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13420
13421    This is called, for example, when wanting to read a variable with a
13422    complex location.  Therefore we don't want to do file i/o for every call.
13423    Therefore we don't want to look for a DWO file on every call.
13424    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13425    then we check if we've already seen DWO_NAME, and only THEN do we check
13426    for a DWO file.
13427
13428    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13429    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13430
13431 static struct dwo_unit *
13432 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13433                  const char *dwo_name, const char *comp_dir,
13434                  ULONGEST signature, int is_debug_types)
13435 {
13436   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13437   struct objfile *objfile = dwarf2_per_objfile->objfile;
13438   const char *kind = is_debug_types ? "TU" : "CU";
13439   void **dwo_file_slot;
13440   struct dwo_file *dwo_file;
13441   struct dwp_file *dwp_file;
13442
13443   /* First see if there's a DWP file.
13444      If we have a DWP file but didn't find the DWO inside it, don't
13445      look for the original DWO file.  It makes gdb behave differently
13446      depending on whether one is debugging in the build tree.  */
13447
13448   dwp_file = get_dwp_file (dwarf2_per_objfile);
13449   if (dwp_file != NULL)
13450     {
13451       const struct dwp_hash_table *dwp_htab =
13452         is_debug_types ? dwp_file->tus : dwp_file->cus;
13453
13454       if (dwp_htab != NULL)
13455         {
13456           struct dwo_unit *dwo_cutu =
13457             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13458                                     signature, is_debug_types);
13459
13460           if (dwo_cutu != NULL)
13461             {
13462               if (dwarf_read_debug)
13463                 {
13464                   fprintf_unfiltered (gdb_stdlog,
13465                                       "Virtual DWO %s %s found: @%s\n",
13466                                       kind, hex_string (signature),
13467                                       host_address_to_string (dwo_cutu));
13468                 }
13469               return dwo_cutu;
13470             }
13471         }
13472     }
13473   else
13474     {
13475       /* No DWP file, look for the DWO file.  */
13476
13477       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13478                                             dwo_name, comp_dir);
13479       if (*dwo_file_slot == NULL)
13480         {
13481           /* Read in the file and build a table of the CUs/TUs it contains.  */
13482           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13483         }
13484       /* NOTE: This will be NULL if unable to open the file.  */
13485       dwo_file = (struct dwo_file *) *dwo_file_slot;
13486
13487       if (dwo_file != NULL)
13488         {
13489           struct dwo_unit *dwo_cutu = NULL;
13490
13491           if (is_debug_types && dwo_file->tus)
13492             {
13493               struct dwo_unit find_dwo_cutu;
13494
13495               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13496               find_dwo_cutu.signature = signature;
13497               dwo_cutu
13498                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13499             }
13500           else if (!is_debug_types && dwo_file->cus)
13501             {
13502               struct dwo_unit find_dwo_cutu;
13503
13504               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13505               find_dwo_cutu.signature = signature;
13506               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13507                                                        &find_dwo_cutu);
13508             }
13509
13510           if (dwo_cutu != NULL)
13511             {
13512               if (dwarf_read_debug)
13513                 {
13514                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13515                                       kind, dwo_name, hex_string (signature),
13516                                       host_address_to_string (dwo_cutu));
13517                 }
13518               return dwo_cutu;
13519             }
13520         }
13521     }
13522
13523   /* We didn't find it.  This could mean a dwo_id mismatch, or
13524      someone deleted the DWO/DWP file, or the search path isn't set up
13525      correctly to find the file.  */
13526
13527   if (dwarf_read_debug)
13528     {
13529       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13530                           kind, dwo_name, hex_string (signature));
13531     }
13532
13533   /* This is a warning and not a complaint because it can be caused by
13534      pilot error (e.g., user accidentally deleting the DWO).  */
13535   {
13536     /* Print the name of the DWP file if we looked there, helps the user
13537        better diagnose the problem.  */
13538     std::string dwp_text;
13539
13540     if (dwp_file != NULL)
13541       dwp_text = string_printf (" [in DWP file %s]",
13542                                 lbasename (dwp_file->name));
13543
13544     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
13545                " [in module %s]"),
13546              kind, dwo_name, hex_string (signature),
13547              dwp_text.c_str (),
13548              this_unit->is_debug_types ? "TU" : "CU",
13549              to_underlying (this_unit->sect_off), objfile_name (objfile));
13550   }
13551   return NULL;
13552 }
13553
13554 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13555    See lookup_dwo_cutu_unit for details.  */
13556
13557 static struct dwo_unit *
13558 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13559                       const char *dwo_name, const char *comp_dir,
13560                       ULONGEST signature)
13561 {
13562   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13563 }
13564
13565 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13566    See lookup_dwo_cutu_unit for details.  */
13567
13568 static struct dwo_unit *
13569 lookup_dwo_type_unit (struct signatured_type *this_tu,
13570                       const char *dwo_name, const char *comp_dir)
13571 {
13572   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13573 }
13574
13575 /* Traversal function for queue_and_load_all_dwo_tus.  */
13576
13577 static int
13578 queue_and_load_dwo_tu (void **slot, void *info)
13579 {
13580   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13581   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13582   ULONGEST signature = dwo_unit->signature;
13583   struct signatured_type *sig_type =
13584     lookup_dwo_signatured_type (per_cu->cu, signature);
13585
13586   if (sig_type != NULL)
13587     {
13588       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13589
13590       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13591          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13592          while processing PER_CU.  */
13593       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13594         load_full_type_unit (sig_cu);
13595       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13596     }
13597
13598   return 1;
13599 }
13600
13601 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13602    The DWO may have the only definition of the type, though it may not be
13603    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13604    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13605
13606 static void
13607 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13608 {
13609   struct dwo_unit *dwo_unit;
13610   struct dwo_file *dwo_file;
13611
13612   gdb_assert (!per_cu->is_debug_types);
13613   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13614   gdb_assert (per_cu->cu != NULL);
13615
13616   dwo_unit = per_cu->cu->dwo_unit;
13617   gdb_assert (dwo_unit != NULL);
13618
13619   dwo_file = dwo_unit->dwo_file;
13620   if (dwo_file->tus != NULL)
13621     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13622 }
13623
13624 /* Free all resources associated with DWO_FILE.
13625    Close the DWO file and munmap the sections.
13626    All memory should be on the objfile obstack.  */
13627
13628 static void
13629 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
13630 {
13631
13632   /* Note: dbfd is NULL for virtual DWO files.  */
13633   gdb_bfd_unref (dwo_file->dbfd);
13634
13635   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13636 }
13637
13638 /* Wrapper for free_dwo_file for use in cleanups.  */
13639
13640 static void
13641 free_dwo_file_cleanup (void *arg)
13642 {
13643   struct free_dwo_file_cleanup_data *data
13644     = (struct free_dwo_file_cleanup_data *) arg;
13645   struct objfile *objfile = data->dwarf2_per_objfile->objfile;
13646
13647   free_dwo_file (data->dwo_file, objfile);
13648
13649   xfree (data);
13650 }
13651
13652 /* Traversal function for free_dwo_files.  */
13653
13654 static int
13655 free_dwo_file_from_slot (void **slot, void *info)
13656 {
13657   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13658   struct objfile *objfile = (struct objfile *) info;
13659
13660   free_dwo_file (dwo_file, objfile);
13661
13662   return 1;
13663 }
13664
13665 /* Free all resources associated with DWO_FILES.  */
13666
13667 static void
13668 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13669 {
13670   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13671 }
13672 \f
13673 /* Read in various DIEs.  */
13674
13675 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13676    Inherit only the children of the DW_AT_abstract_origin DIE not being
13677    already referenced by DW_AT_abstract_origin from the children of the
13678    current DIE.  */
13679
13680 static void
13681 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13682 {
13683   struct die_info *child_die;
13684   sect_offset *offsetp;
13685   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13686   struct die_info *origin_die;
13687   /* Iterator of the ORIGIN_DIE children.  */
13688   struct die_info *origin_child_die;
13689   struct attribute *attr;
13690   struct dwarf2_cu *origin_cu;
13691   struct pending **origin_previous_list_in_scope;
13692
13693   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13694   if (!attr)
13695     return;
13696
13697   /* Note that following die references may follow to a die in a
13698      different cu.  */
13699
13700   origin_cu = cu;
13701   origin_die = follow_die_ref (die, attr, &origin_cu);
13702
13703   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13704      symbols in.  */
13705   origin_previous_list_in_scope = origin_cu->list_in_scope;
13706   origin_cu->list_in_scope = cu->list_in_scope;
13707
13708   if (die->tag != origin_die->tag
13709       && !(die->tag == DW_TAG_inlined_subroutine
13710            && origin_die->tag == DW_TAG_subprogram))
13711     complaint (&symfile_complaints,
13712                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
13713                to_underlying (die->sect_off),
13714                to_underlying (origin_die->sect_off));
13715
13716   std::vector<sect_offset> offsets;
13717
13718   for (child_die = die->child;
13719        child_die && child_die->tag;
13720        child_die = sibling_die (child_die))
13721     {
13722       struct die_info *child_origin_die;
13723       struct dwarf2_cu *child_origin_cu;
13724
13725       /* We are trying to process concrete instance entries:
13726          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13727          it's not relevant to our analysis here. i.e. detecting DIEs that are
13728          present in the abstract instance but not referenced in the concrete
13729          one.  */
13730       if (child_die->tag == DW_TAG_call_site
13731           || child_die->tag == DW_TAG_GNU_call_site)
13732         continue;
13733
13734       /* For each CHILD_DIE, find the corresponding child of
13735          ORIGIN_DIE.  If there is more than one layer of
13736          DW_AT_abstract_origin, follow them all; there shouldn't be,
13737          but GCC versions at least through 4.4 generate this (GCC PR
13738          40573).  */
13739       child_origin_die = child_die;
13740       child_origin_cu = cu;
13741       while (1)
13742         {
13743           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13744                               child_origin_cu);
13745           if (attr == NULL)
13746             break;
13747           child_origin_die = follow_die_ref (child_origin_die, attr,
13748                                              &child_origin_cu);
13749         }
13750
13751       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13752          counterpart may exist.  */
13753       if (child_origin_die != child_die)
13754         {
13755           if (child_die->tag != child_origin_die->tag
13756               && !(child_die->tag == DW_TAG_inlined_subroutine
13757                    && child_origin_die->tag == DW_TAG_subprogram))
13758             complaint (&symfile_complaints,
13759                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13760                          "different tags"),
13761                        to_underlying (child_die->sect_off),
13762                        to_underlying (child_origin_die->sect_off));
13763           if (child_origin_die->parent != origin_die)
13764             complaint (&symfile_complaints,
13765                        _("Child DIE 0x%x and its abstract origin 0x%x have "
13766                          "different parents"),
13767                        to_underlying (child_die->sect_off),
13768                        to_underlying (child_origin_die->sect_off));
13769           else
13770             offsets.push_back (child_origin_die->sect_off);
13771         }
13772     }
13773   std::sort (offsets.begin (), offsets.end ());
13774   sect_offset *offsets_end = offsets.data () + offsets.size ();
13775   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13776     if (offsetp[-1] == *offsetp)
13777       complaint (&symfile_complaints,
13778                  _("Multiple children of DIE 0x%x refer "
13779                    "to DIE 0x%x as their abstract origin"),
13780                  to_underlying (die->sect_off), to_underlying (*offsetp));
13781
13782   offsetp = offsets.data ();
13783   origin_child_die = origin_die->child;
13784   while (origin_child_die && origin_child_die->tag)
13785     {
13786       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13787       while (offsetp < offsets_end
13788              && *offsetp < origin_child_die->sect_off)
13789         offsetp++;
13790       if (offsetp >= offsets_end
13791           || *offsetp > origin_child_die->sect_off)
13792         {
13793           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13794              Check whether we're already processing ORIGIN_CHILD_DIE.
13795              This can happen with mutually referenced abstract_origins.
13796              PR 16581.  */
13797           if (!origin_child_die->in_process)
13798             process_die (origin_child_die, origin_cu);
13799         }
13800       origin_child_die = sibling_die (origin_child_die);
13801     }
13802   origin_cu->list_in_scope = origin_previous_list_in_scope;
13803 }
13804
13805 static void
13806 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13807 {
13808   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13809   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13810   struct context_stack *newobj;
13811   CORE_ADDR lowpc;
13812   CORE_ADDR highpc;
13813   struct die_info *child_die;
13814   struct attribute *attr, *call_line, *call_file;
13815   const char *name;
13816   CORE_ADDR baseaddr;
13817   struct block *block;
13818   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13819   std::vector<struct symbol *> template_args;
13820   struct template_symbol *templ_func = NULL;
13821
13822   if (inlined_func)
13823     {
13824       /* If we do not have call site information, we can't show the
13825          caller of this inlined function.  That's too confusing, so
13826          only use the scope for local variables.  */
13827       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13828       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13829       if (call_line == NULL || call_file == NULL)
13830         {
13831           read_lexical_block_scope (die, cu);
13832           return;
13833         }
13834     }
13835
13836   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13837
13838   name = dwarf2_name (die, cu);
13839
13840   /* Ignore functions with missing or empty names.  These are actually
13841      illegal according to the DWARF standard.  */
13842   if (name == NULL)
13843     {
13844       complaint (&symfile_complaints,
13845                  _("missing name for subprogram DIE at %d"),
13846                  to_underlying (die->sect_off));
13847       return;
13848     }
13849
13850   /* Ignore functions with missing or invalid low and high pc attributes.  */
13851   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13852       <= PC_BOUNDS_INVALID)
13853     {
13854       attr = dwarf2_attr (die, DW_AT_external, cu);
13855       if (!attr || !DW_UNSND (attr))
13856         complaint (&symfile_complaints,
13857                    _("cannot get low and high bounds "
13858                      "for subprogram DIE at %d"),
13859                    to_underlying (die->sect_off));
13860       return;
13861     }
13862
13863   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13864   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13865
13866   /* If we have any template arguments, then we must allocate a
13867      different sort of symbol.  */
13868   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13869     {
13870       if (child_die->tag == DW_TAG_template_type_param
13871           || child_die->tag == DW_TAG_template_value_param)
13872         {
13873           templ_func = allocate_template_symbol (objfile);
13874           templ_func->subclass = SYMBOL_TEMPLATE;
13875           break;
13876         }
13877     }
13878
13879   newobj = push_context (0, lowpc);
13880   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13881                              (struct symbol *) templ_func);
13882
13883   /* If there is a location expression for DW_AT_frame_base, record
13884      it.  */
13885   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13886   if (attr)
13887     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13888
13889   /* If there is a location for the static link, record it.  */
13890   newobj->static_link = NULL;
13891   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13892   if (attr)
13893     {
13894       newobj->static_link
13895         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13896       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13897     }
13898
13899   cu->list_in_scope = &local_symbols;
13900
13901   if (die->child != NULL)
13902     {
13903       child_die = die->child;
13904       while (child_die && child_die->tag)
13905         {
13906           if (child_die->tag == DW_TAG_template_type_param
13907               || child_die->tag == DW_TAG_template_value_param)
13908             {
13909               struct symbol *arg = new_symbol (child_die, NULL, cu);
13910
13911               if (arg != NULL)
13912                 template_args.push_back (arg);
13913             }
13914           else
13915             process_die (child_die, cu);
13916           child_die = sibling_die (child_die);
13917         }
13918     }
13919
13920   inherit_abstract_dies (die, cu);
13921
13922   /* If we have a DW_AT_specification, we might need to import using
13923      directives from the context of the specification DIE.  See the
13924      comment in determine_prefix.  */
13925   if (cu->language == language_cplus
13926       && dwarf2_attr (die, DW_AT_specification, cu))
13927     {
13928       struct dwarf2_cu *spec_cu = cu;
13929       struct die_info *spec_die = die_specification (die, &spec_cu);
13930
13931       while (spec_die)
13932         {
13933           child_die = spec_die->child;
13934           while (child_die && child_die->tag)
13935             {
13936               if (child_die->tag == DW_TAG_imported_module)
13937                 process_die (child_die, spec_cu);
13938               child_die = sibling_die (child_die);
13939             }
13940
13941           /* In some cases, GCC generates specification DIEs that
13942              themselves contain DW_AT_specification attributes.  */
13943           spec_die = die_specification (spec_die, &spec_cu);
13944         }
13945     }
13946
13947   newobj = pop_context ();
13948   /* Make a block for the local symbols within.  */
13949   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13950                         newobj->static_link, lowpc, highpc);
13951
13952   /* For C++, set the block's scope.  */
13953   if ((cu->language == language_cplus
13954        || cu->language == language_fortran
13955        || cu->language == language_d
13956        || cu->language == language_rust)
13957       && cu->processing_has_namespace_info)
13958     block_set_scope (block, determine_prefix (die, cu),
13959                      &objfile->objfile_obstack);
13960
13961   /* If we have address ranges, record them.  */
13962   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13963
13964   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13965
13966   /* Attach template arguments to function.  */
13967   if (!template_args.empty ())
13968     {
13969       gdb_assert (templ_func != NULL);
13970
13971       templ_func->n_template_arguments = template_args.size ();
13972       templ_func->template_arguments
13973         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13974                      templ_func->n_template_arguments);
13975       memcpy (templ_func->template_arguments,
13976               template_args.data (),
13977               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13978     }
13979
13980   /* In C++, we can have functions nested inside functions (e.g., when
13981      a function declares a class that has methods).  This means that
13982      when we finish processing a function scope, we may need to go
13983      back to building a containing block's symbol lists.  */
13984   local_symbols = newobj->locals;
13985   local_using_directives = newobj->local_using_directives;
13986
13987   /* If we've finished processing a top-level function, subsequent
13988      symbols go in the file symbol list.  */
13989   if (outermost_context_p ())
13990     cu->list_in_scope = &file_symbols;
13991 }
13992
13993 /* Process all the DIES contained within a lexical block scope.  Start
13994    a new scope, process the dies, and then close the scope.  */
13995
13996 static void
13997 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13998 {
13999   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14000   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14001   struct context_stack *newobj;
14002   CORE_ADDR lowpc, highpc;
14003   struct die_info *child_die;
14004   CORE_ADDR baseaddr;
14005
14006   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14007
14008   /* Ignore blocks with missing or invalid low and high pc attributes.  */
14009   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
14010      as multiple lexical blocks?  Handling children in a sane way would
14011      be nasty.  Might be easier to properly extend generic blocks to
14012      describe ranges.  */
14013   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
14014     {
14015     case PC_BOUNDS_NOT_PRESENT:
14016       /* DW_TAG_lexical_block has no attributes, process its children as if
14017          there was no wrapping by that DW_TAG_lexical_block.
14018          GCC does no longer produces such DWARF since GCC r224161.  */
14019       for (child_die = die->child;
14020            child_die != NULL && child_die->tag;
14021            child_die = sibling_die (child_die))
14022         process_die (child_die, cu);
14023       return;
14024     case PC_BOUNDS_INVALID:
14025       return;
14026     }
14027   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14028   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
14029
14030   push_context (0, lowpc);
14031   if (die->child != NULL)
14032     {
14033       child_die = die->child;
14034       while (child_die && child_die->tag)
14035         {
14036           process_die (child_die, cu);
14037           child_die = sibling_die (child_die);
14038         }
14039     }
14040   inherit_abstract_dies (die, cu);
14041   newobj = pop_context ();
14042
14043   if (local_symbols != NULL || local_using_directives != NULL)
14044     {
14045       struct block *block
14046         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
14047                         newobj->start_addr, highpc);
14048
14049       /* Note that recording ranges after traversing children, as we
14050          do here, means that recording a parent's ranges entails
14051          walking across all its children's ranges as they appear in
14052          the address map, which is quadratic behavior.
14053
14054          It would be nicer to record the parent's ranges before
14055          traversing its children, simply overriding whatever you find
14056          there.  But since we don't even decide whether to create a
14057          block until after we've traversed its children, that's hard
14058          to do.  */
14059       dwarf2_record_block_ranges (die, block, baseaddr, cu);
14060     }
14061   local_symbols = newobj->locals;
14062   local_using_directives = newobj->local_using_directives;
14063 }
14064
14065 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
14066
14067 static void
14068 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
14069 {
14070   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14071   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14072   CORE_ADDR pc, baseaddr;
14073   struct attribute *attr;
14074   struct call_site *call_site, call_site_local;
14075   void **slot;
14076   int nparams;
14077   struct die_info *child_die;
14078
14079   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14080
14081   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
14082   if (attr == NULL)
14083     {
14084       /* This was a pre-DWARF-5 GNU extension alias
14085          for DW_AT_call_return_pc.  */
14086       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14087     }
14088   if (!attr)
14089     {
14090       complaint (&symfile_complaints,
14091                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
14092                    "DIE 0x%x [in module %s]"),
14093                  to_underlying (die->sect_off), objfile_name (objfile));
14094       return;
14095     }
14096   pc = attr_value_as_address (attr) + baseaddr;
14097   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
14098
14099   if (cu->call_site_htab == NULL)
14100     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
14101                                                NULL, &objfile->objfile_obstack,
14102                                                hashtab_obstack_allocate, NULL);
14103   call_site_local.pc = pc;
14104   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
14105   if (*slot != NULL)
14106     {
14107       complaint (&symfile_complaints,
14108                  _("Duplicate PC %s for DW_TAG_call_site "
14109                    "DIE 0x%x [in module %s]"),
14110                  paddress (gdbarch, pc), to_underlying (die->sect_off),
14111                  objfile_name (objfile));
14112       return;
14113     }
14114
14115   /* Count parameters at the caller.  */
14116
14117   nparams = 0;
14118   for (child_die = die->child; child_die && child_die->tag;
14119        child_die = sibling_die (child_die))
14120     {
14121       if (child_die->tag != DW_TAG_call_site_parameter
14122           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14123         {
14124           complaint (&symfile_complaints,
14125                      _("Tag %d is not DW_TAG_call_site_parameter in "
14126                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14127                      child_die->tag, to_underlying (child_die->sect_off),
14128                      objfile_name (objfile));
14129           continue;
14130         }
14131
14132       nparams++;
14133     }
14134
14135   call_site
14136     = ((struct call_site *)
14137        obstack_alloc (&objfile->objfile_obstack,
14138                       sizeof (*call_site)
14139                       + (sizeof (*call_site->parameter) * (nparams - 1))));
14140   *slot = call_site;
14141   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
14142   call_site->pc = pc;
14143
14144   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
14145       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
14146     {
14147       struct die_info *func_die;
14148
14149       /* Skip also over DW_TAG_inlined_subroutine.  */
14150       for (func_die = die->parent;
14151            func_die && func_die->tag != DW_TAG_subprogram
14152            && func_die->tag != DW_TAG_subroutine_type;
14153            func_die = func_die->parent);
14154
14155       /* DW_AT_call_all_calls is a superset
14156          of DW_AT_call_all_tail_calls.  */
14157       if (func_die
14158           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
14159           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
14160           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
14161           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
14162         {
14163           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
14164              not complete.  But keep CALL_SITE for look ups via call_site_htab,
14165              both the initial caller containing the real return address PC and
14166              the final callee containing the current PC of a chain of tail
14167              calls do not need to have the tail call list complete.  But any
14168              function candidate for a virtual tail call frame searched via
14169              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
14170              determined unambiguously.  */
14171         }
14172       else
14173         {
14174           struct type *func_type = NULL;
14175
14176           if (func_die)
14177             func_type = get_die_type (func_die, cu);
14178           if (func_type != NULL)
14179             {
14180               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
14181
14182               /* Enlist this call site to the function.  */
14183               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
14184               TYPE_TAIL_CALL_LIST (func_type) = call_site;
14185             }
14186           else
14187             complaint (&symfile_complaints,
14188                        _("Cannot find function owning DW_TAG_call_site "
14189                          "DIE 0x%x [in module %s]"),
14190                        to_underlying (die->sect_off), objfile_name (objfile));
14191         }
14192     }
14193
14194   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14195   if (attr == NULL)
14196     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14197   if (attr == NULL)
14198     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14199   if (attr == NULL)
14200     {
14201       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14202       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14203     }
14204   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14205   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14206     /* Keep NULL DWARF_BLOCK.  */;
14207   else if (attr_form_is_block (attr))
14208     {
14209       struct dwarf2_locexpr_baton *dlbaton;
14210
14211       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14212       dlbaton->data = DW_BLOCK (attr)->data;
14213       dlbaton->size = DW_BLOCK (attr)->size;
14214       dlbaton->per_cu = cu->per_cu;
14215
14216       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14217     }
14218   else if (attr_form_is_ref (attr))
14219     {
14220       struct dwarf2_cu *target_cu = cu;
14221       struct die_info *target_die;
14222
14223       target_die = follow_die_ref (die, attr, &target_cu);
14224       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14225       if (die_is_declaration (target_die, target_cu))
14226         {
14227           const char *target_physname;
14228
14229           /* Prefer the mangled name; otherwise compute the demangled one.  */
14230           target_physname = dw2_linkage_name (target_die, target_cu);
14231           if (target_physname == NULL)
14232             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14233           if (target_physname == NULL)
14234             complaint (&symfile_complaints,
14235                        _("DW_AT_call_target target DIE has invalid "
14236                          "physname, for referencing DIE 0x%x [in module %s]"),
14237                        to_underlying (die->sect_off), objfile_name (objfile));
14238           else
14239             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14240         }
14241       else
14242         {
14243           CORE_ADDR lowpc;
14244
14245           /* DW_AT_entry_pc should be preferred.  */
14246           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14247               <= PC_BOUNDS_INVALID)
14248             complaint (&symfile_complaints,
14249                        _("DW_AT_call_target target DIE has invalid "
14250                          "low pc, for referencing DIE 0x%x [in module %s]"),
14251                        to_underlying (die->sect_off), objfile_name (objfile));
14252           else
14253             {
14254               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14255               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14256             }
14257         }
14258     }
14259   else
14260     complaint (&symfile_complaints,
14261                _("DW_TAG_call_site DW_AT_call_target is neither "
14262                  "block nor reference, for DIE 0x%x [in module %s]"),
14263                to_underlying (die->sect_off), objfile_name (objfile));
14264
14265   call_site->per_cu = cu->per_cu;
14266
14267   for (child_die = die->child;
14268        child_die && child_die->tag;
14269        child_die = sibling_die (child_die))
14270     {
14271       struct call_site_parameter *parameter;
14272       struct attribute *loc, *origin;
14273
14274       if (child_die->tag != DW_TAG_call_site_parameter
14275           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14276         {
14277           /* Already printed the complaint above.  */
14278           continue;
14279         }
14280
14281       gdb_assert (call_site->parameter_count < nparams);
14282       parameter = &call_site->parameter[call_site->parameter_count];
14283
14284       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14285          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14286          register is contained in DW_AT_call_value.  */
14287
14288       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14289       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14290       if (origin == NULL)
14291         {
14292           /* This was a pre-DWARF-5 GNU extension alias
14293              for DW_AT_call_parameter.  */
14294           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14295         }
14296       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14297         {
14298           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14299
14300           sect_offset sect_off
14301             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14302           if (!offset_in_cu_p (&cu->header, sect_off))
14303             {
14304               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14305                  binding can be done only inside one CU.  Such referenced DIE
14306                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14307               complaint (&symfile_complaints,
14308                          _("DW_AT_call_parameter offset is not in CU for "
14309                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14310                          to_underlying (child_die->sect_off),
14311                          objfile_name (objfile));
14312               continue;
14313             }
14314           parameter->u.param_cu_off
14315             = (cu_offset) (sect_off - cu->header.sect_off);
14316         }
14317       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14318         {
14319           complaint (&symfile_complaints,
14320                      _("No DW_FORM_block* DW_AT_location for "
14321                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14322                      to_underlying (child_die->sect_off), objfile_name (objfile));
14323           continue;
14324         }
14325       else
14326         {
14327           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14328             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14329           if (parameter->u.dwarf_reg != -1)
14330             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14331           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14332                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14333                                              &parameter->u.fb_offset))
14334             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14335           else
14336             {
14337               complaint (&symfile_complaints,
14338                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
14339                            "for DW_FORM_block* DW_AT_location is supported for "
14340                            "DW_TAG_call_site child DIE 0x%x "
14341                            "[in module %s]"),
14342                          to_underlying (child_die->sect_off),
14343                          objfile_name (objfile));
14344               continue;
14345             }
14346         }
14347
14348       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14349       if (attr == NULL)
14350         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14351       if (!attr_form_is_block (attr))
14352         {
14353           complaint (&symfile_complaints,
14354                      _("No DW_FORM_block* DW_AT_call_value for "
14355                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14356                      to_underlying (child_die->sect_off),
14357                      objfile_name (objfile));
14358           continue;
14359         }
14360       parameter->value = DW_BLOCK (attr)->data;
14361       parameter->value_size = DW_BLOCK (attr)->size;
14362
14363       /* Parameters are not pre-cleared by memset above.  */
14364       parameter->data_value = NULL;
14365       parameter->data_value_size = 0;
14366       call_site->parameter_count++;
14367
14368       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14369       if (attr == NULL)
14370         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14371       if (attr)
14372         {
14373           if (!attr_form_is_block (attr))
14374             complaint (&symfile_complaints,
14375                        _("No DW_FORM_block* DW_AT_call_data_value for "
14376                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
14377                        to_underlying (child_die->sect_off),
14378                        objfile_name (objfile));
14379           else
14380             {
14381               parameter->data_value = DW_BLOCK (attr)->data;
14382               parameter->data_value_size = DW_BLOCK (attr)->size;
14383             }
14384         }
14385     }
14386 }
14387
14388 /* Helper function for read_variable.  If DIE represents a virtual
14389    table, then return the type of the concrete object that is
14390    associated with the virtual table.  Otherwise, return NULL.  */
14391
14392 static struct type *
14393 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14394 {
14395   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14396   if (attr == NULL)
14397     return NULL;
14398
14399   /* Find the type DIE.  */
14400   struct die_info *type_die = NULL;
14401   struct dwarf2_cu *type_cu = cu;
14402
14403   if (attr_form_is_ref (attr))
14404     type_die = follow_die_ref (die, attr, &type_cu);
14405   if (type_die == NULL)
14406     return NULL;
14407
14408   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14409     return NULL;
14410   return die_containing_type (type_die, type_cu);
14411 }
14412
14413 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14414
14415 static void
14416 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14417 {
14418   struct rust_vtable_symbol *storage = NULL;
14419
14420   if (cu->language == language_rust)
14421     {
14422       struct type *containing_type = rust_containing_type (die, cu);
14423
14424       if (containing_type != NULL)
14425         {
14426           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14427
14428           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14429                                     struct rust_vtable_symbol);
14430           initialize_objfile_symbol (storage);
14431           storage->concrete_type = containing_type;
14432           storage->subclass = SYMBOL_RUST_VTABLE;
14433         }
14434     }
14435
14436   new_symbol (die, NULL, cu, storage);
14437 }
14438
14439 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14440    reading .debug_rnglists.
14441    Callback's type should be:
14442     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14443    Return true if the attributes are present and valid, otherwise,
14444    return false.  */
14445
14446 template <typename Callback>
14447 static bool
14448 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14449                          Callback &&callback)
14450 {
14451   struct dwarf2_per_objfile *dwarf2_per_objfile
14452     = cu->per_cu->dwarf2_per_objfile;
14453   struct objfile *objfile = dwarf2_per_objfile->objfile;
14454   bfd *obfd = objfile->obfd;
14455   /* Base address selection entry.  */
14456   CORE_ADDR base;
14457   int found_base;
14458   const gdb_byte *buffer;
14459   CORE_ADDR baseaddr;
14460   bool overflow = false;
14461
14462   found_base = cu->base_known;
14463   base = cu->base_address;
14464
14465   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14466   if (offset >= dwarf2_per_objfile->rnglists.size)
14467     {
14468       complaint (&symfile_complaints,
14469                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14470                  offset);
14471       return false;
14472     }
14473   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14474
14475   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14476
14477   while (1)
14478     {
14479       /* Initialize it due to a false compiler warning.  */
14480       CORE_ADDR range_beginning = 0, range_end = 0;
14481       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14482                                  + dwarf2_per_objfile->rnglists.size);
14483       unsigned int bytes_read;
14484
14485       if (buffer == buf_end)
14486         {
14487           overflow = true;
14488           break;
14489         }
14490       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14491       switch (rlet)
14492         {
14493         case DW_RLE_end_of_list:
14494           break;
14495         case DW_RLE_base_address:
14496           if (buffer + cu->header.addr_size > buf_end)
14497             {
14498               overflow = true;
14499               break;
14500             }
14501           base = read_address (obfd, buffer, cu, &bytes_read);
14502           found_base = 1;
14503           buffer += bytes_read;
14504           break;
14505         case DW_RLE_start_length:
14506           if (buffer + cu->header.addr_size > buf_end)
14507             {
14508               overflow = true;
14509               break;
14510             }
14511           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14512           buffer += bytes_read;
14513           range_end = (range_beginning
14514                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14515           buffer += bytes_read;
14516           if (buffer > buf_end)
14517             {
14518               overflow = true;
14519               break;
14520             }
14521           break;
14522         case DW_RLE_offset_pair:
14523           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14524           buffer += bytes_read;
14525           if (buffer > buf_end)
14526             {
14527               overflow = true;
14528               break;
14529             }
14530           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14531           buffer += bytes_read;
14532           if (buffer > buf_end)
14533             {
14534               overflow = true;
14535               break;
14536             }
14537           break;
14538         case DW_RLE_start_end:
14539           if (buffer + 2 * cu->header.addr_size > buf_end)
14540             {
14541               overflow = true;
14542               break;
14543             }
14544           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14545           buffer += bytes_read;
14546           range_end = read_address (obfd, buffer, cu, &bytes_read);
14547           buffer += bytes_read;
14548           break;
14549         default:
14550           complaint (&symfile_complaints,
14551                      _("Invalid .debug_rnglists data (no base address)"));
14552           return false;
14553         }
14554       if (rlet == DW_RLE_end_of_list || overflow)
14555         break;
14556       if (rlet == DW_RLE_base_address)
14557         continue;
14558
14559       if (!found_base)
14560         {
14561           /* We have no valid base address for the ranges
14562              data.  */
14563           complaint (&symfile_complaints,
14564                      _("Invalid .debug_rnglists data (no base address)"));
14565           return false;
14566         }
14567
14568       if (range_beginning > range_end)
14569         {
14570           /* Inverted range entries are invalid.  */
14571           complaint (&symfile_complaints,
14572                      _("Invalid .debug_rnglists data (inverted range)"));
14573           return false;
14574         }
14575
14576       /* Empty range entries have no effect.  */
14577       if (range_beginning == range_end)
14578         continue;
14579
14580       range_beginning += base;
14581       range_end += base;
14582
14583       /* A not-uncommon case of bad debug info.
14584          Don't pollute the addrmap with bad data.  */
14585       if (range_beginning + baseaddr == 0
14586           && !dwarf2_per_objfile->has_section_at_zero)
14587         {
14588           complaint (&symfile_complaints,
14589                      _(".debug_rnglists entry has start address of zero"
14590                        " [in module %s]"), objfile_name (objfile));
14591           continue;
14592         }
14593
14594       callback (range_beginning, range_end);
14595     }
14596
14597   if (overflow)
14598     {
14599       complaint (&symfile_complaints,
14600                  _("Offset %d is not terminated "
14601                    "for DW_AT_ranges attribute"),
14602                  offset);
14603       return false;
14604     }
14605
14606   return true;
14607 }
14608
14609 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14610    Callback's type should be:
14611     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14612    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14613
14614 template <typename Callback>
14615 static int
14616 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14617                        Callback &&callback)
14618 {
14619   struct dwarf2_per_objfile *dwarf2_per_objfile
14620       = cu->per_cu->dwarf2_per_objfile;
14621   struct objfile *objfile = dwarf2_per_objfile->objfile;
14622   struct comp_unit_head *cu_header = &cu->header;
14623   bfd *obfd = objfile->obfd;
14624   unsigned int addr_size = cu_header->addr_size;
14625   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14626   /* Base address selection entry.  */
14627   CORE_ADDR base;
14628   int found_base;
14629   unsigned int dummy;
14630   const gdb_byte *buffer;
14631   CORE_ADDR baseaddr;
14632
14633   if (cu_header->version >= 5)
14634     return dwarf2_rnglists_process (offset, cu, callback);
14635
14636   found_base = cu->base_known;
14637   base = cu->base_address;
14638
14639   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14640   if (offset >= dwarf2_per_objfile->ranges.size)
14641     {
14642       complaint (&symfile_complaints,
14643                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
14644                  offset);
14645       return 0;
14646     }
14647   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14648
14649   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14650
14651   while (1)
14652     {
14653       CORE_ADDR range_beginning, range_end;
14654
14655       range_beginning = read_address (obfd, buffer, cu, &dummy);
14656       buffer += addr_size;
14657       range_end = read_address (obfd, buffer, cu, &dummy);
14658       buffer += addr_size;
14659       offset += 2 * addr_size;
14660
14661       /* An end of list marker is a pair of zero addresses.  */
14662       if (range_beginning == 0 && range_end == 0)
14663         /* Found the end of list entry.  */
14664         break;
14665
14666       /* Each base address selection entry is a pair of 2 values.
14667          The first is the largest possible address, the second is
14668          the base address.  Check for a base address here.  */
14669       if ((range_beginning & mask) == mask)
14670         {
14671           /* If we found the largest possible address, then we already
14672              have the base address in range_end.  */
14673           base = range_end;
14674           found_base = 1;
14675           continue;
14676         }
14677
14678       if (!found_base)
14679         {
14680           /* We have no valid base address for the ranges
14681              data.  */
14682           complaint (&symfile_complaints,
14683                      _("Invalid .debug_ranges data (no base address)"));
14684           return 0;
14685         }
14686
14687       if (range_beginning > range_end)
14688         {
14689           /* Inverted range entries are invalid.  */
14690           complaint (&symfile_complaints,
14691                      _("Invalid .debug_ranges data (inverted range)"));
14692           return 0;
14693         }
14694
14695       /* Empty range entries have no effect.  */
14696       if (range_beginning == range_end)
14697         continue;
14698
14699       range_beginning += base;
14700       range_end += base;
14701
14702       /* A not-uncommon case of bad debug info.
14703          Don't pollute the addrmap with bad data.  */
14704       if (range_beginning + baseaddr == 0
14705           && !dwarf2_per_objfile->has_section_at_zero)
14706         {
14707           complaint (&symfile_complaints,
14708                      _(".debug_ranges entry has start address of zero"
14709                        " [in module %s]"), objfile_name (objfile));
14710           continue;
14711         }
14712
14713       callback (range_beginning, range_end);
14714     }
14715
14716   return 1;
14717 }
14718
14719 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14720    Return 1 if the attributes are present and valid, otherwise, return 0.
14721    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14722
14723 static int
14724 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14725                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14726                     struct partial_symtab *ranges_pst)
14727 {
14728   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14729   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14730   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14731                                        SECT_OFF_TEXT (objfile));
14732   int low_set = 0;
14733   CORE_ADDR low = 0;
14734   CORE_ADDR high = 0;
14735   int retval;
14736
14737   retval = dwarf2_ranges_process (offset, cu,
14738     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14739     {
14740       if (ranges_pst != NULL)
14741         {
14742           CORE_ADDR lowpc;
14743           CORE_ADDR highpc;
14744
14745           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14746                                               range_beginning + baseaddr);
14747           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14748                                                range_end + baseaddr);
14749           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14750                              ranges_pst);
14751         }
14752
14753       /* FIXME: This is recording everything as a low-high
14754          segment of consecutive addresses.  We should have a
14755          data structure for discontiguous block ranges
14756          instead.  */
14757       if (! low_set)
14758         {
14759           low = range_beginning;
14760           high = range_end;
14761           low_set = 1;
14762         }
14763       else
14764         {
14765           if (range_beginning < low)
14766             low = range_beginning;
14767           if (range_end > high)
14768             high = range_end;
14769         }
14770     });
14771   if (!retval)
14772     return 0;
14773
14774   if (! low_set)
14775     /* If the first entry is an end-of-list marker, the range
14776        describes an empty scope, i.e. no instructions.  */
14777     return 0;
14778
14779   if (low_return)
14780     *low_return = low;
14781   if (high_return)
14782     *high_return = high;
14783   return 1;
14784 }
14785
14786 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14787    definition for the return value.  *LOWPC and *HIGHPC are set iff
14788    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14789
14790 static enum pc_bounds_kind
14791 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14792                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14793                       struct partial_symtab *pst)
14794 {
14795   struct dwarf2_per_objfile *dwarf2_per_objfile
14796     = cu->per_cu->dwarf2_per_objfile;
14797   struct attribute *attr;
14798   struct attribute *attr_high;
14799   CORE_ADDR low = 0;
14800   CORE_ADDR high = 0;
14801   enum pc_bounds_kind ret;
14802
14803   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14804   if (attr_high)
14805     {
14806       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14807       if (attr)
14808         {
14809           low = attr_value_as_address (attr);
14810           high = attr_value_as_address (attr_high);
14811           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14812             high += low;
14813         }
14814       else
14815         /* Found high w/o low attribute.  */
14816         return PC_BOUNDS_INVALID;
14817
14818       /* Found consecutive range of addresses.  */
14819       ret = PC_BOUNDS_HIGH_LOW;
14820     }
14821   else
14822     {
14823       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14824       if (attr != NULL)
14825         {
14826           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14827              We take advantage of the fact that DW_AT_ranges does not appear
14828              in DW_TAG_compile_unit of DWO files.  */
14829           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14830           unsigned int ranges_offset = (DW_UNSND (attr)
14831                                         + (need_ranges_base
14832                                            ? cu->ranges_base
14833                                            : 0));
14834
14835           /* Value of the DW_AT_ranges attribute is the offset in the
14836              .debug_ranges section.  */
14837           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14838             return PC_BOUNDS_INVALID;
14839           /* Found discontinuous range of addresses.  */
14840           ret = PC_BOUNDS_RANGES;
14841         }
14842       else
14843         return PC_BOUNDS_NOT_PRESENT;
14844     }
14845
14846   /* read_partial_die has also the strict LOW < HIGH requirement.  */
14847   if (high <= low)
14848     return PC_BOUNDS_INVALID;
14849
14850   /* When using the GNU linker, .gnu.linkonce. sections are used to
14851      eliminate duplicate copies of functions and vtables and such.
14852      The linker will arbitrarily choose one and discard the others.
14853      The AT_*_pc values for such functions refer to local labels in
14854      these sections.  If the section from that file was discarded, the
14855      labels are not in the output, so the relocs get a value of 0.
14856      If this is a discarded function, mark the pc bounds as invalid,
14857      so that GDB will ignore it.  */
14858   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14859     return PC_BOUNDS_INVALID;
14860
14861   *lowpc = low;
14862   if (highpc)
14863     *highpc = high;
14864   return ret;
14865 }
14866
14867 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14868    its low and high PC addresses.  Do nothing if these addresses could not
14869    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14870    and HIGHPC to the high address if greater than HIGHPC.  */
14871
14872 static void
14873 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14874                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14875                                  struct dwarf2_cu *cu)
14876 {
14877   CORE_ADDR low, high;
14878   struct die_info *child = die->child;
14879
14880   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14881     {
14882       *lowpc = std::min (*lowpc, low);
14883       *highpc = std::max (*highpc, high);
14884     }
14885
14886   /* If the language does not allow nested subprograms (either inside
14887      subprograms or lexical blocks), we're done.  */
14888   if (cu->language != language_ada)
14889     return;
14890
14891   /* Check all the children of the given DIE.  If it contains nested
14892      subprograms, then check their pc bounds.  Likewise, we need to
14893      check lexical blocks as well, as they may also contain subprogram
14894      definitions.  */
14895   while (child && child->tag)
14896     {
14897       if (child->tag == DW_TAG_subprogram
14898           || child->tag == DW_TAG_lexical_block)
14899         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14900       child = sibling_die (child);
14901     }
14902 }
14903
14904 /* Get the low and high pc's represented by the scope DIE, and store
14905    them in *LOWPC and *HIGHPC.  If the correct values can't be
14906    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14907
14908 static void
14909 get_scope_pc_bounds (struct die_info *die,
14910                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14911                      struct dwarf2_cu *cu)
14912 {
14913   CORE_ADDR best_low = (CORE_ADDR) -1;
14914   CORE_ADDR best_high = (CORE_ADDR) 0;
14915   CORE_ADDR current_low, current_high;
14916
14917   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14918       >= PC_BOUNDS_RANGES)
14919     {
14920       best_low = current_low;
14921       best_high = current_high;
14922     }
14923   else
14924     {
14925       struct die_info *child = die->child;
14926
14927       while (child && child->tag)
14928         {
14929           switch (child->tag) {
14930           case DW_TAG_subprogram:
14931             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14932             break;
14933           case DW_TAG_namespace:
14934           case DW_TAG_module:
14935             /* FIXME: carlton/2004-01-16: Should we do this for
14936                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14937                that current GCC's always emit the DIEs corresponding
14938                to definitions of methods of classes as children of a
14939                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14940                the DIEs giving the declarations, which could be
14941                anywhere).  But I don't see any reason why the
14942                standards says that they have to be there.  */
14943             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14944
14945             if (current_low != ((CORE_ADDR) -1))
14946               {
14947                 best_low = std::min (best_low, current_low);
14948                 best_high = std::max (best_high, current_high);
14949               }
14950             break;
14951           default:
14952             /* Ignore.  */
14953             break;
14954           }
14955
14956           child = sibling_die (child);
14957         }
14958     }
14959
14960   *lowpc = best_low;
14961   *highpc = best_high;
14962 }
14963
14964 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14965    in DIE.  */
14966
14967 static void
14968 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14969                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14970 {
14971   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14972   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14973   struct attribute *attr;
14974   struct attribute *attr_high;
14975
14976   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14977   if (attr_high)
14978     {
14979       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14980       if (attr)
14981         {
14982           CORE_ADDR low = attr_value_as_address (attr);
14983           CORE_ADDR high = attr_value_as_address (attr_high);
14984
14985           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14986             high += low;
14987
14988           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14989           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14990           record_block_range (block, low, high - 1);
14991         }
14992     }
14993
14994   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14995   if (attr)
14996     {
14997       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14998          We take advantage of the fact that DW_AT_ranges does not appear
14999          in DW_TAG_compile_unit of DWO files.  */
15000       int need_ranges_base = die->tag != DW_TAG_compile_unit;
15001
15002       /* The value of the DW_AT_ranges attribute is the offset of the
15003          address range list in the .debug_ranges section.  */
15004       unsigned long offset = (DW_UNSND (attr)
15005                               + (need_ranges_base ? cu->ranges_base : 0));
15006       const gdb_byte *buffer;
15007
15008       /* For some target architectures, but not others, the
15009          read_address function sign-extends the addresses it returns.
15010          To recognize base address selection entries, we need a
15011          mask.  */
15012       unsigned int addr_size = cu->header.addr_size;
15013       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
15014
15015       /* The base address, to which the next pair is relative.  Note
15016          that this 'base' is a DWARF concept: most entries in a range
15017          list are relative, to reduce the number of relocs against the
15018          debugging information.  This is separate from this function's
15019          'baseaddr' argument, which GDB uses to relocate debugging
15020          information from a shared library based on the address at
15021          which the library was loaded.  */
15022       CORE_ADDR base = cu->base_address;
15023       int base_known = cu->base_known;
15024
15025       dwarf2_ranges_process (offset, cu,
15026         [&] (CORE_ADDR start, CORE_ADDR end)
15027         {
15028           start += baseaddr;
15029           end += baseaddr;
15030           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
15031           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
15032           record_block_range (block, start, end - 1);
15033         });
15034     }
15035 }
15036
15037 /* Check whether the producer field indicates either of GCC < 4.6, or the
15038    Intel C/C++ compiler, and cache the result in CU.  */
15039
15040 static void
15041 check_producer (struct dwarf2_cu *cu)
15042 {
15043   int major, minor;
15044
15045   if (cu->producer == NULL)
15046     {
15047       /* For unknown compilers expect their behavior is DWARF version
15048          compliant.
15049
15050          GCC started to support .debug_types sections by -gdwarf-4 since
15051          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
15052          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
15053          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
15054          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
15055     }
15056   else if (producer_is_gcc (cu->producer, &major, &minor))
15057     {
15058       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
15059       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
15060     }
15061   else if (producer_is_icc (cu->producer, &major, &minor))
15062     cu->producer_is_icc_lt_14 = major < 14;
15063   else
15064     {
15065       /* For other non-GCC compilers, expect their behavior is DWARF version
15066          compliant.  */
15067     }
15068
15069   cu->checked_producer = 1;
15070 }
15071
15072 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
15073    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
15074    during 4.6.0 experimental.  */
15075
15076 static int
15077 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
15078 {
15079   if (!cu->checked_producer)
15080     check_producer (cu);
15081
15082   return cu->producer_is_gxx_lt_4_6;
15083 }
15084
15085 /* Return the default accessibility type if it is not overriden by
15086    DW_AT_accessibility.  */
15087
15088 static enum dwarf_access_attribute
15089 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
15090 {
15091   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
15092     {
15093       /* The default DWARF 2 accessibility for members is public, the default
15094          accessibility for inheritance is private.  */
15095
15096       if (die->tag != DW_TAG_inheritance)
15097         return DW_ACCESS_public;
15098       else
15099         return DW_ACCESS_private;
15100     }
15101   else
15102     {
15103       /* DWARF 3+ defines the default accessibility a different way.  The same
15104          rules apply now for DW_TAG_inheritance as for the members and it only
15105          depends on the container kind.  */
15106
15107       if (die->parent->tag == DW_TAG_class_type)
15108         return DW_ACCESS_private;
15109       else
15110         return DW_ACCESS_public;
15111     }
15112 }
15113
15114 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
15115    offset.  If the attribute was not found return 0, otherwise return
15116    1.  If it was found but could not properly be handled, set *OFFSET
15117    to 0.  */
15118
15119 static int
15120 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
15121                              LONGEST *offset)
15122 {
15123   struct attribute *attr;
15124
15125   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
15126   if (attr != NULL)
15127     {
15128       *offset = 0;
15129
15130       /* Note that we do not check for a section offset first here.
15131          This is because DW_AT_data_member_location is new in DWARF 4,
15132          so if we see it, we can assume that a constant form is really
15133          a constant and not a section offset.  */
15134       if (attr_form_is_constant (attr))
15135         *offset = dwarf2_get_attr_constant_value (attr, 0);
15136       else if (attr_form_is_section_offset (attr))
15137         dwarf2_complex_location_expr_complaint ();
15138       else if (attr_form_is_block (attr))
15139         *offset = decode_locdesc (DW_BLOCK (attr), cu);
15140       else
15141         dwarf2_complex_location_expr_complaint ();
15142
15143       return 1;
15144     }
15145
15146   return 0;
15147 }
15148
15149 /* Add an aggregate field to the field list.  */
15150
15151 static void
15152 dwarf2_add_field (struct field_info *fip, struct die_info *die,
15153                   struct dwarf2_cu *cu)
15154 {
15155   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15156   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15157   struct nextfield *new_field;
15158   struct attribute *attr;
15159   struct field *fp;
15160   const char *fieldname = "";
15161
15162   /* Allocate a new field list entry and link it in.  */
15163   new_field = XNEW (struct nextfield);
15164   make_cleanup (xfree, new_field);
15165   memset (new_field, 0, sizeof (struct nextfield));
15166
15167   if (die->tag == DW_TAG_inheritance)
15168     {
15169       new_field->next = fip->baseclasses;
15170       fip->baseclasses = new_field;
15171     }
15172   else
15173     {
15174       new_field->next = fip->fields;
15175       fip->fields = new_field;
15176     }
15177   fip->nfields++;
15178
15179   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15180   if (attr)
15181     new_field->accessibility = DW_UNSND (attr);
15182   else
15183     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
15184   if (new_field->accessibility != DW_ACCESS_public)
15185     fip->non_public_fields = 1;
15186
15187   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15188   if (attr)
15189     new_field->virtuality = DW_UNSND (attr);
15190   else
15191     new_field->virtuality = DW_VIRTUALITY_none;
15192
15193   fp = &new_field->field;
15194
15195   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
15196     {
15197       LONGEST offset;
15198
15199       /* Data member other than a C++ static data member.  */
15200
15201       /* Get type of field.  */
15202       fp->type = die_type (die, cu);
15203
15204       SET_FIELD_BITPOS (*fp, 0);
15205
15206       /* Get bit size of field (zero if none).  */
15207       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
15208       if (attr)
15209         {
15210           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
15211         }
15212       else
15213         {
15214           FIELD_BITSIZE (*fp) = 0;
15215         }
15216
15217       /* Get bit offset of field.  */
15218       if (handle_data_member_location (die, cu, &offset))
15219         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15220       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
15221       if (attr)
15222         {
15223           if (gdbarch_bits_big_endian (gdbarch))
15224             {
15225               /* For big endian bits, the DW_AT_bit_offset gives the
15226                  additional bit offset from the MSB of the containing
15227                  anonymous object to the MSB of the field.  We don't
15228                  have to do anything special since we don't need to
15229                  know the size of the anonymous object.  */
15230               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15231             }
15232           else
15233             {
15234               /* For little endian bits, compute the bit offset to the
15235                  MSB of the anonymous object, subtract off the number of
15236                  bits from the MSB of the field to the MSB of the
15237                  object, and then subtract off the number of bits of
15238                  the field itself.  The result is the bit offset of
15239                  the LSB of the field.  */
15240               int anonymous_size;
15241               int bit_offset = DW_UNSND (attr);
15242
15243               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15244               if (attr)
15245                 {
15246                   /* The size of the anonymous object containing
15247                      the bit field is explicit, so use the
15248                      indicated size (in bytes).  */
15249                   anonymous_size = DW_UNSND (attr);
15250                 }
15251               else
15252                 {
15253                   /* The size of the anonymous object containing
15254                      the bit field must be inferred from the type
15255                      attribute of the data member containing the
15256                      bit field.  */
15257                   anonymous_size = TYPE_LENGTH (fp->type);
15258                 }
15259               SET_FIELD_BITPOS (*fp,
15260                                 (FIELD_BITPOS (*fp)
15261                                  + anonymous_size * bits_per_byte
15262                                  - bit_offset - FIELD_BITSIZE (*fp)));
15263             }
15264         }
15265       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15266       if (attr != NULL)
15267         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15268                                 + dwarf2_get_attr_constant_value (attr, 0)));
15269
15270       /* Get name of field.  */
15271       fieldname = dwarf2_name (die, cu);
15272       if (fieldname == NULL)
15273         fieldname = "";
15274
15275       /* The name is already allocated along with this objfile, so we don't
15276          need to duplicate it for the type.  */
15277       fp->name = fieldname;
15278
15279       /* Change accessibility for artificial fields (e.g. virtual table
15280          pointer or virtual base class pointer) to private.  */
15281       if (dwarf2_attr (die, DW_AT_artificial, cu))
15282         {
15283           FIELD_ARTIFICIAL (*fp) = 1;
15284           new_field->accessibility = DW_ACCESS_private;
15285           fip->non_public_fields = 1;
15286         }
15287     }
15288   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15289     {
15290       /* C++ static member.  */
15291
15292       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15293          is a declaration, but all versions of G++ as of this writing
15294          (so through at least 3.2.1) incorrectly generate
15295          DW_TAG_variable tags.  */
15296
15297       const char *physname;
15298
15299       /* Get name of field.  */
15300       fieldname = dwarf2_name (die, cu);
15301       if (fieldname == NULL)
15302         return;
15303
15304       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15305       if (attr
15306           /* Only create a symbol if this is an external value.
15307              new_symbol checks this and puts the value in the global symbol
15308              table, which we want.  If it is not external, new_symbol
15309              will try to put the value in cu->list_in_scope which is wrong.  */
15310           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15311         {
15312           /* A static const member, not much different than an enum as far as
15313              we're concerned, except that we can support more types.  */
15314           new_symbol (die, NULL, cu);
15315         }
15316
15317       /* Get physical name.  */
15318       physname = dwarf2_physname (fieldname, die, cu);
15319
15320       /* The name is already allocated along with this objfile, so we don't
15321          need to duplicate it for the type.  */
15322       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15323       FIELD_TYPE (*fp) = die_type (die, cu);
15324       FIELD_NAME (*fp) = fieldname;
15325     }
15326   else if (die->tag == DW_TAG_inheritance)
15327     {
15328       LONGEST offset;
15329
15330       /* C++ base class field.  */
15331       if (handle_data_member_location (die, cu, &offset))
15332         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15333       FIELD_BITSIZE (*fp) = 0;
15334       FIELD_TYPE (*fp) = die_type (die, cu);
15335       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
15336       fip->nbaseclasses++;
15337     }
15338 }
15339
15340 /* Can the type given by DIE define another type?  */
15341
15342 static bool
15343 type_can_define_types (const struct die_info *die)
15344 {
15345   switch (die->tag)
15346     {
15347     case DW_TAG_typedef:
15348     case DW_TAG_class_type:
15349     case DW_TAG_structure_type:
15350     case DW_TAG_union_type:
15351     case DW_TAG_enumeration_type:
15352       return true;
15353
15354     default:
15355       return false;
15356     }
15357 }
15358
15359 /* Add a type definition defined in the scope of the FIP's class.  */
15360
15361 static void
15362 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15363                       struct dwarf2_cu *cu)
15364 {
15365   struct decl_field_list *new_field;
15366   struct decl_field *fp;
15367
15368   /* Allocate a new field list entry and link it in.  */
15369   new_field = XCNEW (struct decl_field_list);
15370   make_cleanup (xfree, new_field);
15371
15372   gdb_assert (type_can_define_types (die));
15373
15374   fp = &new_field->field;
15375
15376   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15377   fp->name = dwarf2_name (die, cu);
15378   fp->type = read_type_die (die, cu);
15379
15380   /* Save accessibility.  */
15381   enum dwarf_access_attribute accessibility;
15382   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15383   if (attr != NULL)
15384     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15385   else
15386     accessibility = dwarf2_default_access_attribute (die, cu);
15387   switch (accessibility)
15388     {
15389     case DW_ACCESS_public:
15390       /* The assumed value if neither private nor protected.  */
15391       break;
15392     case DW_ACCESS_private:
15393       fp->is_private = 1;
15394       break;
15395     case DW_ACCESS_protected:
15396       fp->is_protected = 1;
15397       break;
15398     default:
15399       complaint (&symfile_complaints,
15400                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15401     }
15402
15403   if (die->tag == DW_TAG_typedef)
15404     {
15405       new_field->next = fip->typedef_field_list;
15406       fip->typedef_field_list = new_field;
15407       fip->typedef_field_list_count++;
15408     }
15409   else
15410     {
15411       new_field->next = fip->nested_types_list;
15412       fip->nested_types_list = new_field;
15413       fip->nested_types_list_count++;
15414     }
15415 }
15416
15417 /* Create the vector of fields, and attach it to the type.  */
15418
15419 static void
15420 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15421                               struct dwarf2_cu *cu)
15422 {
15423   int nfields = fip->nfields;
15424
15425   /* Record the field count, allocate space for the array of fields,
15426      and create blank accessibility bitfields if necessary.  */
15427   TYPE_NFIELDS (type) = nfields;
15428   TYPE_FIELDS (type) = (struct field *)
15429     TYPE_ALLOC (type, sizeof (struct field) * nfields);
15430   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
15431
15432   if (fip->non_public_fields && cu->language != language_ada)
15433     {
15434       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15435
15436       TYPE_FIELD_PRIVATE_BITS (type) =
15437         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15438       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15439
15440       TYPE_FIELD_PROTECTED_BITS (type) =
15441         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15442       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15443
15444       TYPE_FIELD_IGNORE_BITS (type) =
15445         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15446       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15447     }
15448
15449   /* If the type has baseclasses, allocate and clear a bit vector for
15450      TYPE_FIELD_VIRTUAL_BITS.  */
15451   if (fip->nbaseclasses && cu->language != language_ada)
15452     {
15453       int num_bytes = B_BYTES (fip->nbaseclasses);
15454       unsigned char *pointer;
15455
15456       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15457       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15458       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15459       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
15460       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
15461     }
15462
15463   /* Copy the saved-up fields into the field vector.  Start from the head of
15464      the list, adding to the tail of the field array, so that they end up in
15465      the same order in the array in which they were added to the list.  */
15466   while (nfields-- > 0)
15467     {
15468       struct nextfield *fieldp;
15469
15470       if (fip->fields)
15471         {
15472           fieldp = fip->fields;
15473           fip->fields = fieldp->next;
15474         }
15475       else
15476         {
15477           fieldp = fip->baseclasses;
15478           fip->baseclasses = fieldp->next;
15479         }
15480
15481       TYPE_FIELD (type, nfields) = fieldp->field;
15482       switch (fieldp->accessibility)
15483         {
15484         case DW_ACCESS_private:
15485           if (cu->language != language_ada)
15486             SET_TYPE_FIELD_PRIVATE (type, nfields);
15487           break;
15488
15489         case DW_ACCESS_protected:
15490           if (cu->language != language_ada)
15491             SET_TYPE_FIELD_PROTECTED (type, nfields);
15492           break;
15493
15494         case DW_ACCESS_public:
15495           break;
15496
15497         default:
15498           /* Unknown accessibility.  Complain and treat it as public.  */
15499           {
15500             complaint (&symfile_complaints, _("unsupported accessibility %d"),
15501                        fieldp->accessibility);
15502           }
15503           break;
15504         }
15505       if (nfields < fip->nbaseclasses)
15506         {
15507           switch (fieldp->virtuality)
15508             {
15509             case DW_VIRTUALITY_virtual:
15510             case DW_VIRTUALITY_pure_virtual:
15511               if (cu->language == language_ada)
15512                 error (_("unexpected virtuality in component of Ada type"));
15513               SET_TYPE_FIELD_VIRTUAL (type, nfields);
15514               break;
15515             }
15516         }
15517     }
15518 }
15519
15520 /* Return true if this member function is a constructor, false
15521    otherwise.  */
15522
15523 static int
15524 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15525 {
15526   const char *fieldname;
15527   const char *type_name;
15528   int len;
15529
15530   if (die->parent == NULL)
15531     return 0;
15532
15533   if (die->parent->tag != DW_TAG_structure_type
15534       && die->parent->tag != DW_TAG_union_type
15535       && die->parent->tag != DW_TAG_class_type)
15536     return 0;
15537
15538   fieldname = dwarf2_name (die, cu);
15539   type_name = dwarf2_name (die->parent, cu);
15540   if (fieldname == NULL || type_name == NULL)
15541     return 0;
15542
15543   len = strlen (fieldname);
15544   return (strncmp (fieldname, type_name, len) == 0
15545           && (type_name[len] == '\0' || type_name[len] == '<'));
15546 }
15547
15548 /* Add a member function to the proper fieldlist.  */
15549
15550 static void
15551 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15552                       struct type *type, struct dwarf2_cu *cu)
15553 {
15554   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15555   struct attribute *attr;
15556   struct fnfieldlist *flp;
15557   int i;
15558   struct fn_field *fnp;
15559   const char *fieldname;
15560   struct nextfnfield *new_fnfield;
15561   struct type *this_type;
15562   enum dwarf_access_attribute accessibility;
15563
15564   if (cu->language == language_ada)
15565     error (_("unexpected member function in Ada type"));
15566
15567   /* Get name of member function.  */
15568   fieldname = dwarf2_name (die, cu);
15569   if (fieldname == NULL)
15570     return;
15571
15572   /* Look up member function name in fieldlist.  */
15573   for (i = 0; i < fip->nfnfields; i++)
15574     {
15575       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15576         break;
15577     }
15578
15579   /* Create new list element if necessary.  */
15580   if (i < fip->nfnfields)
15581     flp = &fip->fnfieldlists[i];
15582   else
15583     {
15584       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
15585         {
15586           fip->fnfieldlists = (struct fnfieldlist *)
15587             xrealloc (fip->fnfieldlists,
15588                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
15589                       * sizeof (struct fnfieldlist));
15590           if (fip->nfnfields == 0)
15591             make_cleanup (free_current_contents, &fip->fnfieldlists);
15592         }
15593       flp = &fip->fnfieldlists[fip->nfnfields];
15594       flp->name = fieldname;
15595       flp->length = 0;
15596       flp->head = NULL;
15597       i = fip->nfnfields++;
15598     }
15599
15600   /* Create a new member function field and chain it to the field list
15601      entry.  */
15602   new_fnfield = XNEW (struct nextfnfield);
15603   make_cleanup (xfree, new_fnfield);
15604   memset (new_fnfield, 0, sizeof (struct nextfnfield));
15605   new_fnfield->next = flp->head;
15606   flp->head = new_fnfield;
15607   flp->length++;
15608
15609   /* Fill in the member function field info.  */
15610   fnp = &new_fnfield->fnfield;
15611
15612   /* Delay processing of the physname until later.  */
15613   if (cu->language == language_cplus)
15614     {
15615       add_to_method_list (type, i, flp->length - 1, fieldname,
15616                           die, cu);
15617     }
15618   else
15619     {
15620       const char *physname = dwarf2_physname (fieldname, die, cu);
15621       fnp->physname = physname ? physname : "";
15622     }
15623
15624   fnp->type = alloc_type (objfile);
15625   this_type = read_type_die (die, cu);
15626   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15627     {
15628       int nparams = TYPE_NFIELDS (this_type);
15629
15630       /* TYPE is the domain of this method, and THIS_TYPE is the type
15631            of the method itself (TYPE_CODE_METHOD).  */
15632       smash_to_method_type (fnp->type, type,
15633                             TYPE_TARGET_TYPE (this_type),
15634                             TYPE_FIELDS (this_type),
15635                             TYPE_NFIELDS (this_type),
15636                             TYPE_VARARGS (this_type));
15637
15638       /* Handle static member functions.
15639          Dwarf2 has no clean way to discern C++ static and non-static
15640          member functions.  G++ helps GDB by marking the first
15641          parameter for non-static member functions (which is the this
15642          pointer) as artificial.  We obtain this information from
15643          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15644       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15645         fnp->voffset = VOFFSET_STATIC;
15646     }
15647   else
15648     complaint (&symfile_complaints, _("member function type missing for '%s'"),
15649                dwarf2_full_name (fieldname, die, cu));
15650
15651   /* Get fcontext from DW_AT_containing_type if present.  */
15652   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15653     fnp->fcontext = die_containing_type (die, cu);
15654
15655   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15656      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15657
15658   /* Get accessibility.  */
15659   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15660   if (attr)
15661     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15662   else
15663     accessibility = dwarf2_default_access_attribute (die, cu);
15664   switch (accessibility)
15665     {
15666     case DW_ACCESS_private:
15667       fnp->is_private = 1;
15668       break;
15669     case DW_ACCESS_protected:
15670       fnp->is_protected = 1;
15671       break;
15672     }
15673
15674   /* Check for artificial methods.  */
15675   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15676   if (attr && DW_UNSND (attr) != 0)
15677     fnp->is_artificial = 1;
15678
15679   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15680
15681   /* Get index in virtual function table if it is a virtual member
15682      function.  For older versions of GCC, this is an offset in the
15683      appropriate virtual table, as specified by DW_AT_containing_type.
15684      For everyone else, it is an expression to be evaluated relative
15685      to the object address.  */
15686
15687   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15688   if (attr)
15689     {
15690       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15691         {
15692           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15693             {
15694               /* Old-style GCC.  */
15695               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15696             }
15697           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15698                    || (DW_BLOCK (attr)->size > 1
15699                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15700                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15701             {
15702               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15703               if ((fnp->voffset % cu->header.addr_size) != 0)
15704                 dwarf2_complex_location_expr_complaint ();
15705               else
15706                 fnp->voffset /= cu->header.addr_size;
15707               fnp->voffset += 2;
15708             }
15709           else
15710             dwarf2_complex_location_expr_complaint ();
15711
15712           if (!fnp->fcontext)
15713             {
15714               /* If there is no `this' field and no DW_AT_containing_type,
15715                  we cannot actually find a base class context for the
15716                  vtable!  */
15717               if (TYPE_NFIELDS (this_type) == 0
15718                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15719                 {
15720                   complaint (&symfile_complaints,
15721                              _("cannot determine context for virtual member "
15722                                "function \"%s\" (offset %d)"),
15723                              fieldname, to_underlying (die->sect_off));
15724                 }
15725               else
15726                 {
15727                   fnp->fcontext
15728                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15729                 }
15730             }
15731         }
15732       else if (attr_form_is_section_offset (attr))
15733         {
15734           dwarf2_complex_location_expr_complaint ();
15735         }
15736       else
15737         {
15738           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15739                                                  fieldname);
15740         }
15741     }
15742   else
15743     {
15744       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15745       if (attr && DW_UNSND (attr))
15746         {
15747           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15748           complaint (&symfile_complaints,
15749                      _("Member function \"%s\" (offset %d) is virtual "
15750                        "but the vtable offset is not specified"),
15751                      fieldname, to_underlying (die->sect_off));
15752           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15753           TYPE_CPLUS_DYNAMIC (type) = 1;
15754         }
15755     }
15756 }
15757
15758 /* Create the vector of member function fields, and attach it to the type.  */
15759
15760 static void
15761 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15762                                  struct dwarf2_cu *cu)
15763 {
15764   struct fnfieldlist *flp;
15765   int i;
15766
15767   if (cu->language == language_ada)
15768     error (_("unexpected member functions in Ada type"));
15769
15770   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15771   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15772     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
15773
15774   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
15775     {
15776       struct nextfnfield *nfp = flp->head;
15777       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15778       int k;
15779
15780       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
15781       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
15782       fn_flp->fn_fields = (struct fn_field *)
15783         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
15784       for (k = flp->length; (k--, nfp); nfp = nfp->next)
15785         fn_flp->fn_fields[k] = nfp->fnfield;
15786     }
15787
15788   TYPE_NFN_FIELDS (type) = fip->nfnfields;
15789 }
15790
15791 /* Returns non-zero if NAME is the name of a vtable member in CU's
15792    language, zero otherwise.  */
15793 static int
15794 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15795 {
15796   static const char vptr[] = "_vptr";
15797
15798   /* Look for the C++ form of the vtable.  */
15799   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15800     return 1;
15801
15802   return 0;
15803 }
15804
15805 /* GCC outputs unnamed structures that are really pointers to member
15806    functions, with the ABI-specified layout.  If TYPE describes
15807    such a structure, smash it into a member function type.
15808
15809    GCC shouldn't do this; it should just output pointer to member DIEs.
15810    This is GCC PR debug/28767.  */
15811
15812 static void
15813 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15814 {
15815   struct type *pfn_type, *self_type, *new_type;
15816
15817   /* Check for a structure with no name and two children.  */
15818   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15819     return;
15820
15821   /* Check for __pfn and __delta members.  */
15822   if (TYPE_FIELD_NAME (type, 0) == NULL
15823       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15824       || TYPE_FIELD_NAME (type, 1) == NULL
15825       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15826     return;
15827
15828   /* Find the type of the method.  */
15829   pfn_type = TYPE_FIELD_TYPE (type, 0);
15830   if (pfn_type == NULL
15831       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15832       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15833     return;
15834
15835   /* Look for the "this" argument.  */
15836   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15837   if (TYPE_NFIELDS (pfn_type) == 0
15838       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15839       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15840     return;
15841
15842   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15843   new_type = alloc_type (objfile);
15844   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15845                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15846                         TYPE_VARARGS (pfn_type));
15847   smash_to_methodptr_type (type, new_type);
15848 }
15849
15850
15851 /* Called when we find the DIE that starts a structure or union scope
15852    (definition) to create a type for the structure or union.  Fill in
15853    the type's name and general properties; the members will not be
15854    processed until process_structure_scope.  A symbol table entry for
15855    the type will also not be done until process_structure_scope (assuming
15856    the type has a name).
15857
15858    NOTE: we need to call these functions regardless of whether or not the
15859    DIE has a DW_AT_name attribute, since it might be an anonymous
15860    structure or union.  This gets the type entered into our set of
15861    user defined types.  */
15862
15863 static struct type *
15864 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15865 {
15866   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15867   struct type *type;
15868   struct attribute *attr;
15869   const char *name;
15870
15871   /* If the definition of this type lives in .debug_types, read that type.
15872      Don't follow DW_AT_specification though, that will take us back up
15873      the chain and we want to go down.  */
15874   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15875   if (attr)
15876     {
15877       type = get_DW_AT_signature_type (die, attr, cu);
15878
15879       /* The type's CU may not be the same as CU.
15880          Ensure TYPE is recorded with CU in die_type_hash.  */
15881       return set_die_type (die, type, cu);
15882     }
15883
15884   type = alloc_type (objfile);
15885   INIT_CPLUS_SPECIFIC (type);
15886
15887   name = dwarf2_name (die, cu);
15888   if (name != NULL)
15889     {
15890       if (cu->language == language_cplus
15891           || cu->language == language_d
15892           || cu->language == language_rust)
15893         {
15894           const char *full_name = dwarf2_full_name (name, die, cu);
15895
15896           /* dwarf2_full_name might have already finished building the DIE's
15897              type.  If so, there is no need to continue.  */
15898           if (get_die_type (die, cu) != NULL)
15899             return get_die_type (die, cu);
15900
15901           TYPE_TAG_NAME (type) = full_name;
15902           if (die->tag == DW_TAG_structure_type
15903               || die->tag == DW_TAG_class_type)
15904             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15905         }
15906       else
15907         {
15908           /* The name is already allocated along with this objfile, so
15909              we don't need to duplicate it for the type.  */
15910           TYPE_TAG_NAME (type) = name;
15911           if (die->tag == DW_TAG_class_type)
15912             TYPE_NAME (type) = TYPE_TAG_NAME (type);
15913         }
15914     }
15915
15916   if (die->tag == DW_TAG_structure_type)
15917     {
15918       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15919     }
15920   else if (die->tag == DW_TAG_union_type)
15921     {
15922       TYPE_CODE (type) = TYPE_CODE_UNION;
15923     }
15924   else
15925     {
15926       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15927     }
15928
15929   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15930     TYPE_DECLARED_CLASS (type) = 1;
15931
15932   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15933   if (attr)
15934     {
15935       if (attr_form_is_constant (attr))
15936         TYPE_LENGTH (type) = DW_UNSND (attr);
15937       else
15938         {
15939           /* For the moment, dynamic type sizes are not supported
15940              by GDB's struct type.  The actual size is determined
15941              on-demand when resolving the type of a given object,
15942              so set the type's length to zero for now.  Otherwise,
15943              we record an expression as the length, and that expression
15944              could lead to a very large value, which could eventually
15945              lead to us trying to allocate that much memory when creating
15946              a value of that type.  */
15947           TYPE_LENGTH (type) = 0;
15948         }
15949     }
15950   else
15951     {
15952       TYPE_LENGTH (type) = 0;
15953     }
15954
15955   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15956     {
15957       /* ICC<14 does not output the required DW_AT_declaration on
15958          incomplete types, but gives them a size of zero.  */
15959       TYPE_STUB (type) = 1;
15960     }
15961   else
15962     TYPE_STUB_SUPPORTED (type) = 1;
15963
15964   if (die_is_declaration (die, cu))
15965     TYPE_STUB (type) = 1;
15966   else if (attr == NULL && die->child == NULL
15967            && producer_is_realview (cu->producer))
15968     /* RealView does not output the required DW_AT_declaration
15969        on incomplete types.  */
15970     TYPE_STUB (type) = 1;
15971
15972   /* We need to add the type field to the die immediately so we don't
15973      infinitely recurse when dealing with pointers to the structure
15974      type within the structure itself.  */
15975   set_die_type (die, type, cu);
15976
15977   /* set_die_type should be already done.  */
15978   set_descriptive_type (type, die, cu);
15979
15980   return type;
15981 }
15982
15983 /* Finish creating a structure or union type, including filling in
15984    its members and creating a symbol for it.  */
15985
15986 static void
15987 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15988 {
15989   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15990   struct die_info *child_die;
15991   struct type *type;
15992
15993   type = get_die_type (die, cu);
15994   if (type == NULL)
15995     type = read_structure_type (die, cu);
15996
15997   if (die->child != NULL && ! die_is_declaration (die, cu))
15998     {
15999       struct field_info fi;
16000       std::vector<struct symbol *> template_args;
16001       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
16002
16003       memset (&fi, 0, sizeof (struct field_info));
16004
16005       child_die = die->child;
16006
16007       while (child_die && child_die->tag)
16008         {
16009           if (child_die->tag == DW_TAG_member
16010               || child_die->tag == DW_TAG_variable)
16011             {
16012               /* NOTE: carlton/2002-11-05: A C++ static data member
16013                  should be a DW_TAG_member that is a declaration, but
16014                  all versions of G++ as of this writing (so through at
16015                  least 3.2.1) incorrectly generate DW_TAG_variable
16016                  tags for them instead.  */
16017               dwarf2_add_field (&fi, child_die, cu);
16018             }
16019           else if (child_die->tag == DW_TAG_subprogram)
16020             {
16021               /* Rust doesn't have member functions in the C++ sense.
16022                  However, it does emit ordinary functions as children
16023                  of a struct DIE.  */
16024               if (cu->language == language_rust)
16025                 read_func_scope (child_die, cu);
16026               else
16027                 {
16028                   /* C++ member function.  */
16029                   dwarf2_add_member_fn (&fi, child_die, type, cu);
16030                 }
16031             }
16032           else if (child_die->tag == DW_TAG_inheritance)
16033             {
16034               /* C++ base class field.  */
16035               dwarf2_add_field (&fi, child_die, cu);
16036             }
16037           else if (type_can_define_types (child_die))
16038             dwarf2_add_type_defn (&fi, child_die, cu);
16039           else if (child_die->tag == DW_TAG_template_type_param
16040                    || child_die->tag == DW_TAG_template_value_param)
16041             {
16042               struct symbol *arg = new_symbol (child_die, NULL, cu);
16043
16044               if (arg != NULL)
16045                 template_args.push_back (arg);
16046             }
16047
16048           child_die = sibling_die (child_die);
16049         }
16050
16051       /* Attach template arguments to type.  */
16052       if (!template_args.empty ())
16053         {
16054           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16055           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
16056           TYPE_TEMPLATE_ARGUMENTS (type)
16057             = XOBNEWVEC (&objfile->objfile_obstack,
16058                          struct symbol *,
16059                          TYPE_N_TEMPLATE_ARGUMENTS (type));
16060           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
16061                   template_args.data (),
16062                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
16063                    * sizeof (struct symbol *)));
16064         }
16065
16066       /* Attach fields and member functions to the type.  */
16067       if (fi.nfields)
16068         dwarf2_attach_fields_to_type (&fi, type, cu);
16069       if (fi.nfnfields)
16070         {
16071           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
16072
16073           /* Get the type which refers to the base class (possibly this
16074              class itself) which contains the vtable pointer for the current
16075              class from the DW_AT_containing_type attribute.  This use of
16076              DW_AT_containing_type is a GNU extension.  */
16077
16078           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
16079             {
16080               struct type *t = die_containing_type (die, cu);
16081
16082               set_type_vptr_basetype (type, t);
16083               if (type == t)
16084                 {
16085                   int i;
16086
16087                   /* Our own class provides vtbl ptr.  */
16088                   for (i = TYPE_NFIELDS (t) - 1;
16089                        i >= TYPE_N_BASECLASSES (t);
16090                        --i)
16091                     {
16092                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16093
16094                       if (is_vtable_name (fieldname, cu))
16095                         {
16096                           set_type_vptr_fieldno (type, i);
16097                           break;
16098                         }
16099                     }
16100
16101                   /* Complain if virtual function table field not found.  */
16102                   if (i < TYPE_N_BASECLASSES (t))
16103                     complaint (&symfile_complaints,
16104                                _("virtual function table pointer "
16105                                  "not found when defining class '%s'"),
16106                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
16107                                "");
16108                 }
16109               else
16110                 {
16111                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16112                 }
16113             }
16114           else if (cu->producer
16115                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16116             {
16117               /* The IBM XLC compiler does not provide direct indication
16118                  of the containing type, but the vtable pointer is
16119                  always named __vfp.  */
16120
16121               int i;
16122
16123               for (i = TYPE_NFIELDS (type) - 1;
16124                    i >= TYPE_N_BASECLASSES (type);
16125                    --i)
16126                 {
16127                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16128                     {
16129                       set_type_vptr_fieldno (type, i);
16130                       set_type_vptr_basetype (type, type);
16131                       break;
16132                     }
16133                 }
16134             }
16135         }
16136
16137       /* Copy fi.typedef_field_list linked list elements content into the
16138          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16139       if (fi.typedef_field_list)
16140         {
16141           int i = fi.typedef_field_list_count;
16142
16143           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16144           TYPE_TYPEDEF_FIELD_ARRAY (type)
16145             = ((struct decl_field *)
16146                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
16147           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
16148
16149           /* Reverse the list order to keep the debug info elements order.  */
16150           while (--i >= 0)
16151             {
16152               struct decl_field *dest, *src;
16153
16154               dest = &TYPE_TYPEDEF_FIELD (type, i);
16155               src = &fi.typedef_field_list->field;
16156               fi.typedef_field_list = fi.typedef_field_list->next;
16157               *dest = *src;
16158             }
16159         }
16160
16161       /* Copy fi.nested_types_list linked list elements content into the
16162          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16163       if (fi.nested_types_list != NULL && cu->language != language_ada)
16164         {
16165           int i = fi.nested_types_list_count;
16166
16167           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16168           TYPE_NESTED_TYPES_ARRAY (type)
16169             = ((struct decl_field *)
16170                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
16171           TYPE_NESTED_TYPES_COUNT (type) = i;
16172
16173           /* Reverse the list order to keep the debug info elements order.  */
16174           while (--i >= 0)
16175             {
16176               struct decl_field *dest, *src;
16177
16178               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
16179               src = &fi.nested_types_list->field;
16180               fi.nested_types_list = fi.nested_types_list->next;
16181               *dest = *src;
16182             }
16183         }
16184
16185       do_cleanups (back_to);
16186     }
16187
16188   quirk_gcc_member_function_pointer (type, objfile);
16189
16190   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16191      snapshots) has been known to create a die giving a declaration
16192      for a class that has, as a child, a die giving a definition for a
16193      nested class.  So we have to process our children even if the
16194      current die is a declaration.  Normally, of course, a declaration
16195      won't have any children at all.  */
16196
16197   child_die = die->child;
16198
16199   while (child_die != NULL && child_die->tag)
16200     {
16201       if (child_die->tag == DW_TAG_member
16202           || child_die->tag == DW_TAG_variable
16203           || child_die->tag == DW_TAG_inheritance
16204           || child_die->tag == DW_TAG_template_value_param
16205           || child_die->tag == DW_TAG_template_type_param)
16206         {
16207           /* Do nothing.  */
16208         }
16209       else
16210         process_die (child_die, cu);
16211
16212       child_die = sibling_die (child_die);
16213     }
16214
16215   /* Do not consider external references.  According to the DWARF standard,
16216      these DIEs are identified by the fact that they have no byte_size
16217      attribute, and a declaration attribute.  */
16218   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16219       || !die_is_declaration (die, cu))
16220     new_symbol (die, type, cu);
16221 }
16222
16223 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16224    update TYPE using some information only available in DIE's children.  */
16225
16226 static void
16227 update_enumeration_type_from_children (struct die_info *die,
16228                                        struct type *type,
16229                                        struct dwarf2_cu *cu)
16230 {
16231   struct die_info *child_die;
16232   int unsigned_enum = 1;
16233   int flag_enum = 1;
16234   ULONGEST mask = 0;
16235
16236   auto_obstack obstack;
16237
16238   for (child_die = die->child;
16239        child_die != NULL && child_die->tag;
16240        child_die = sibling_die (child_die))
16241     {
16242       struct attribute *attr;
16243       LONGEST value;
16244       const gdb_byte *bytes;
16245       struct dwarf2_locexpr_baton *baton;
16246       const char *name;
16247
16248       if (child_die->tag != DW_TAG_enumerator)
16249         continue;
16250
16251       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16252       if (attr == NULL)
16253         continue;
16254
16255       name = dwarf2_name (child_die, cu);
16256       if (name == NULL)
16257         name = "<anonymous enumerator>";
16258
16259       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16260                                &value, &bytes, &baton);
16261       if (value < 0)
16262         {
16263           unsigned_enum = 0;
16264           flag_enum = 0;
16265         }
16266       else if ((mask & value) != 0)
16267         flag_enum = 0;
16268       else
16269         mask |= value;
16270
16271       /* If we already know that the enum type is neither unsigned, nor
16272          a flag type, no need to look at the rest of the enumerates.  */
16273       if (!unsigned_enum && !flag_enum)
16274         break;
16275     }
16276
16277   if (unsigned_enum)
16278     TYPE_UNSIGNED (type) = 1;
16279   if (flag_enum)
16280     TYPE_FLAG_ENUM (type) = 1;
16281 }
16282
16283 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16284    complete the type's fields yet, or create any symbols.  */
16285
16286 static struct type *
16287 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16288 {
16289   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16290   struct type *type;
16291   struct attribute *attr;
16292   const char *name;
16293
16294   /* If the definition of this type lives in .debug_types, read that type.
16295      Don't follow DW_AT_specification though, that will take us back up
16296      the chain and we want to go down.  */
16297   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16298   if (attr)
16299     {
16300       type = get_DW_AT_signature_type (die, attr, cu);
16301
16302       /* The type's CU may not be the same as CU.
16303          Ensure TYPE is recorded with CU in die_type_hash.  */
16304       return set_die_type (die, type, cu);
16305     }
16306
16307   type = alloc_type (objfile);
16308
16309   TYPE_CODE (type) = TYPE_CODE_ENUM;
16310   name = dwarf2_full_name (NULL, die, cu);
16311   if (name != NULL)
16312     TYPE_TAG_NAME (type) = name;
16313
16314   attr = dwarf2_attr (die, DW_AT_type, cu);
16315   if (attr != NULL)
16316     {
16317       struct type *underlying_type = die_type (die, cu);
16318
16319       TYPE_TARGET_TYPE (type) = underlying_type;
16320     }
16321
16322   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16323   if (attr)
16324     {
16325       TYPE_LENGTH (type) = DW_UNSND (attr);
16326     }
16327   else
16328     {
16329       TYPE_LENGTH (type) = 0;
16330     }
16331
16332   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16333      declared as private in the package spec, and then defined only
16334      inside the package body.  Such types are known as Taft Amendment
16335      Types.  When another package uses such a type, an incomplete DIE
16336      may be generated by the compiler.  */
16337   if (die_is_declaration (die, cu))
16338     TYPE_STUB (type) = 1;
16339
16340   /* Finish the creation of this type by using the enum's children.
16341      We must call this even when the underlying type has been provided
16342      so that we can determine if we're looking at a "flag" enum.  */
16343   update_enumeration_type_from_children (die, type, cu);
16344
16345   /* If this type has an underlying type that is not a stub, then we
16346      may use its attributes.  We always use the "unsigned" attribute
16347      in this situation, because ordinarily we guess whether the type
16348      is unsigned -- but the guess can be wrong and the underlying type
16349      can tell us the reality.  However, we defer to a local size
16350      attribute if one exists, because this lets the compiler override
16351      the underlying type if needed.  */
16352   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16353     {
16354       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16355       if (TYPE_LENGTH (type) == 0)
16356         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16357     }
16358
16359   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16360
16361   return set_die_type (die, type, cu);
16362 }
16363
16364 /* Given a pointer to a die which begins an enumeration, process all
16365    the dies that define the members of the enumeration, and create the
16366    symbol for the enumeration type.
16367
16368    NOTE: We reverse the order of the element list.  */
16369
16370 static void
16371 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16372 {
16373   struct type *this_type;
16374
16375   this_type = get_die_type (die, cu);
16376   if (this_type == NULL)
16377     this_type = read_enumeration_type (die, cu);
16378
16379   if (die->child != NULL)
16380     {
16381       struct die_info *child_die;
16382       struct symbol *sym;
16383       struct field *fields = NULL;
16384       int num_fields = 0;
16385       const char *name;
16386
16387       child_die = die->child;
16388       while (child_die && child_die->tag)
16389         {
16390           if (child_die->tag != DW_TAG_enumerator)
16391             {
16392               process_die (child_die, cu);
16393             }
16394           else
16395             {
16396               name = dwarf2_name (child_die, cu);
16397               if (name)
16398                 {
16399                   sym = new_symbol (child_die, this_type, cu);
16400
16401                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16402                     {
16403                       fields = (struct field *)
16404                         xrealloc (fields,
16405                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16406                                   * sizeof (struct field));
16407                     }
16408
16409                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16410                   FIELD_TYPE (fields[num_fields]) = NULL;
16411                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16412                   FIELD_BITSIZE (fields[num_fields]) = 0;
16413
16414                   num_fields++;
16415                 }
16416             }
16417
16418           child_die = sibling_die (child_die);
16419         }
16420
16421       if (num_fields)
16422         {
16423           TYPE_NFIELDS (this_type) = num_fields;
16424           TYPE_FIELDS (this_type) = (struct field *)
16425             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16426           memcpy (TYPE_FIELDS (this_type), fields,
16427                   sizeof (struct field) * num_fields);
16428           xfree (fields);
16429         }
16430     }
16431
16432   /* If we are reading an enum from a .debug_types unit, and the enum
16433      is a declaration, and the enum is not the signatured type in the
16434      unit, then we do not want to add a symbol for it.  Adding a
16435      symbol would in some cases obscure the true definition of the
16436      enum, giving users an incomplete type when the definition is
16437      actually available.  Note that we do not want to do this for all
16438      enums which are just declarations, because C++0x allows forward
16439      enum declarations.  */
16440   if (cu->per_cu->is_debug_types
16441       && die_is_declaration (die, cu))
16442     {
16443       struct signatured_type *sig_type;
16444
16445       sig_type = (struct signatured_type *) cu->per_cu;
16446       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16447       if (sig_type->type_offset_in_section != die->sect_off)
16448         return;
16449     }
16450
16451   new_symbol (die, this_type, cu);
16452 }
16453
16454 /* Extract all information from a DW_TAG_array_type DIE and put it in
16455    the DIE's type field.  For now, this only handles one dimensional
16456    arrays.  */
16457
16458 static struct type *
16459 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16460 {
16461   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16462   struct die_info *child_die;
16463   struct type *type;
16464   struct type *element_type, *range_type, *index_type;
16465   struct attribute *attr;
16466   const char *name;
16467   struct dynamic_prop *byte_stride_prop = NULL;
16468   unsigned int bit_stride = 0;
16469
16470   element_type = die_type (die, cu);
16471
16472   /* The die_type call above may have already set the type for this DIE.  */
16473   type = get_die_type (die, cu);
16474   if (type)
16475     return type;
16476
16477   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16478   if (attr != NULL)
16479     {
16480       int stride_ok;
16481
16482       byte_stride_prop
16483         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16484       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16485       if (!stride_ok)
16486         {
16487           complaint (&symfile_complaints,
16488                      _("unable to read array DW_AT_byte_stride "
16489                        " - DIE at 0x%x [in module %s]"),
16490                      to_underlying (die->sect_off),
16491                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16492           /* Ignore this attribute.  We will likely not be able to print
16493              arrays of this type correctly, but there is little we can do
16494              to help if we cannot read the attribute's value.  */
16495           byte_stride_prop = NULL;
16496         }
16497     }
16498
16499   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16500   if (attr != NULL)
16501     bit_stride = DW_UNSND (attr);
16502
16503   /* Irix 6.2 native cc creates array types without children for
16504      arrays with unspecified length.  */
16505   if (die->child == NULL)
16506     {
16507       index_type = objfile_type (objfile)->builtin_int;
16508       range_type = create_static_range_type (NULL, index_type, 0, -1);
16509       type = create_array_type_with_stride (NULL, element_type, range_type,
16510                                             byte_stride_prop, bit_stride);
16511       return set_die_type (die, type, cu);
16512     }
16513
16514   std::vector<struct type *> range_types;
16515   child_die = die->child;
16516   while (child_die && child_die->tag)
16517     {
16518       if (child_die->tag == DW_TAG_subrange_type)
16519         {
16520           struct type *child_type = read_type_die (child_die, cu);
16521
16522           if (child_type != NULL)
16523             {
16524               /* The range type was succesfully read.  Save it for the
16525                  array type creation.  */
16526               range_types.push_back (child_type);
16527             }
16528         }
16529       child_die = sibling_die (child_die);
16530     }
16531
16532   /* Dwarf2 dimensions are output from left to right, create the
16533      necessary array types in backwards order.  */
16534
16535   type = element_type;
16536
16537   if (read_array_order (die, cu) == DW_ORD_col_major)
16538     {
16539       int i = 0;
16540
16541       while (i < range_types.size ())
16542         type = create_array_type_with_stride (NULL, type, range_types[i++],
16543                                               byte_stride_prop, bit_stride);
16544     }
16545   else
16546     {
16547       size_t ndim = range_types.size ();
16548       while (ndim-- > 0)
16549         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16550                                               byte_stride_prop, bit_stride);
16551     }
16552
16553   /* Understand Dwarf2 support for vector types (like they occur on
16554      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16555      array type.  This is not part of the Dwarf2/3 standard yet, but a
16556      custom vendor extension.  The main difference between a regular
16557      array and the vector variant is that vectors are passed by value
16558      to functions.  */
16559   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16560   if (attr)
16561     make_vector_type (type);
16562
16563   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16564      implementation may choose to implement triple vectors using this
16565      attribute.  */
16566   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16567   if (attr)
16568     {
16569       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16570         TYPE_LENGTH (type) = DW_UNSND (attr);
16571       else
16572         complaint (&symfile_complaints,
16573                    _("DW_AT_byte_size for array type smaller "
16574                      "than the total size of elements"));
16575     }
16576
16577   name = dwarf2_name (die, cu);
16578   if (name)
16579     TYPE_NAME (type) = name;
16580
16581   /* Install the type in the die.  */
16582   set_die_type (die, type, cu);
16583
16584   /* set_die_type should be already done.  */
16585   set_descriptive_type (type, die, cu);
16586
16587   return type;
16588 }
16589
16590 static enum dwarf_array_dim_ordering
16591 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16592 {
16593   struct attribute *attr;
16594
16595   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16596
16597   if (attr)
16598     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16599
16600   /* GNU F77 is a special case, as at 08/2004 array type info is the
16601      opposite order to the dwarf2 specification, but data is still
16602      laid out as per normal fortran.
16603
16604      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16605      version checking.  */
16606
16607   if (cu->language == language_fortran
16608       && cu->producer && strstr (cu->producer, "GNU F77"))
16609     {
16610       return DW_ORD_row_major;
16611     }
16612
16613   switch (cu->language_defn->la_array_ordering)
16614     {
16615     case array_column_major:
16616       return DW_ORD_col_major;
16617     case array_row_major:
16618     default:
16619       return DW_ORD_row_major;
16620     };
16621 }
16622
16623 /* Extract all information from a DW_TAG_set_type DIE and put it in
16624    the DIE's type field.  */
16625
16626 static struct type *
16627 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16628 {
16629   struct type *domain_type, *set_type;
16630   struct attribute *attr;
16631
16632   domain_type = die_type (die, cu);
16633
16634   /* The die_type call above may have already set the type for this DIE.  */
16635   set_type = get_die_type (die, cu);
16636   if (set_type)
16637     return set_type;
16638
16639   set_type = create_set_type (NULL, domain_type);
16640
16641   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16642   if (attr)
16643     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16644
16645   return set_die_type (die, set_type, cu);
16646 }
16647
16648 /* A helper for read_common_block that creates a locexpr baton.
16649    SYM is the symbol which we are marking as computed.
16650    COMMON_DIE is the DIE for the common block.
16651    COMMON_LOC is the location expression attribute for the common
16652    block itself.
16653    MEMBER_LOC is the location expression attribute for the particular
16654    member of the common block that we are processing.
16655    CU is the CU from which the above come.  */
16656
16657 static void
16658 mark_common_block_symbol_computed (struct symbol *sym,
16659                                    struct die_info *common_die,
16660                                    struct attribute *common_loc,
16661                                    struct attribute *member_loc,
16662                                    struct dwarf2_cu *cu)
16663 {
16664   struct dwarf2_per_objfile *dwarf2_per_objfile
16665     = cu->per_cu->dwarf2_per_objfile;
16666   struct objfile *objfile = dwarf2_per_objfile->objfile;
16667   struct dwarf2_locexpr_baton *baton;
16668   gdb_byte *ptr;
16669   unsigned int cu_off;
16670   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16671   LONGEST offset = 0;
16672
16673   gdb_assert (common_loc && member_loc);
16674   gdb_assert (attr_form_is_block (common_loc));
16675   gdb_assert (attr_form_is_block (member_loc)
16676               || attr_form_is_constant (member_loc));
16677
16678   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16679   baton->per_cu = cu->per_cu;
16680   gdb_assert (baton->per_cu);
16681
16682   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16683
16684   if (attr_form_is_constant (member_loc))
16685     {
16686       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16687       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16688     }
16689   else
16690     baton->size += DW_BLOCK (member_loc)->size;
16691
16692   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16693   baton->data = ptr;
16694
16695   *ptr++ = DW_OP_call4;
16696   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16697   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16698   ptr += 4;
16699
16700   if (attr_form_is_constant (member_loc))
16701     {
16702       *ptr++ = DW_OP_addr;
16703       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16704       ptr += cu->header.addr_size;
16705     }
16706   else
16707     {
16708       /* We have to copy the data here, because DW_OP_call4 will only
16709          use a DW_AT_location attribute.  */
16710       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16711       ptr += DW_BLOCK (member_loc)->size;
16712     }
16713
16714   *ptr++ = DW_OP_plus;
16715   gdb_assert (ptr - baton->data == baton->size);
16716
16717   SYMBOL_LOCATION_BATON (sym) = baton;
16718   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16719 }
16720
16721 /* Create appropriate locally-scoped variables for all the
16722    DW_TAG_common_block entries.  Also create a struct common_block
16723    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16724    is used to sepate the common blocks name namespace from regular
16725    variable names.  */
16726
16727 static void
16728 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16729 {
16730   struct attribute *attr;
16731
16732   attr = dwarf2_attr (die, DW_AT_location, cu);
16733   if (attr)
16734     {
16735       /* Support the .debug_loc offsets.  */
16736       if (attr_form_is_block (attr))
16737         {
16738           /* Ok.  */
16739         }
16740       else if (attr_form_is_section_offset (attr))
16741         {
16742           dwarf2_complex_location_expr_complaint ();
16743           attr = NULL;
16744         }
16745       else
16746         {
16747           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16748                                                  "common block member");
16749           attr = NULL;
16750         }
16751     }
16752
16753   if (die->child != NULL)
16754     {
16755       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16756       struct die_info *child_die;
16757       size_t n_entries = 0, size;
16758       struct common_block *common_block;
16759       struct symbol *sym;
16760
16761       for (child_die = die->child;
16762            child_die && child_die->tag;
16763            child_die = sibling_die (child_die))
16764         ++n_entries;
16765
16766       size = (sizeof (struct common_block)
16767               + (n_entries - 1) * sizeof (struct symbol *));
16768       common_block
16769         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16770                                                  size);
16771       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16772       common_block->n_entries = 0;
16773
16774       for (child_die = die->child;
16775            child_die && child_die->tag;
16776            child_die = sibling_die (child_die))
16777         {
16778           /* Create the symbol in the DW_TAG_common_block block in the current
16779              symbol scope.  */
16780           sym = new_symbol (child_die, NULL, cu);
16781           if (sym != NULL)
16782             {
16783               struct attribute *member_loc;
16784
16785               common_block->contents[common_block->n_entries++] = sym;
16786
16787               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16788                                         cu);
16789               if (member_loc)
16790                 {
16791                   /* GDB has handled this for a long time, but it is
16792                      not specified by DWARF.  It seems to have been
16793                      emitted by gfortran at least as recently as:
16794                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16795                   complaint (&symfile_complaints,
16796                              _("Variable in common block has "
16797                                "DW_AT_data_member_location "
16798                                "- DIE at 0x%x [in module %s]"),
16799                              to_underlying (child_die->sect_off),
16800                              objfile_name (objfile));
16801
16802                   if (attr_form_is_section_offset (member_loc))
16803                     dwarf2_complex_location_expr_complaint ();
16804                   else if (attr_form_is_constant (member_loc)
16805                            || attr_form_is_block (member_loc))
16806                     {
16807                       if (attr)
16808                         mark_common_block_symbol_computed (sym, die, attr,
16809                                                            member_loc, cu);
16810                     }
16811                   else
16812                     dwarf2_complex_location_expr_complaint ();
16813                 }
16814             }
16815         }
16816
16817       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16818       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16819     }
16820 }
16821
16822 /* Create a type for a C++ namespace.  */
16823
16824 static struct type *
16825 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16826 {
16827   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16828   const char *previous_prefix, *name;
16829   int is_anonymous;
16830   struct type *type;
16831
16832   /* For extensions, reuse the type of the original namespace.  */
16833   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16834     {
16835       struct die_info *ext_die;
16836       struct dwarf2_cu *ext_cu = cu;
16837
16838       ext_die = dwarf2_extension (die, &ext_cu);
16839       type = read_type_die (ext_die, ext_cu);
16840
16841       /* EXT_CU may not be the same as CU.
16842          Ensure TYPE is recorded with CU in die_type_hash.  */
16843       return set_die_type (die, type, cu);
16844     }
16845
16846   name = namespace_name (die, &is_anonymous, cu);
16847
16848   /* Now build the name of the current namespace.  */
16849
16850   previous_prefix = determine_prefix (die, cu);
16851   if (previous_prefix[0] != '\0')
16852     name = typename_concat (&objfile->objfile_obstack,
16853                             previous_prefix, name, 0, cu);
16854
16855   /* Create the type.  */
16856   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16857   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16858
16859   return set_die_type (die, type, cu);
16860 }
16861
16862 /* Read a namespace scope.  */
16863
16864 static void
16865 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16866 {
16867   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16868   int is_anonymous;
16869
16870   /* Add a symbol associated to this if we haven't seen the namespace
16871      before.  Also, add a using directive if it's an anonymous
16872      namespace.  */
16873
16874   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16875     {
16876       struct type *type;
16877
16878       type = read_type_die (die, cu);
16879       new_symbol (die, type, cu);
16880
16881       namespace_name (die, &is_anonymous, cu);
16882       if (is_anonymous)
16883         {
16884           const char *previous_prefix = determine_prefix (die, cu);
16885
16886           std::vector<const char *> excludes;
16887           add_using_directive (using_directives (cu->language),
16888                                previous_prefix, TYPE_NAME (type), NULL,
16889                                NULL, excludes, 0, &objfile->objfile_obstack);
16890         }
16891     }
16892
16893   if (die->child != NULL)
16894     {
16895       struct die_info *child_die = die->child;
16896
16897       while (child_die && child_die->tag)
16898         {
16899           process_die (child_die, cu);
16900           child_die = sibling_die (child_die);
16901         }
16902     }
16903 }
16904
16905 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16906    imported module.  Still we need that type as local Fortran "use ... only"
16907    declaration imports depend on the created type in determine_prefix.  */
16908
16909 static struct type *
16910 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16911 {
16912   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16913   const char *module_name;
16914   struct type *type;
16915
16916   module_name = dwarf2_name (die, cu);
16917   if (!module_name)
16918     complaint (&symfile_complaints,
16919                _("DW_TAG_module has no name, offset 0x%x"),
16920                to_underlying (die->sect_off));
16921   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16922
16923   /* determine_prefix uses TYPE_TAG_NAME.  */
16924   TYPE_TAG_NAME (type) = TYPE_NAME (type);
16925
16926   return set_die_type (die, type, cu);
16927 }
16928
16929 /* Read a Fortran module.  */
16930
16931 static void
16932 read_module (struct die_info *die, struct dwarf2_cu *cu)
16933 {
16934   struct die_info *child_die = die->child;
16935   struct type *type;
16936
16937   type = read_type_die (die, cu);
16938   new_symbol (die, type, cu);
16939
16940   while (child_die && child_die->tag)
16941     {
16942       process_die (child_die, cu);
16943       child_die = sibling_die (child_die);
16944     }
16945 }
16946
16947 /* Return the name of the namespace represented by DIE.  Set
16948    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16949    namespace.  */
16950
16951 static const char *
16952 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16953 {
16954   struct die_info *current_die;
16955   const char *name = NULL;
16956
16957   /* Loop through the extensions until we find a name.  */
16958
16959   for (current_die = die;
16960        current_die != NULL;
16961        current_die = dwarf2_extension (die, &cu))
16962     {
16963       /* We don't use dwarf2_name here so that we can detect the absence
16964          of a name -> anonymous namespace.  */
16965       name = dwarf2_string_attr (die, DW_AT_name, cu);
16966
16967       if (name != NULL)
16968         break;
16969     }
16970
16971   /* Is it an anonymous namespace?  */
16972
16973   *is_anonymous = (name == NULL);
16974   if (*is_anonymous)
16975     name = CP_ANONYMOUS_NAMESPACE_STR;
16976
16977   return name;
16978 }
16979
16980 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16981    the user defined type vector.  */
16982
16983 static struct type *
16984 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16985 {
16986   struct gdbarch *gdbarch
16987     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16988   struct comp_unit_head *cu_header = &cu->header;
16989   struct type *type;
16990   struct attribute *attr_byte_size;
16991   struct attribute *attr_address_class;
16992   int byte_size, addr_class;
16993   struct type *target_type;
16994
16995   target_type = die_type (die, cu);
16996
16997   /* The die_type call above may have already set the type for this DIE.  */
16998   type = get_die_type (die, cu);
16999   if (type)
17000     return type;
17001
17002   type = lookup_pointer_type (target_type);
17003
17004   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
17005   if (attr_byte_size)
17006     byte_size = DW_UNSND (attr_byte_size);
17007   else
17008     byte_size = cu_header->addr_size;
17009
17010   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
17011   if (attr_address_class)
17012     addr_class = DW_UNSND (attr_address_class);
17013   else
17014     addr_class = DW_ADDR_none;
17015
17016   /* If the pointer size or address class is different than the
17017      default, create a type variant marked as such and set the
17018      length accordingly.  */
17019   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
17020     {
17021       if (gdbarch_address_class_type_flags_p (gdbarch))
17022         {
17023           int type_flags;
17024
17025           type_flags = gdbarch_address_class_type_flags
17026                          (gdbarch, byte_size, addr_class);
17027           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
17028                       == 0);
17029           type = make_type_with_address_space (type, type_flags);
17030         }
17031       else if (TYPE_LENGTH (type) != byte_size)
17032         {
17033           complaint (&symfile_complaints,
17034                      _("invalid pointer size %d"), byte_size);
17035         }
17036       else
17037         {
17038           /* Should we also complain about unhandled address classes?  */
17039         }
17040     }
17041
17042   TYPE_LENGTH (type) = byte_size;
17043   return set_die_type (die, type, cu);
17044 }
17045
17046 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
17047    the user defined type vector.  */
17048
17049 static struct type *
17050 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
17051 {
17052   struct type *type;
17053   struct type *to_type;
17054   struct type *domain;
17055
17056   to_type = die_type (die, cu);
17057   domain = die_containing_type (die, cu);
17058
17059   /* The calls above may have already set the type for this DIE.  */
17060   type = get_die_type (die, cu);
17061   if (type)
17062     return type;
17063
17064   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
17065     type = lookup_methodptr_type (to_type);
17066   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
17067     {
17068       struct type *new_type
17069         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
17070
17071       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
17072                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
17073                             TYPE_VARARGS (to_type));
17074       type = lookup_methodptr_type (new_type);
17075     }
17076   else
17077     type = lookup_memberptr_type (to_type, domain);
17078
17079   return set_die_type (die, type, cu);
17080 }
17081
17082 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17083    the user defined type vector.  */
17084
17085 static struct type *
17086 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17087                           enum type_code refcode)
17088 {
17089   struct comp_unit_head *cu_header = &cu->header;
17090   struct type *type, *target_type;
17091   struct attribute *attr;
17092
17093   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17094
17095   target_type = die_type (die, cu);
17096
17097   /* The die_type call above may have already set the type for this DIE.  */
17098   type = get_die_type (die, cu);
17099   if (type)
17100     return type;
17101
17102   type = lookup_reference_type (target_type, refcode);
17103   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17104   if (attr)
17105     {
17106       TYPE_LENGTH (type) = DW_UNSND (attr);
17107     }
17108   else
17109     {
17110       TYPE_LENGTH (type) = cu_header->addr_size;
17111     }
17112   return set_die_type (die, type, cu);
17113 }
17114
17115 /* Add the given cv-qualifiers to the element type of the array.  GCC
17116    outputs DWARF type qualifiers that apply to an array, not the
17117    element type.  But GDB relies on the array element type to carry
17118    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17119    specification.  */
17120
17121 static struct type *
17122 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17123                    struct type *base_type, int cnst, int voltl)
17124 {
17125   struct type *el_type, *inner_array;
17126
17127   base_type = copy_type (base_type);
17128   inner_array = base_type;
17129
17130   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17131     {
17132       TYPE_TARGET_TYPE (inner_array) =
17133         copy_type (TYPE_TARGET_TYPE (inner_array));
17134       inner_array = TYPE_TARGET_TYPE (inner_array);
17135     }
17136
17137   el_type = TYPE_TARGET_TYPE (inner_array);
17138   cnst |= TYPE_CONST (el_type);
17139   voltl |= TYPE_VOLATILE (el_type);
17140   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17141
17142   return set_die_type (die, base_type, cu);
17143 }
17144
17145 static struct type *
17146 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17147 {
17148   struct type *base_type, *cv_type;
17149
17150   base_type = die_type (die, cu);
17151
17152   /* The die_type call above may have already set the type for this DIE.  */
17153   cv_type = get_die_type (die, cu);
17154   if (cv_type)
17155     return cv_type;
17156
17157   /* In case the const qualifier is applied to an array type, the element type
17158      is so qualified, not the array type (section 6.7.3 of C99).  */
17159   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17160     return add_array_cv_type (die, cu, base_type, 1, 0);
17161
17162   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17163   return set_die_type (die, cv_type, cu);
17164 }
17165
17166 static struct type *
17167 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17168 {
17169   struct type *base_type, *cv_type;
17170
17171   base_type = die_type (die, cu);
17172
17173   /* The die_type call above may have already set the type for this DIE.  */
17174   cv_type = get_die_type (die, cu);
17175   if (cv_type)
17176     return cv_type;
17177
17178   /* In case the volatile qualifier is applied to an array type, the
17179      element type is so qualified, not the array type (section 6.7.3
17180      of C99).  */
17181   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17182     return add_array_cv_type (die, cu, base_type, 0, 1);
17183
17184   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17185   return set_die_type (die, cv_type, cu);
17186 }
17187
17188 /* Handle DW_TAG_restrict_type.  */
17189
17190 static struct type *
17191 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17192 {
17193   struct type *base_type, *cv_type;
17194
17195   base_type = die_type (die, cu);
17196
17197   /* The die_type call above may have already set the type for this DIE.  */
17198   cv_type = get_die_type (die, cu);
17199   if (cv_type)
17200     return cv_type;
17201
17202   cv_type = make_restrict_type (base_type);
17203   return set_die_type (die, cv_type, cu);
17204 }
17205
17206 /* Handle DW_TAG_atomic_type.  */
17207
17208 static struct type *
17209 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17210 {
17211   struct type *base_type, *cv_type;
17212
17213   base_type = die_type (die, cu);
17214
17215   /* The die_type call above may have already set the type for this DIE.  */
17216   cv_type = get_die_type (die, cu);
17217   if (cv_type)
17218     return cv_type;
17219
17220   cv_type = make_atomic_type (base_type);
17221   return set_die_type (die, cv_type, cu);
17222 }
17223
17224 /* Extract all information from a DW_TAG_string_type DIE and add to
17225    the user defined type vector.  It isn't really a user defined type,
17226    but it behaves like one, with other DIE's using an AT_user_def_type
17227    attribute to reference it.  */
17228
17229 static struct type *
17230 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17231 {
17232   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17233   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17234   struct type *type, *range_type, *index_type, *char_type;
17235   struct attribute *attr;
17236   unsigned int length;
17237
17238   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17239   if (attr)
17240     {
17241       length = DW_UNSND (attr);
17242     }
17243   else
17244     {
17245       /* Check for the DW_AT_byte_size attribute.  */
17246       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17247       if (attr)
17248         {
17249           length = DW_UNSND (attr);
17250         }
17251       else
17252         {
17253           length = 1;
17254         }
17255     }
17256
17257   index_type = objfile_type (objfile)->builtin_int;
17258   range_type = create_static_range_type (NULL, index_type, 1, length);
17259   char_type = language_string_char_type (cu->language_defn, gdbarch);
17260   type = create_string_type (NULL, char_type, range_type);
17261
17262   return set_die_type (die, type, cu);
17263 }
17264
17265 /* Assuming that DIE corresponds to a function, returns nonzero
17266    if the function is prototyped.  */
17267
17268 static int
17269 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17270 {
17271   struct attribute *attr;
17272
17273   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17274   if (attr && (DW_UNSND (attr) != 0))
17275     return 1;
17276
17277   /* The DWARF standard implies that the DW_AT_prototyped attribute
17278      is only meaninful for C, but the concept also extends to other
17279      languages that allow unprototyped functions (Eg: Objective C).
17280      For all other languages, assume that functions are always
17281      prototyped.  */
17282   if (cu->language != language_c
17283       && cu->language != language_objc
17284       && cu->language != language_opencl)
17285     return 1;
17286
17287   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17288      prototyped and unprototyped functions; default to prototyped,
17289      since that is more common in modern code (and RealView warns
17290      about unprototyped functions).  */
17291   if (producer_is_realview (cu->producer))
17292     return 1;
17293
17294   return 0;
17295 }
17296
17297 /* Handle DIES due to C code like:
17298
17299    struct foo
17300    {
17301    int (*funcp)(int a, long l);
17302    int b;
17303    };
17304
17305    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17306
17307 static struct type *
17308 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17309 {
17310   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17311   struct type *type;            /* Type that this function returns.  */
17312   struct type *ftype;           /* Function that returns above type.  */
17313   struct attribute *attr;
17314
17315   type = die_type (die, cu);
17316
17317   /* The die_type call above may have already set the type for this DIE.  */
17318   ftype = get_die_type (die, cu);
17319   if (ftype)
17320     return ftype;
17321
17322   ftype = lookup_function_type (type);
17323
17324   if (prototyped_function_p (die, cu))
17325     TYPE_PROTOTYPED (ftype) = 1;
17326
17327   /* Store the calling convention in the type if it's available in
17328      the subroutine die.  Otherwise set the calling convention to
17329      the default value DW_CC_normal.  */
17330   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17331   if (attr)
17332     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17333   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17334     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17335   else
17336     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17337
17338   /* Record whether the function returns normally to its caller or not
17339      if the DWARF producer set that information.  */
17340   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17341   if (attr && (DW_UNSND (attr) != 0))
17342     TYPE_NO_RETURN (ftype) = 1;
17343
17344   /* We need to add the subroutine type to the die immediately so
17345      we don't infinitely recurse when dealing with parameters
17346      declared as the same subroutine type.  */
17347   set_die_type (die, ftype, cu);
17348
17349   if (die->child != NULL)
17350     {
17351       struct type *void_type = objfile_type (objfile)->builtin_void;
17352       struct die_info *child_die;
17353       int nparams, iparams;
17354
17355       /* Count the number of parameters.
17356          FIXME: GDB currently ignores vararg functions, but knows about
17357          vararg member functions.  */
17358       nparams = 0;
17359       child_die = die->child;
17360       while (child_die && child_die->tag)
17361         {
17362           if (child_die->tag == DW_TAG_formal_parameter)
17363             nparams++;
17364           else if (child_die->tag == DW_TAG_unspecified_parameters)
17365             TYPE_VARARGS (ftype) = 1;
17366           child_die = sibling_die (child_die);
17367         }
17368
17369       /* Allocate storage for parameters and fill them in.  */
17370       TYPE_NFIELDS (ftype) = nparams;
17371       TYPE_FIELDS (ftype) = (struct field *)
17372         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17373
17374       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17375          even if we error out during the parameters reading below.  */
17376       for (iparams = 0; iparams < nparams; iparams++)
17377         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17378
17379       iparams = 0;
17380       child_die = die->child;
17381       while (child_die && child_die->tag)
17382         {
17383           if (child_die->tag == DW_TAG_formal_parameter)
17384             {
17385               struct type *arg_type;
17386
17387               /* DWARF version 2 has no clean way to discern C++
17388                  static and non-static member functions.  G++ helps
17389                  GDB by marking the first parameter for non-static
17390                  member functions (which is the this pointer) as
17391                  artificial.  We pass this information to
17392                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17393
17394                  DWARF version 3 added DW_AT_object_pointer, which GCC
17395                  4.5 does not yet generate.  */
17396               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17397               if (attr)
17398                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17399               else
17400                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17401               arg_type = die_type (child_die, cu);
17402
17403               /* RealView does not mark THIS as const, which the testsuite
17404                  expects.  GCC marks THIS as const in method definitions,
17405                  but not in the class specifications (GCC PR 43053).  */
17406               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17407                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17408                 {
17409                   int is_this = 0;
17410                   struct dwarf2_cu *arg_cu = cu;
17411                   const char *name = dwarf2_name (child_die, cu);
17412
17413                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17414                   if (attr)
17415                     {
17416                       /* If the compiler emits this, use it.  */
17417                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17418                         is_this = 1;
17419                     }
17420                   else if (name && strcmp (name, "this") == 0)
17421                     /* Function definitions will have the argument names.  */
17422                     is_this = 1;
17423                   else if (name == NULL && iparams == 0)
17424                     /* Declarations may not have the names, so like
17425                        elsewhere in GDB, assume an artificial first
17426                        argument is "this".  */
17427                     is_this = 1;
17428
17429                   if (is_this)
17430                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17431                                              arg_type, 0);
17432                 }
17433
17434               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17435               iparams++;
17436             }
17437           child_die = sibling_die (child_die);
17438         }
17439     }
17440
17441   return ftype;
17442 }
17443
17444 static struct type *
17445 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17446 {
17447   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17448   const char *name = NULL;
17449   struct type *this_type, *target_type;
17450
17451   name = dwarf2_full_name (NULL, die, cu);
17452   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17453   TYPE_TARGET_STUB (this_type) = 1;
17454   set_die_type (die, this_type, cu);
17455   target_type = die_type (die, cu);
17456   if (target_type != this_type)
17457     TYPE_TARGET_TYPE (this_type) = target_type;
17458   else
17459     {
17460       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17461          spec and cause infinite loops in GDB.  */
17462       complaint (&symfile_complaints,
17463                  _("Self-referential DW_TAG_typedef "
17464                    "- DIE at 0x%x [in module %s]"),
17465                  to_underlying (die->sect_off), objfile_name (objfile));
17466       TYPE_TARGET_TYPE (this_type) = NULL;
17467     }
17468   return this_type;
17469 }
17470
17471 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17472    (which may be different from NAME) to the architecture back-end to allow
17473    it to guess the correct format if necessary.  */
17474
17475 static struct type *
17476 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17477                         const char *name_hint)
17478 {
17479   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17480   const struct floatformat **format;
17481   struct type *type;
17482
17483   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17484   if (format)
17485     type = init_float_type (objfile, bits, name, format);
17486   else
17487     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17488
17489   return type;
17490 }
17491
17492 /* Find a representation of a given base type and install
17493    it in the TYPE field of the die.  */
17494
17495 static struct type *
17496 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17497 {
17498   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17499   struct type *type;
17500   struct attribute *attr;
17501   int encoding = 0, bits = 0;
17502   const char *name;
17503
17504   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17505   if (attr)
17506     {
17507       encoding = DW_UNSND (attr);
17508     }
17509   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17510   if (attr)
17511     {
17512       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17513     }
17514   name = dwarf2_name (die, cu);
17515   if (!name)
17516     {
17517       complaint (&symfile_complaints,
17518                  _("DW_AT_name missing from DW_TAG_base_type"));
17519     }
17520
17521   switch (encoding)
17522     {
17523       case DW_ATE_address:
17524         /* Turn DW_ATE_address into a void * pointer.  */
17525         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17526         type = init_pointer_type (objfile, bits, name, type);
17527         break;
17528       case DW_ATE_boolean:
17529         type = init_boolean_type (objfile, bits, 1, name);
17530         break;
17531       case DW_ATE_complex_float:
17532         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17533         type = init_complex_type (objfile, name, type);
17534         break;
17535       case DW_ATE_decimal_float:
17536         type = init_decfloat_type (objfile, bits, name);
17537         break;
17538       case DW_ATE_float:
17539         type = dwarf2_init_float_type (objfile, bits, name, name);
17540         break;
17541       case DW_ATE_signed:
17542         type = init_integer_type (objfile, bits, 0, name);
17543         break;
17544       case DW_ATE_unsigned:
17545         if (cu->language == language_fortran
17546             && name
17547             && startswith (name, "character("))
17548           type = init_character_type (objfile, bits, 1, name);
17549         else
17550           type = init_integer_type (objfile, bits, 1, name);
17551         break;
17552       case DW_ATE_signed_char:
17553         if (cu->language == language_ada || cu->language == language_m2
17554             || cu->language == language_pascal
17555             || cu->language == language_fortran)
17556           type = init_character_type (objfile, bits, 0, name);
17557         else
17558           type = init_integer_type (objfile, bits, 0, name);
17559         break;
17560       case DW_ATE_unsigned_char:
17561         if (cu->language == language_ada || cu->language == language_m2
17562             || cu->language == language_pascal
17563             || cu->language == language_fortran
17564             || cu->language == language_rust)
17565           type = init_character_type (objfile, bits, 1, name);
17566         else
17567           type = init_integer_type (objfile, bits, 1, name);
17568         break;
17569       case DW_ATE_UTF:
17570         {
17571           gdbarch *arch = get_objfile_arch (objfile);
17572
17573           if (bits == 16)
17574             type = builtin_type (arch)->builtin_char16;
17575           else if (bits == 32)
17576             type = builtin_type (arch)->builtin_char32;
17577           else
17578             {
17579               complaint (&symfile_complaints,
17580                          _("unsupported DW_ATE_UTF bit size: '%d'"),
17581                          bits);
17582               type = init_integer_type (objfile, bits, 1, name);
17583             }
17584           return set_die_type (die, type, cu);
17585         }
17586         break;
17587
17588       default:
17589         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
17590                    dwarf_type_encoding_name (encoding));
17591         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17592         break;
17593     }
17594
17595   if (name && strcmp (name, "char") == 0)
17596     TYPE_NOSIGN (type) = 1;
17597
17598   return set_die_type (die, type, cu);
17599 }
17600
17601 /* Parse dwarf attribute if it's a block, reference or constant and put the
17602    resulting value of the attribute into struct bound_prop.
17603    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17604
17605 static int
17606 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17607                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17608 {
17609   struct dwarf2_property_baton *baton;
17610   struct obstack *obstack
17611     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17612
17613   if (attr == NULL || prop == NULL)
17614     return 0;
17615
17616   if (attr_form_is_block (attr))
17617     {
17618       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17619       baton->referenced_type = NULL;
17620       baton->locexpr.per_cu = cu->per_cu;
17621       baton->locexpr.size = DW_BLOCK (attr)->size;
17622       baton->locexpr.data = DW_BLOCK (attr)->data;
17623       prop->data.baton = baton;
17624       prop->kind = PROP_LOCEXPR;
17625       gdb_assert (prop->data.baton != NULL);
17626     }
17627   else if (attr_form_is_ref (attr))
17628     {
17629       struct dwarf2_cu *target_cu = cu;
17630       struct die_info *target_die;
17631       struct attribute *target_attr;
17632
17633       target_die = follow_die_ref (die, attr, &target_cu);
17634       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17635       if (target_attr == NULL)
17636         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17637                                    target_cu);
17638       if (target_attr == NULL)
17639         return 0;
17640
17641       switch (target_attr->name)
17642         {
17643           case DW_AT_location:
17644             if (attr_form_is_section_offset (target_attr))
17645               {
17646                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17647                 baton->referenced_type = die_type (target_die, target_cu);
17648                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17649                 prop->data.baton = baton;
17650                 prop->kind = PROP_LOCLIST;
17651                 gdb_assert (prop->data.baton != NULL);
17652               }
17653             else if (attr_form_is_block (target_attr))
17654               {
17655                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17656                 baton->referenced_type = die_type (target_die, target_cu);
17657                 baton->locexpr.per_cu = cu->per_cu;
17658                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17659                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17660                 prop->data.baton = baton;
17661                 prop->kind = PROP_LOCEXPR;
17662                 gdb_assert (prop->data.baton != NULL);
17663               }
17664             else
17665               {
17666                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17667                                                        "dynamic property");
17668                 return 0;
17669               }
17670             break;
17671           case DW_AT_data_member_location:
17672             {
17673               LONGEST offset;
17674
17675               if (!handle_data_member_location (target_die, target_cu,
17676                                                 &offset))
17677                 return 0;
17678
17679               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17680               baton->referenced_type = read_type_die (target_die->parent,
17681                                                       target_cu);
17682               baton->offset_info.offset = offset;
17683               baton->offset_info.type = die_type (target_die, target_cu);
17684               prop->data.baton = baton;
17685               prop->kind = PROP_ADDR_OFFSET;
17686               break;
17687             }
17688         }
17689     }
17690   else if (attr_form_is_constant (attr))
17691     {
17692       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17693       prop->kind = PROP_CONST;
17694     }
17695   else
17696     {
17697       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17698                                              dwarf2_name (die, cu));
17699       return 0;
17700     }
17701
17702   return 1;
17703 }
17704
17705 /* Read the given DW_AT_subrange DIE.  */
17706
17707 static struct type *
17708 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17709 {
17710   struct type *base_type, *orig_base_type;
17711   struct type *range_type;
17712   struct attribute *attr;
17713   struct dynamic_prop low, high;
17714   int low_default_is_valid;
17715   int high_bound_is_count = 0;
17716   const char *name;
17717   LONGEST negative_mask;
17718
17719   orig_base_type = die_type (die, cu);
17720   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17721      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17722      creating the range type, but we use the result of check_typedef
17723      when examining properties of the type.  */
17724   base_type = check_typedef (orig_base_type);
17725
17726   /* The die_type call above may have already set the type for this DIE.  */
17727   range_type = get_die_type (die, cu);
17728   if (range_type)
17729     return range_type;
17730
17731   low.kind = PROP_CONST;
17732   high.kind = PROP_CONST;
17733   high.data.const_val = 0;
17734
17735   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17736      omitting DW_AT_lower_bound.  */
17737   switch (cu->language)
17738     {
17739     case language_c:
17740     case language_cplus:
17741       low.data.const_val = 0;
17742       low_default_is_valid = 1;
17743       break;
17744     case language_fortran:
17745       low.data.const_val = 1;
17746       low_default_is_valid = 1;
17747       break;
17748     case language_d:
17749     case language_objc:
17750     case language_rust:
17751       low.data.const_val = 0;
17752       low_default_is_valid = (cu->header.version >= 4);
17753       break;
17754     case language_ada:
17755     case language_m2:
17756     case language_pascal:
17757       low.data.const_val = 1;
17758       low_default_is_valid = (cu->header.version >= 4);
17759       break;
17760     default:
17761       low.data.const_val = 0;
17762       low_default_is_valid = 0;
17763       break;
17764     }
17765
17766   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17767   if (attr)
17768     attr_to_dynamic_prop (attr, die, cu, &low);
17769   else if (!low_default_is_valid)
17770     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
17771                                       "- DIE at 0x%x [in module %s]"),
17772                to_underlying (die->sect_off),
17773                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17774
17775   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17776   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17777     {
17778       attr = dwarf2_attr (die, DW_AT_count, cu);
17779       if (attr_to_dynamic_prop (attr, die, cu, &high))
17780         {
17781           /* If bounds are constant do the final calculation here.  */
17782           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17783             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17784           else
17785             high_bound_is_count = 1;
17786         }
17787     }
17788
17789   /* Dwarf-2 specifications explicitly allows to create subrange types
17790      without specifying a base type.
17791      In that case, the base type must be set to the type of
17792      the lower bound, upper bound or count, in that order, if any of these
17793      three attributes references an object that has a type.
17794      If no base type is found, the Dwarf-2 specifications say that
17795      a signed integer type of size equal to the size of an address should
17796      be used.
17797      For the following C code: `extern char gdb_int [];'
17798      GCC produces an empty range DIE.
17799      FIXME: muller/2010-05-28: Possible references to object for low bound,
17800      high bound or count are not yet handled by this code.  */
17801   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17802     {
17803       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17804       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17805       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17806       struct type *int_type = objfile_type (objfile)->builtin_int;
17807
17808       /* Test "int", "long int", and "long long int" objfile types,
17809          and select the first one having a size above or equal to the
17810          architecture address size.  */
17811       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17812         base_type = int_type;
17813       else
17814         {
17815           int_type = objfile_type (objfile)->builtin_long;
17816           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17817             base_type = int_type;
17818           else
17819             {
17820               int_type = objfile_type (objfile)->builtin_long_long;
17821               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17822                 base_type = int_type;
17823             }
17824         }
17825     }
17826
17827   /* Normally, the DWARF producers are expected to use a signed
17828      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17829      But this is unfortunately not always the case, as witnessed
17830      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17831      is used instead.  To work around that ambiguity, we treat
17832      the bounds as signed, and thus sign-extend their values, when
17833      the base type is signed.  */
17834   negative_mask =
17835     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17836   if (low.kind == PROP_CONST
17837       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17838     low.data.const_val |= negative_mask;
17839   if (high.kind == PROP_CONST
17840       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17841     high.data.const_val |= negative_mask;
17842
17843   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17844
17845   if (high_bound_is_count)
17846     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17847
17848   /* Ada expects an empty array on no boundary attributes.  */
17849   if (attr == NULL && cu->language != language_ada)
17850     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17851
17852   name = dwarf2_name (die, cu);
17853   if (name)
17854     TYPE_NAME (range_type) = name;
17855
17856   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17857   if (attr)
17858     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17859
17860   set_die_type (die, range_type, cu);
17861
17862   /* set_die_type should be already done.  */
17863   set_descriptive_type (range_type, die, cu);
17864
17865   return range_type;
17866 }
17867
17868 static struct type *
17869 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17870 {
17871   struct type *type;
17872
17873   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17874                     NULL);
17875   TYPE_NAME (type) = dwarf2_name (die, cu);
17876
17877   /* In Ada, an unspecified type is typically used when the description
17878      of the type is defered to a different unit.  When encountering
17879      such a type, we treat it as a stub, and try to resolve it later on,
17880      when needed.  */
17881   if (cu->language == language_ada)
17882     TYPE_STUB (type) = 1;
17883
17884   return set_die_type (die, type, cu);
17885 }
17886
17887 /* Read a single die and all its descendents.  Set the die's sibling
17888    field to NULL; set other fields in the die correctly, and set all
17889    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17890    location of the info_ptr after reading all of those dies.  PARENT
17891    is the parent of the die in question.  */
17892
17893 static struct die_info *
17894 read_die_and_children (const struct die_reader_specs *reader,
17895                        const gdb_byte *info_ptr,
17896                        const gdb_byte **new_info_ptr,
17897                        struct die_info *parent)
17898 {
17899   struct die_info *die;
17900   const gdb_byte *cur_ptr;
17901   int has_children;
17902
17903   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17904   if (die == NULL)
17905     {
17906       *new_info_ptr = cur_ptr;
17907       return NULL;
17908     }
17909   store_in_ref_table (die, reader->cu);
17910
17911   if (has_children)
17912     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17913   else
17914     {
17915       die->child = NULL;
17916       *new_info_ptr = cur_ptr;
17917     }
17918
17919   die->sibling = NULL;
17920   die->parent = parent;
17921   return die;
17922 }
17923
17924 /* Read a die, all of its descendents, and all of its siblings; set
17925    all of the fields of all of the dies correctly.  Arguments are as
17926    in read_die_and_children.  */
17927
17928 static struct die_info *
17929 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17930                          const gdb_byte *info_ptr,
17931                          const gdb_byte **new_info_ptr,
17932                          struct die_info *parent)
17933 {
17934   struct die_info *first_die, *last_sibling;
17935   const gdb_byte *cur_ptr;
17936
17937   cur_ptr = info_ptr;
17938   first_die = last_sibling = NULL;
17939
17940   while (1)
17941     {
17942       struct die_info *die
17943         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17944
17945       if (die == NULL)
17946         {
17947           *new_info_ptr = cur_ptr;
17948           return first_die;
17949         }
17950
17951       if (!first_die)
17952         first_die = die;
17953       else
17954         last_sibling->sibling = die;
17955
17956       last_sibling = die;
17957     }
17958 }
17959
17960 /* Read a die, all of its descendents, and all of its siblings; set
17961    all of the fields of all of the dies correctly.  Arguments are as
17962    in read_die_and_children.
17963    This the main entry point for reading a DIE and all its children.  */
17964
17965 static struct die_info *
17966 read_die_and_siblings (const struct die_reader_specs *reader,
17967                        const gdb_byte *info_ptr,
17968                        const gdb_byte **new_info_ptr,
17969                        struct die_info *parent)
17970 {
17971   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17972                                                   new_info_ptr, parent);
17973
17974   if (dwarf_die_debug)
17975     {
17976       fprintf_unfiltered (gdb_stdlog,
17977                           "Read die from %s@0x%x of %s:\n",
17978                           get_section_name (reader->die_section),
17979                           (unsigned) (info_ptr - reader->die_section->buffer),
17980                           bfd_get_filename (reader->abfd));
17981       dump_die (die, dwarf_die_debug);
17982     }
17983
17984   return die;
17985 }
17986
17987 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17988    attributes.
17989    The caller is responsible for filling in the extra attributes
17990    and updating (*DIEP)->num_attrs.
17991    Set DIEP to point to a newly allocated die with its information,
17992    except for its child, sibling, and parent fields.
17993    Set HAS_CHILDREN to tell whether the die has children or not.  */
17994
17995 static const gdb_byte *
17996 read_full_die_1 (const struct die_reader_specs *reader,
17997                  struct die_info **diep, const gdb_byte *info_ptr,
17998                  int *has_children, int num_extra_attrs)
17999 {
18000   unsigned int abbrev_number, bytes_read, i;
18001   struct abbrev_info *abbrev;
18002   struct die_info *die;
18003   struct dwarf2_cu *cu = reader->cu;
18004   bfd *abfd = reader->abfd;
18005
18006   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
18007   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18008   info_ptr += bytes_read;
18009   if (!abbrev_number)
18010     {
18011       *diep = NULL;
18012       *has_children = 0;
18013       return info_ptr;
18014     }
18015
18016   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
18017   if (!abbrev)
18018     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
18019            abbrev_number,
18020            bfd_get_filename (abfd));
18021
18022   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
18023   die->sect_off = sect_off;
18024   die->tag = abbrev->tag;
18025   die->abbrev = abbrev_number;
18026
18027   /* Make the result usable.
18028      The caller needs to update num_attrs after adding the extra
18029      attributes.  */
18030   die->num_attrs = abbrev->num_attrs;
18031
18032   for (i = 0; i < abbrev->num_attrs; ++i)
18033     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
18034                                info_ptr);
18035
18036   *diep = die;
18037   *has_children = abbrev->has_children;
18038   return info_ptr;
18039 }
18040
18041 /* Read a die and all its attributes.
18042    Set DIEP to point to a newly allocated die with its information,
18043    except for its child, sibling, and parent fields.
18044    Set HAS_CHILDREN to tell whether the die has children or not.  */
18045
18046 static const gdb_byte *
18047 read_full_die (const struct die_reader_specs *reader,
18048                struct die_info **diep, const gdb_byte *info_ptr,
18049                int *has_children)
18050 {
18051   const gdb_byte *result;
18052
18053   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
18054
18055   if (dwarf_die_debug)
18056     {
18057       fprintf_unfiltered (gdb_stdlog,
18058                           "Read die from %s@0x%x of %s:\n",
18059                           get_section_name (reader->die_section),
18060                           (unsigned) (info_ptr - reader->die_section->buffer),
18061                           bfd_get_filename (reader->abfd));
18062       dump_die (*diep, dwarf_die_debug);
18063     }
18064
18065   return result;
18066 }
18067 \f
18068 /* Abbreviation tables.
18069
18070    In DWARF version 2, the description of the debugging information is
18071    stored in a separate .debug_abbrev section.  Before we read any
18072    dies from a section we read in all abbreviations and install them
18073    in a hash table.  */
18074
18075 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18076
18077 static struct abbrev_info *
18078 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
18079 {
18080   struct abbrev_info *abbrev;
18081
18082   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
18083   memset (abbrev, 0, sizeof (struct abbrev_info));
18084
18085   return abbrev;
18086 }
18087
18088 /* Add an abbreviation to the table.  */
18089
18090 static void
18091 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
18092                          unsigned int abbrev_number,
18093                          struct abbrev_info *abbrev)
18094 {
18095   unsigned int hash_number;
18096
18097   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18098   abbrev->next = abbrev_table->abbrevs[hash_number];
18099   abbrev_table->abbrevs[hash_number] = abbrev;
18100 }
18101
18102 /* Look up an abbrev in the table.
18103    Returns NULL if the abbrev is not found.  */
18104
18105 static struct abbrev_info *
18106 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
18107                             unsigned int abbrev_number)
18108 {
18109   unsigned int hash_number;
18110   struct abbrev_info *abbrev;
18111
18112   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18113   abbrev = abbrev_table->abbrevs[hash_number];
18114
18115   while (abbrev)
18116     {
18117       if (abbrev->number == abbrev_number)
18118         return abbrev;
18119       abbrev = abbrev->next;
18120     }
18121   return NULL;
18122 }
18123
18124 /* Read in an abbrev table.  */
18125
18126 static struct abbrev_table *
18127 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18128                          struct dwarf2_section_info *section,
18129                          sect_offset sect_off)
18130 {
18131   struct objfile *objfile = dwarf2_per_objfile->objfile;
18132   bfd *abfd = get_section_bfd_owner (section);
18133   struct abbrev_table *abbrev_table;
18134   const gdb_byte *abbrev_ptr;
18135   struct abbrev_info *cur_abbrev;
18136   unsigned int abbrev_number, bytes_read, abbrev_name;
18137   unsigned int abbrev_form;
18138   struct attr_abbrev *cur_attrs;
18139   unsigned int allocated_attrs;
18140
18141   abbrev_table = XNEW (struct abbrev_table);
18142   abbrev_table->sect_off = sect_off;
18143   obstack_init (&abbrev_table->abbrev_obstack);
18144   abbrev_table->abbrevs =
18145     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
18146                ABBREV_HASH_SIZE);
18147   memset (abbrev_table->abbrevs, 0,
18148           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
18149
18150   dwarf2_read_section (objfile, section);
18151   abbrev_ptr = section->buffer + to_underlying (sect_off);
18152   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18153   abbrev_ptr += bytes_read;
18154
18155   allocated_attrs = ATTR_ALLOC_CHUNK;
18156   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18157
18158   /* Loop until we reach an abbrev number of 0.  */
18159   while (abbrev_number)
18160     {
18161       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
18162
18163       /* read in abbrev header */
18164       cur_abbrev->number = abbrev_number;
18165       cur_abbrev->tag
18166         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18167       abbrev_ptr += bytes_read;
18168       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18169       abbrev_ptr += 1;
18170
18171       /* now read in declarations */
18172       for (;;)
18173         {
18174           LONGEST implicit_const;
18175
18176           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18177           abbrev_ptr += bytes_read;
18178           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18179           abbrev_ptr += bytes_read;
18180           if (abbrev_form == DW_FORM_implicit_const)
18181             {
18182               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18183                                                    &bytes_read);
18184               abbrev_ptr += bytes_read;
18185             }
18186           else
18187             {
18188               /* Initialize it due to a false compiler warning.  */
18189               implicit_const = -1;
18190             }
18191
18192           if (abbrev_name == 0)
18193             break;
18194
18195           if (cur_abbrev->num_attrs == allocated_attrs)
18196             {
18197               allocated_attrs += ATTR_ALLOC_CHUNK;
18198               cur_attrs
18199                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18200             }
18201
18202           cur_attrs[cur_abbrev->num_attrs].name
18203             = (enum dwarf_attribute) abbrev_name;
18204           cur_attrs[cur_abbrev->num_attrs].form
18205             = (enum dwarf_form) abbrev_form;
18206           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18207           ++cur_abbrev->num_attrs;
18208         }
18209
18210       cur_abbrev->attrs =
18211         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18212                    cur_abbrev->num_attrs);
18213       memcpy (cur_abbrev->attrs, cur_attrs,
18214               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18215
18216       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
18217
18218       /* Get next abbreviation.
18219          Under Irix6 the abbreviations for a compilation unit are not
18220          always properly terminated with an abbrev number of 0.
18221          Exit loop if we encounter an abbreviation which we have
18222          already read (which means we are about to read the abbreviations
18223          for the next compile unit) or if the end of the abbreviation
18224          table is reached.  */
18225       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18226         break;
18227       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18228       abbrev_ptr += bytes_read;
18229       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
18230         break;
18231     }
18232
18233   xfree (cur_attrs);
18234   return abbrev_table;
18235 }
18236
18237 /* Free the resources held by ABBREV_TABLE.  */
18238
18239 static void
18240 abbrev_table_free (struct abbrev_table *abbrev_table)
18241 {
18242   obstack_free (&abbrev_table->abbrev_obstack, NULL);
18243   xfree (abbrev_table);
18244 }
18245
18246 /* Same as abbrev_table_free but as a cleanup.
18247    We pass in a pointer to the pointer to the table so that we can
18248    set the pointer to NULL when we're done.  It also simplifies
18249    build_type_psymtabs_1.  */
18250
18251 static void
18252 abbrev_table_free_cleanup (void *table_ptr)
18253 {
18254   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
18255
18256   if (*abbrev_table_ptr != NULL)
18257     abbrev_table_free (*abbrev_table_ptr);
18258   *abbrev_table_ptr = NULL;
18259 }
18260
18261 /* Read the abbrev table for CU from ABBREV_SECTION.  */
18262
18263 static void
18264 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
18265                      struct dwarf2_section_info *abbrev_section)
18266 {
18267   cu->abbrev_table =
18268     abbrev_table_read_table (cu->per_cu->dwarf2_per_objfile, abbrev_section,
18269                              cu->header.abbrev_sect_off);
18270 }
18271
18272 /* Release the memory used by the abbrev table for a compilation unit.  */
18273
18274 static void
18275 dwarf2_free_abbrev_table (void *ptr_to_cu)
18276 {
18277   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
18278
18279   if (cu->abbrev_table != NULL)
18280     abbrev_table_free (cu->abbrev_table);
18281   /* Set this to NULL so that we SEGV if we try to read it later,
18282      and also because free_comp_unit verifies this is NULL.  */
18283   cu->abbrev_table = NULL;
18284 }
18285 \f
18286 /* Returns nonzero if TAG represents a type that we might generate a partial
18287    symbol for.  */
18288
18289 static int
18290 is_type_tag_for_partial (int tag)
18291 {
18292   switch (tag)
18293     {
18294 #if 0
18295     /* Some types that would be reasonable to generate partial symbols for,
18296        that we don't at present.  */
18297     case DW_TAG_array_type:
18298     case DW_TAG_file_type:
18299     case DW_TAG_ptr_to_member_type:
18300     case DW_TAG_set_type:
18301     case DW_TAG_string_type:
18302     case DW_TAG_subroutine_type:
18303 #endif
18304     case DW_TAG_base_type:
18305     case DW_TAG_class_type:
18306     case DW_TAG_interface_type:
18307     case DW_TAG_enumeration_type:
18308     case DW_TAG_structure_type:
18309     case DW_TAG_subrange_type:
18310     case DW_TAG_typedef:
18311     case DW_TAG_union_type:
18312       return 1;
18313     default:
18314       return 0;
18315     }
18316 }
18317
18318 /* Load all DIEs that are interesting for partial symbols into memory.  */
18319
18320 static struct partial_die_info *
18321 load_partial_dies (const struct die_reader_specs *reader,
18322                    const gdb_byte *info_ptr, int building_psymtab)
18323 {
18324   struct dwarf2_cu *cu = reader->cu;
18325   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18326   struct partial_die_info *part_die;
18327   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18328   struct abbrev_info *abbrev;
18329   unsigned int bytes_read;
18330   unsigned int load_all = 0;
18331   int nesting_level = 1;
18332
18333   parent_die = NULL;
18334   last_die = NULL;
18335
18336   gdb_assert (cu->per_cu != NULL);
18337   if (cu->per_cu->load_all_dies)
18338     load_all = 1;
18339
18340   cu->partial_dies
18341     = htab_create_alloc_ex (cu->header.length / 12,
18342                             partial_die_hash,
18343                             partial_die_eq,
18344                             NULL,
18345                             &cu->comp_unit_obstack,
18346                             hashtab_obstack_allocate,
18347                             dummy_obstack_deallocate);
18348
18349   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18350
18351   while (1)
18352     {
18353       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
18354
18355       /* A NULL abbrev means the end of a series of children.  */
18356       if (abbrev == NULL)
18357         {
18358           if (--nesting_level == 0)
18359             {
18360               /* PART_DIE was probably the last thing allocated on the
18361                  comp_unit_obstack, so we could call obstack_free
18362                  here.  We don't do that because the waste is small,
18363                  and will be cleaned up when we're done with this
18364                  compilation unit.  This way, we're also more robust
18365                  against other users of the comp_unit_obstack.  */
18366               return first_die;
18367             }
18368           info_ptr += bytes_read;
18369           last_die = parent_die;
18370           parent_die = parent_die->die_parent;
18371           continue;
18372         }
18373
18374       /* Check for template arguments.  We never save these; if
18375          they're seen, we just mark the parent, and go on our way.  */
18376       if (parent_die != NULL
18377           && cu->language == language_cplus
18378           && (abbrev->tag == DW_TAG_template_type_param
18379               || abbrev->tag == DW_TAG_template_value_param))
18380         {
18381           parent_die->has_template_arguments = 1;
18382
18383           if (!load_all)
18384             {
18385               /* We don't need a partial DIE for the template argument.  */
18386               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18387               continue;
18388             }
18389         }
18390
18391       /* We only recurse into c++ subprograms looking for template arguments.
18392          Skip their other children.  */
18393       if (!load_all
18394           && cu->language == language_cplus
18395           && parent_die != NULL
18396           && parent_die->tag == DW_TAG_subprogram)
18397         {
18398           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18399           continue;
18400         }
18401
18402       /* Check whether this DIE is interesting enough to save.  Normally
18403          we would not be interested in members here, but there may be
18404          later variables referencing them via DW_AT_specification (for
18405          static members).  */
18406       if (!load_all
18407           && !is_type_tag_for_partial (abbrev->tag)
18408           && abbrev->tag != DW_TAG_constant
18409           && abbrev->tag != DW_TAG_enumerator
18410           && abbrev->tag != DW_TAG_subprogram
18411           && abbrev->tag != DW_TAG_inlined_subroutine
18412           && abbrev->tag != DW_TAG_lexical_block
18413           && abbrev->tag != DW_TAG_variable
18414           && abbrev->tag != DW_TAG_namespace
18415           && abbrev->tag != DW_TAG_module
18416           && abbrev->tag != DW_TAG_member
18417           && abbrev->tag != DW_TAG_imported_unit
18418           && abbrev->tag != DW_TAG_imported_declaration)
18419         {
18420           /* Otherwise we skip to the next sibling, if any.  */
18421           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18422           continue;
18423         }
18424
18425       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
18426                                    info_ptr);
18427
18428       /* This two-pass algorithm for processing partial symbols has a
18429          high cost in cache pressure.  Thus, handle some simple cases
18430          here which cover the majority of C partial symbols.  DIEs
18431          which neither have specification tags in them, nor could have
18432          specification tags elsewhere pointing at them, can simply be
18433          processed and discarded.
18434
18435          This segment is also optional; scan_partial_symbols and
18436          add_partial_symbol will handle these DIEs if we chain
18437          them in normally.  When compilers which do not emit large
18438          quantities of duplicate debug information are more common,
18439          this code can probably be removed.  */
18440
18441       /* Any complete simple types at the top level (pretty much all
18442          of them, for a language without namespaces), can be processed
18443          directly.  */
18444       if (parent_die == NULL
18445           && part_die->has_specification == 0
18446           && part_die->is_declaration == 0
18447           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
18448               || part_die->tag == DW_TAG_base_type
18449               || part_die->tag == DW_TAG_subrange_type))
18450         {
18451           if (building_psymtab && part_die->name != NULL)
18452             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18453                                  VAR_DOMAIN, LOC_TYPEDEF,
18454                                  &objfile->static_psymbols,
18455                                  0, cu->language, objfile);
18456           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18457           continue;
18458         }
18459
18460       /* The exception for DW_TAG_typedef with has_children above is
18461          a workaround of GCC PR debug/47510.  In the case of this complaint
18462          type_name_no_tag_or_error will error on such types later.
18463
18464          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18465          it could not find the child DIEs referenced later, this is checked
18466          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18467
18468       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
18469         complaint (&symfile_complaints,
18470                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18471                      "- DIE at 0x%x [in module %s]"),
18472                    to_underlying (part_die->sect_off), objfile_name (objfile));
18473
18474       /* If we're at the second level, and we're an enumerator, and
18475          our parent has no specification (meaning possibly lives in a
18476          namespace elsewhere), then we can add the partial symbol now
18477          instead of queueing it.  */
18478       if (part_die->tag == DW_TAG_enumerator
18479           && parent_die != NULL
18480           && parent_die->die_parent == NULL
18481           && parent_die->tag == DW_TAG_enumeration_type
18482           && parent_die->has_specification == 0)
18483         {
18484           if (part_die->name == NULL)
18485             complaint (&symfile_complaints,
18486                        _("malformed enumerator DIE ignored"));
18487           else if (building_psymtab)
18488             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
18489                                  VAR_DOMAIN, LOC_CONST,
18490                                  cu->language == language_cplus
18491                                  ? &objfile->global_psymbols
18492                                  : &objfile->static_psymbols,
18493                                  0, cu->language, objfile);
18494
18495           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
18496           continue;
18497         }
18498
18499       /* We'll save this DIE so link it in.  */
18500       part_die->die_parent = parent_die;
18501       part_die->die_sibling = NULL;
18502       part_die->die_child = NULL;
18503
18504       if (last_die && last_die == parent_die)
18505         last_die->die_child = part_die;
18506       else if (last_die)
18507         last_die->die_sibling = part_die;
18508
18509       last_die = part_die;
18510
18511       if (first_die == NULL)
18512         first_die = part_die;
18513
18514       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18515          find interesting need to be in the hash table, because we
18516          also have the parent/sibling/child chains; only those that we
18517          might refer to by offset later during partial symbol reading.
18518
18519          For now this means things that might have be the target of a
18520          DW_AT_specification, DW_AT_abstract_origin, or
18521          DW_AT_extension.  DW_AT_extension will refer only to
18522          namespaces; DW_AT_abstract_origin refers to functions (and
18523          many things under the function DIE, but we do not recurse
18524          into function DIEs during partial symbol reading) and
18525          possibly variables as well; DW_AT_specification refers to
18526          declarations.  Declarations ought to have the DW_AT_declaration
18527          flag.  It happens that GCC forgets to put it in sometimes, but
18528          only for functions, not for types.
18529
18530          Adding more things than necessary to the hash table is harmless
18531          except for the performance cost.  Adding too few will result in
18532          wasted time in find_partial_die, when we reread the compilation
18533          unit with load_all_dies set.  */
18534
18535       if (load_all
18536           || abbrev->tag == DW_TAG_constant
18537           || abbrev->tag == DW_TAG_subprogram
18538           || abbrev->tag == DW_TAG_variable
18539           || abbrev->tag == DW_TAG_namespace
18540           || part_die->is_declaration)
18541         {
18542           void **slot;
18543
18544           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18545                                            to_underlying (part_die->sect_off),
18546                                            INSERT);
18547           *slot = part_die;
18548         }
18549
18550       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
18551
18552       /* For some DIEs we want to follow their children (if any).  For C
18553          we have no reason to follow the children of structures; for other
18554          languages we have to, so that we can get at method physnames
18555          to infer fully qualified class names, for DW_AT_specification,
18556          and for C++ template arguments.  For C++, we also look one level
18557          inside functions to find template arguments (if the name of the
18558          function does not already contain the template arguments).
18559
18560          For Ada, we need to scan the children of subprograms and lexical
18561          blocks as well because Ada allows the definition of nested
18562          entities that could be interesting for the debugger, such as
18563          nested subprograms for instance.  */
18564       if (last_die->has_children
18565           && (load_all
18566               || last_die->tag == DW_TAG_namespace
18567               || last_die->tag == DW_TAG_module
18568               || last_die->tag == DW_TAG_enumeration_type
18569               || (cu->language == language_cplus
18570                   && last_die->tag == DW_TAG_subprogram
18571                   && (last_die->name == NULL
18572                       || strchr (last_die->name, '<') == NULL))
18573               || (cu->language != language_c
18574                   && (last_die->tag == DW_TAG_class_type
18575                       || last_die->tag == DW_TAG_interface_type
18576                       || last_die->tag == DW_TAG_structure_type
18577                       || last_die->tag == DW_TAG_union_type))
18578               || (cu->language == language_ada
18579                   && (last_die->tag == DW_TAG_subprogram
18580                       || last_die->tag == DW_TAG_lexical_block))))
18581         {
18582           nesting_level++;
18583           parent_die = last_die;
18584           continue;
18585         }
18586
18587       /* Otherwise we skip to the next sibling, if any.  */
18588       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18589
18590       /* Back to the top, do it again.  */
18591     }
18592 }
18593
18594 /* Read a minimal amount of information into the minimal die structure.  */
18595
18596 static const gdb_byte *
18597 read_partial_die (const struct die_reader_specs *reader,
18598                   struct partial_die_info *part_die,
18599                   struct abbrev_info *abbrev, unsigned int abbrev_len,
18600                   const gdb_byte *info_ptr)
18601 {
18602   struct dwarf2_cu *cu = reader->cu;
18603   struct dwarf2_per_objfile *dwarf2_per_objfile
18604     = cu->per_cu->dwarf2_per_objfile;
18605   struct objfile *objfile = dwarf2_per_objfile->objfile;
18606   const gdb_byte *buffer = reader->buffer;
18607   unsigned int i;
18608   struct attribute attr;
18609   int has_low_pc_attr = 0;
18610   int has_high_pc_attr = 0;
18611   int high_pc_relative = 0;
18612
18613   memset (part_die, 0, sizeof (struct partial_die_info));
18614
18615   part_die->sect_off = (sect_offset) (info_ptr - buffer);
18616
18617   info_ptr += abbrev_len;
18618
18619   if (abbrev == NULL)
18620     return info_ptr;
18621
18622   part_die->tag = abbrev->tag;
18623   part_die->has_children = abbrev->has_children;
18624
18625   for (i = 0; i < abbrev->num_attrs; ++i)
18626     {
18627       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
18628
18629       /* Store the data if it is of an attribute we want to keep in a
18630          partial symbol table.  */
18631       switch (attr.name)
18632         {
18633         case DW_AT_name:
18634           switch (part_die->tag)
18635             {
18636             case DW_TAG_compile_unit:
18637             case DW_TAG_partial_unit:
18638             case DW_TAG_type_unit:
18639               /* Compilation units have a DW_AT_name that is a filename, not
18640                  a source language identifier.  */
18641             case DW_TAG_enumeration_type:
18642             case DW_TAG_enumerator:
18643               /* These tags always have simple identifiers already; no need
18644                  to canonicalize them.  */
18645               part_die->name = DW_STRING (&attr);
18646               break;
18647             default:
18648               part_die->name
18649                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18650                                             &objfile->per_bfd->storage_obstack);
18651               break;
18652             }
18653           break;
18654         case DW_AT_linkage_name:
18655         case DW_AT_MIPS_linkage_name:
18656           /* Note that both forms of linkage name might appear.  We
18657              assume they will be the same, and we only store the last
18658              one we see.  */
18659           if (cu->language == language_ada)
18660             part_die->name = DW_STRING (&attr);
18661           part_die->linkage_name = DW_STRING (&attr);
18662           break;
18663         case DW_AT_low_pc:
18664           has_low_pc_attr = 1;
18665           part_die->lowpc = attr_value_as_address (&attr);
18666           break;
18667         case DW_AT_high_pc:
18668           has_high_pc_attr = 1;
18669           part_die->highpc = attr_value_as_address (&attr);
18670           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18671                 high_pc_relative = 1;
18672           break;
18673         case DW_AT_location:
18674           /* Support the .debug_loc offsets.  */
18675           if (attr_form_is_block (&attr))
18676             {
18677                part_die->d.locdesc = DW_BLOCK (&attr);
18678             }
18679           else if (attr_form_is_section_offset (&attr))
18680             {
18681               dwarf2_complex_location_expr_complaint ();
18682             }
18683           else
18684             {
18685               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18686                                                      "partial symbol information");
18687             }
18688           break;
18689         case DW_AT_external:
18690           part_die->is_external = DW_UNSND (&attr);
18691           break;
18692         case DW_AT_declaration:
18693           part_die->is_declaration = DW_UNSND (&attr);
18694           break;
18695         case DW_AT_type:
18696           part_die->has_type = 1;
18697           break;
18698         case DW_AT_abstract_origin:
18699         case DW_AT_specification:
18700         case DW_AT_extension:
18701           part_die->has_specification = 1;
18702           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
18703           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18704                                    || cu->per_cu->is_dwz);
18705           break;
18706         case DW_AT_sibling:
18707           /* Ignore absolute siblings, they might point outside of
18708              the current compile unit.  */
18709           if (attr.form == DW_FORM_ref_addr)
18710             complaint (&symfile_complaints,
18711                        _("ignoring absolute DW_AT_sibling"));
18712           else
18713             {
18714               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18715               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18716
18717               if (sibling_ptr < info_ptr)
18718                 complaint (&symfile_complaints,
18719                            _("DW_AT_sibling points backwards"));
18720               else if (sibling_ptr > reader->buffer_end)
18721                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18722               else
18723                 part_die->sibling = sibling_ptr;
18724             }
18725           break;
18726         case DW_AT_byte_size:
18727           part_die->has_byte_size = 1;
18728           break;
18729         case DW_AT_const_value:
18730           part_die->has_const_value = 1;
18731           break;
18732         case DW_AT_calling_convention:
18733           /* DWARF doesn't provide a way to identify a program's source-level
18734              entry point.  DW_AT_calling_convention attributes are only meant
18735              to describe functions' calling conventions.
18736
18737              However, because it's a necessary piece of information in
18738              Fortran, and before DWARF 4 DW_CC_program was the only
18739              piece of debugging information whose definition refers to
18740              a 'main program' at all, several compilers marked Fortran
18741              main programs with DW_CC_program --- even when those
18742              functions use the standard calling conventions.
18743
18744              Although DWARF now specifies a way to provide this
18745              information, we support this practice for backward
18746              compatibility.  */
18747           if (DW_UNSND (&attr) == DW_CC_program
18748               && cu->language == language_fortran)
18749             part_die->main_subprogram = 1;
18750           break;
18751         case DW_AT_inline:
18752           if (DW_UNSND (&attr) == DW_INL_inlined
18753               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18754             part_die->may_be_inlined = 1;
18755           break;
18756
18757         case DW_AT_import:
18758           if (part_die->tag == DW_TAG_imported_unit)
18759             {
18760               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
18761               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18762                                   || cu->per_cu->is_dwz);
18763             }
18764           break;
18765
18766         case DW_AT_main_subprogram:
18767           part_die->main_subprogram = DW_UNSND (&attr);
18768           break;
18769
18770         default:
18771           break;
18772         }
18773     }
18774
18775   if (high_pc_relative)
18776     part_die->highpc += part_die->lowpc;
18777
18778   if (has_low_pc_attr && has_high_pc_attr)
18779     {
18780       /* When using the GNU linker, .gnu.linkonce. sections are used to
18781          eliminate duplicate copies of functions and vtables and such.
18782          The linker will arbitrarily choose one and discard the others.
18783          The AT_*_pc values for such functions refer to local labels in
18784          these sections.  If the section from that file was discarded, the
18785          labels are not in the output, so the relocs get a value of 0.
18786          If this is a discarded function, mark the pc bounds as invalid,
18787          so that GDB will ignore it.  */
18788       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18789         {
18790           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18791
18792           complaint (&symfile_complaints,
18793                      _("DW_AT_low_pc %s is zero "
18794                        "for DIE at 0x%x [in module %s]"),
18795                      paddress (gdbarch, part_die->lowpc),
18796                      to_underlying (part_die->sect_off), objfile_name (objfile));
18797         }
18798       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18799       else if (part_die->lowpc >= part_die->highpc)
18800         {
18801           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18802
18803           complaint (&symfile_complaints,
18804                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18805                        "for DIE at 0x%x [in module %s]"),
18806                      paddress (gdbarch, part_die->lowpc),
18807                      paddress (gdbarch, part_die->highpc),
18808                      to_underlying (part_die->sect_off),
18809                      objfile_name (objfile));
18810         }
18811       else
18812         part_die->has_pc_info = 1;
18813     }
18814
18815   return info_ptr;
18816 }
18817
18818 /* Find a cached partial DIE at OFFSET in CU.  */
18819
18820 static struct partial_die_info *
18821 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
18822 {
18823   struct partial_die_info *lookup_die = NULL;
18824   struct partial_die_info part_die;
18825
18826   part_die.sect_off = sect_off;
18827   lookup_die = ((struct partial_die_info *)
18828                 htab_find_with_hash (cu->partial_dies, &part_die,
18829                                      to_underlying (sect_off)));
18830
18831   return lookup_die;
18832 }
18833
18834 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18835    except in the case of .debug_types DIEs which do not reference
18836    outside their CU (they do however referencing other types via
18837    DW_FORM_ref_sig8).  */
18838
18839 static struct partial_die_info *
18840 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18841 {
18842   struct dwarf2_per_objfile *dwarf2_per_objfile
18843     = cu->per_cu->dwarf2_per_objfile;
18844   struct objfile *objfile = dwarf2_per_objfile->objfile;
18845   struct dwarf2_per_cu_data *per_cu = NULL;
18846   struct partial_die_info *pd = NULL;
18847
18848   if (offset_in_dwz == cu->per_cu->is_dwz
18849       && offset_in_cu_p (&cu->header, sect_off))
18850     {
18851       pd = find_partial_die_in_comp_unit (sect_off, cu);
18852       if (pd != NULL)
18853         return pd;
18854       /* We missed recording what we needed.
18855          Load all dies and try again.  */
18856       per_cu = cu->per_cu;
18857     }
18858   else
18859     {
18860       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18861       if (cu->per_cu->is_debug_types)
18862         {
18863           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
18864                    " external reference to offset 0x%x [in module %s].\n"),
18865                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
18866                  bfd_get_filename (objfile->obfd));
18867         }
18868       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18869                                                  dwarf2_per_objfile);
18870
18871       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18872         load_partial_comp_unit (per_cu);
18873
18874       per_cu->cu->last_used = 0;
18875       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18876     }
18877
18878   /* If we didn't find it, and not all dies have been loaded,
18879      load them all and try again.  */
18880
18881   if (pd == NULL && per_cu->load_all_dies == 0)
18882     {
18883       per_cu->load_all_dies = 1;
18884
18885       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18886          THIS_CU->cu may already be in use.  So we can't just free it and
18887          replace its DIEs with the ones we read in.  Instead, we leave those
18888          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18889          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18890          set.  */
18891       load_partial_comp_unit (per_cu);
18892
18893       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
18894     }
18895
18896   if (pd == NULL)
18897     internal_error (__FILE__, __LINE__,
18898                     _("could not find partial DIE 0x%x "
18899                       "in cache [from module %s]\n"),
18900                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
18901   return pd;
18902 }
18903
18904 /* See if we can figure out if the class lives in a namespace.  We do
18905    this by looking for a member function; its demangled name will
18906    contain namespace info, if there is any.  */
18907
18908 static void
18909 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18910                                   struct dwarf2_cu *cu)
18911 {
18912   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18913      what template types look like, because the demangler
18914      frequently doesn't give the same name as the debug info.  We
18915      could fix this by only using the demangled name to get the
18916      prefix (but see comment in read_structure_type).  */
18917
18918   struct partial_die_info *real_pdi;
18919   struct partial_die_info *child_pdi;
18920
18921   /* If this DIE (this DIE's specification, if any) has a parent, then
18922      we should not do this.  We'll prepend the parent's fully qualified
18923      name when we create the partial symbol.  */
18924
18925   real_pdi = struct_pdi;
18926   while (real_pdi->has_specification)
18927     real_pdi = find_partial_die (real_pdi->spec_offset,
18928                                  real_pdi->spec_is_dwz, cu);
18929
18930   if (real_pdi->die_parent != NULL)
18931     return;
18932
18933   for (child_pdi = struct_pdi->die_child;
18934        child_pdi != NULL;
18935        child_pdi = child_pdi->die_sibling)
18936     {
18937       if (child_pdi->tag == DW_TAG_subprogram
18938           && child_pdi->linkage_name != NULL)
18939         {
18940           char *actual_class_name
18941             = language_class_name_from_physname (cu->language_defn,
18942                                                  child_pdi->linkage_name);
18943           if (actual_class_name != NULL)
18944             {
18945               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18946               struct_pdi->name
18947                 = ((const char *)
18948                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18949                                   actual_class_name,
18950                                   strlen (actual_class_name)));
18951               xfree (actual_class_name);
18952             }
18953           break;
18954         }
18955     }
18956 }
18957
18958 /* Adjust PART_DIE before generating a symbol for it.  This function
18959    may set the is_external flag or change the DIE's name.  */
18960
18961 static void
18962 fixup_partial_die (struct partial_die_info *part_die,
18963                    struct dwarf2_cu *cu)
18964 {
18965   /* Once we've fixed up a die, there's no point in doing so again.
18966      This also avoids a memory leak if we were to call
18967      guess_partial_die_structure_name multiple times.  */
18968   if (part_die->fixup_called)
18969     return;
18970
18971   /* If we found a reference attribute and the DIE has no name, try
18972      to find a name in the referred to DIE.  */
18973
18974   if (part_die->name == NULL && part_die->has_specification)
18975     {
18976       struct partial_die_info *spec_die;
18977
18978       spec_die = find_partial_die (part_die->spec_offset,
18979                                    part_die->spec_is_dwz, cu);
18980
18981       fixup_partial_die (spec_die, cu);
18982
18983       if (spec_die->name)
18984         {
18985           part_die->name = spec_die->name;
18986
18987           /* Copy DW_AT_external attribute if it is set.  */
18988           if (spec_die->is_external)
18989             part_die->is_external = spec_die->is_external;
18990         }
18991     }
18992
18993   /* Set default names for some unnamed DIEs.  */
18994
18995   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
18996     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
18997
18998   /* If there is no parent die to provide a namespace, and there are
18999      children, see if we can determine the namespace from their linkage
19000      name.  */
19001   if (cu->language == language_cplus
19002       && !VEC_empty (dwarf2_section_info_def,
19003                      cu->per_cu->dwarf2_per_objfile->types)
19004       && part_die->die_parent == NULL
19005       && part_die->has_children
19006       && (part_die->tag == DW_TAG_class_type
19007           || part_die->tag == DW_TAG_structure_type
19008           || part_die->tag == DW_TAG_union_type))
19009     guess_partial_die_structure_name (part_die, cu);
19010
19011   /* GCC might emit a nameless struct or union that has a linkage
19012      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19013   if (part_die->name == NULL
19014       && (part_die->tag == DW_TAG_class_type
19015           || part_die->tag == DW_TAG_interface_type
19016           || part_die->tag == DW_TAG_structure_type
19017           || part_die->tag == DW_TAG_union_type)
19018       && part_die->linkage_name != NULL)
19019     {
19020       char *demangled;
19021
19022       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
19023       if (demangled)
19024         {
19025           const char *base;
19026
19027           /* Strip any leading namespaces/classes, keep only the base name.
19028              DW_AT_name for named DIEs does not contain the prefixes.  */
19029           base = strrchr (demangled, ':');
19030           if (base && base > demangled && base[-1] == ':')
19031             base++;
19032           else
19033             base = demangled;
19034
19035           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
19036           part_die->name
19037             = ((const char *)
19038                obstack_copy0 (&objfile->per_bfd->storage_obstack,
19039                               base, strlen (base)));
19040           xfree (demangled);
19041         }
19042     }
19043
19044   part_die->fixup_called = 1;
19045 }
19046
19047 /* Read an attribute value described by an attribute form.  */
19048
19049 static const gdb_byte *
19050 read_attribute_value (const struct die_reader_specs *reader,
19051                       struct attribute *attr, unsigned form,
19052                       LONGEST implicit_const, const gdb_byte *info_ptr)
19053 {
19054   struct dwarf2_cu *cu = reader->cu;
19055   struct dwarf2_per_objfile *dwarf2_per_objfile
19056     = cu->per_cu->dwarf2_per_objfile;
19057   struct objfile *objfile = dwarf2_per_objfile->objfile;
19058   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19059   bfd *abfd = reader->abfd;
19060   struct comp_unit_head *cu_header = &cu->header;
19061   unsigned int bytes_read;
19062   struct dwarf_block *blk;
19063
19064   attr->form = (enum dwarf_form) form;
19065   switch (form)
19066     {
19067     case DW_FORM_ref_addr:
19068       if (cu->header.version == 2)
19069         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19070       else
19071         DW_UNSND (attr) = read_offset (abfd, info_ptr,
19072                                        &cu->header, &bytes_read);
19073       info_ptr += bytes_read;
19074       break;
19075     case DW_FORM_GNU_ref_alt:
19076       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19077       info_ptr += bytes_read;
19078       break;
19079     case DW_FORM_addr:
19080       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
19081       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
19082       info_ptr += bytes_read;
19083       break;
19084     case DW_FORM_block2:
19085       blk = dwarf_alloc_block (cu);
19086       blk->size = read_2_bytes (abfd, info_ptr);
19087       info_ptr += 2;
19088       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19089       info_ptr += blk->size;
19090       DW_BLOCK (attr) = blk;
19091       break;
19092     case DW_FORM_block4:
19093       blk = dwarf_alloc_block (cu);
19094       blk->size = read_4_bytes (abfd, info_ptr);
19095       info_ptr += 4;
19096       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19097       info_ptr += blk->size;
19098       DW_BLOCK (attr) = blk;
19099       break;
19100     case DW_FORM_data2:
19101       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
19102       info_ptr += 2;
19103       break;
19104     case DW_FORM_data4:
19105       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
19106       info_ptr += 4;
19107       break;
19108     case DW_FORM_data8:
19109       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
19110       info_ptr += 8;
19111       break;
19112     case DW_FORM_data16:
19113       blk = dwarf_alloc_block (cu);
19114       blk->size = 16;
19115       blk->data = read_n_bytes (abfd, info_ptr, 16);
19116       info_ptr += 16;
19117       DW_BLOCK (attr) = blk;
19118       break;
19119     case DW_FORM_sec_offset:
19120       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
19121       info_ptr += bytes_read;
19122       break;
19123     case DW_FORM_string:
19124       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
19125       DW_STRING_IS_CANONICAL (attr) = 0;
19126       info_ptr += bytes_read;
19127       break;
19128     case DW_FORM_strp:
19129       if (!cu->per_cu->is_dwz)
19130         {
19131           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
19132                                                    abfd, info_ptr, cu_header,
19133                                                    &bytes_read);
19134           DW_STRING_IS_CANONICAL (attr) = 0;
19135           info_ptr += bytes_read;
19136           break;
19137         }
19138       /* FALLTHROUGH */
19139     case DW_FORM_line_strp:
19140       if (!cu->per_cu->is_dwz)
19141         {
19142           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19143                                                         abfd, info_ptr,
19144                                                         cu_header, &bytes_read);
19145           DW_STRING_IS_CANONICAL (attr) = 0;
19146           info_ptr += bytes_read;
19147           break;
19148         }
19149       /* FALLTHROUGH */
19150     case DW_FORM_GNU_strp_alt:
19151       {
19152         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19153         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19154                                           &bytes_read);
19155
19156         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19157                                                           dwz, str_offset);
19158         DW_STRING_IS_CANONICAL (attr) = 0;
19159         info_ptr += bytes_read;
19160       }
19161       break;
19162     case DW_FORM_exprloc:
19163     case DW_FORM_block:
19164       blk = dwarf_alloc_block (cu);
19165       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19166       info_ptr += bytes_read;
19167       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19168       info_ptr += blk->size;
19169       DW_BLOCK (attr) = blk;
19170       break;
19171     case DW_FORM_block1:
19172       blk = dwarf_alloc_block (cu);
19173       blk->size = read_1_byte (abfd, info_ptr);
19174       info_ptr += 1;
19175       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19176       info_ptr += blk->size;
19177       DW_BLOCK (attr) = blk;
19178       break;
19179     case DW_FORM_data1:
19180       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19181       info_ptr += 1;
19182       break;
19183     case DW_FORM_flag:
19184       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19185       info_ptr += 1;
19186       break;
19187     case DW_FORM_flag_present:
19188       DW_UNSND (attr) = 1;
19189       break;
19190     case DW_FORM_sdata:
19191       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19192       info_ptr += bytes_read;
19193       break;
19194     case DW_FORM_udata:
19195       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19196       info_ptr += bytes_read;
19197       break;
19198     case DW_FORM_ref1:
19199       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19200                          + read_1_byte (abfd, info_ptr));
19201       info_ptr += 1;
19202       break;
19203     case DW_FORM_ref2:
19204       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19205                          + read_2_bytes (abfd, info_ptr));
19206       info_ptr += 2;
19207       break;
19208     case DW_FORM_ref4:
19209       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19210                          + read_4_bytes (abfd, info_ptr));
19211       info_ptr += 4;
19212       break;
19213     case DW_FORM_ref8:
19214       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19215                          + read_8_bytes (abfd, info_ptr));
19216       info_ptr += 8;
19217       break;
19218     case DW_FORM_ref_sig8:
19219       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19220       info_ptr += 8;
19221       break;
19222     case DW_FORM_ref_udata:
19223       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19224                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19225       info_ptr += bytes_read;
19226       break;
19227     case DW_FORM_indirect:
19228       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19229       info_ptr += bytes_read;
19230       if (form == DW_FORM_implicit_const)
19231         {
19232           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19233           info_ptr += bytes_read;
19234         }
19235       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19236                                        info_ptr);
19237       break;
19238     case DW_FORM_implicit_const:
19239       DW_SND (attr) = implicit_const;
19240       break;
19241     case DW_FORM_GNU_addr_index:
19242       if (reader->dwo_file == NULL)
19243         {
19244           /* For now flag a hard error.
19245              Later we can turn this into a complaint.  */
19246           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19247                  dwarf_form_name (form),
19248                  bfd_get_filename (abfd));
19249         }
19250       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19251       info_ptr += bytes_read;
19252       break;
19253     case DW_FORM_GNU_str_index:
19254       if (reader->dwo_file == NULL)
19255         {
19256           /* For now flag a hard error.
19257              Later we can turn this into a complaint if warranted.  */
19258           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19259                  dwarf_form_name (form),
19260                  bfd_get_filename (abfd));
19261         }
19262       {
19263         ULONGEST str_index =
19264           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19265
19266         DW_STRING (attr) = read_str_index (reader, str_index);
19267         DW_STRING_IS_CANONICAL (attr) = 0;
19268         info_ptr += bytes_read;
19269       }
19270       break;
19271     default:
19272       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19273              dwarf_form_name (form),
19274              bfd_get_filename (abfd));
19275     }
19276
19277   /* Super hack.  */
19278   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19279     attr->form = DW_FORM_GNU_ref_alt;
19280
19281   /* We have seen instances where the compiler tried to emit a byte
19282      size attribute of -1 which ended up being encoded as an unsigned
19283      0xffffffff.  Although 0xffffffff is technically a valid size value,
19284      an object of this size seems pretty unlikely so we can relatively
19285      safely treat these cases as if the size attribute was invalid and
19286      treat them as zero by default.  */
19287   if (attr->name == DW_AT_byte_size
19288       && form == DW_FORM_data4
19289       && DW_UNSND (attr) >= 0xffffffff)
19290     {
19291       complaint
19292         (&symfile_complaints,
19293          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19294          hex_string (DW_UNSND (attr)));
19295       DW_UNSND (attr) = 0;
19296     }
19297
19298   return info_ptr;
19299 }
19300
19301 /* Read an attribute described by an abbreviated attribute.  */
19302
19303 static const gdb_byte *
19304 read_attribute (const struct die_reader_specs *reader,
19305                 struct attribute *attr, struct attr_abbrev *abbrev,
19306                 const gdb_byte *info_ptr)
19307 {
19308   attr->name = abbrev->name;
19309   return read_attribute_value (reader, attr, abbrev->form,
19310                                abbrev->implicit_const, info_ptr);
19311 }
19312
19313 /* Read dwarf information from a buffer.  */
19314
19315 static unsigned int
19316 read_1_byte (bfd *abfd, const gdb_byte *buf)
19317 {
19318   return bfd_get_8 (abfd, buf);
19319 }
19320
19321 static int
19322 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19323 {
19324   return bfd_get_signed_8 (abfd, buf);
19325 }
19326
19327 static unsigned int
19328 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19329 {
19330   return bfd_get_16 (abfd, buf);
19331 }
19332
19333 static int
19334 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19335 {
19336   return bfd_get_signed_16 (abfd, buf);
19337 }
19338
19339 static unsigned int
19340 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19341 {
19342   return bfd_get_32 (abfd, buf);
19343 }
19344
19345 static int
19346 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19347 {
19348   return bfd_get_signed_32 (abfd, buf);
19349 }
19350
19351 static ULONGEST
19352 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19353 {
19354   return bfd_get_64 (abfd, buf);
19355 }
19356
19357 static CORE_ADDR
19358 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19359               unsigned int *bytes_read)
19360 {
19361   struct comp_unit_head *cu_header = &cu->header;
19362   CORE_ADDR retval = 0;
19363
19364   if (cu_header->signed_addr_p)
19365     {
19366       switch (cu_header->addr_size)
19367         {
19368         case 2:
19369           retval = bfd_get_signed_16 (abfd, buf);
19370           break;
19371         case 4:
19372           retval = bfd_get_signed_32 (abfd, buf);
19373           break;
19374         case 8:
19375           retval = bfd_get_signed_64 (abfd, buf);
19376           break;
19377         default:
19378           internal_error (__FILE__, __LINE__,
19379                           _("read_address: bad switch, signed [in module %s]"),
19380                           bfd_get_filename (abfd));
19381         }
19382     }
19383   else
19384     {
19385       switch (cu_header->addr_size)
19386         {
19387         case 2:
19388           retval = bfd_get_16 (abfd, buf);
19389           break;
19390         case 4:
19391           retval = bfd_get_32 (abfd, buf);
19392           break;
19393         case 8:
19394           retval = bfd_get_64 (abfd, buf);
19395           break;
19396         default:
19397           internal_error (__FILE__, __LINE__,
19398                           _("read_address: bad switch, "
19399                             "unsigned [in module %s]"),
19400                           bfd_get_filename (abfd));
19401         }
19402     }
19403
19404   *bytes_read = cu_header->addr_size;
19405   return retval;
19406 }
19407
19408 /* Read the initial length from a section.  The (draft) DWARF 3
19409    specification allows the initial length to take up either 4 bytes
19410    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19411    bytes describe the length and all offsets will be 8 bytes in length
19412    instead of 4.
19413
19414    An older, non-standard 64-bit format is also handled by this
19415    function.  The older format in question stores the initial length
19416    as an 8-byte quantity without an escape value.  Lengths greater
19417    than 2^32 aren't very common which means that the initial 4 bytes
19418    is almost always zero.  Since a length value of zero doesn't make
19419    sense for the 32-bit format, this initial zero can be considered to
19420    be an escape value which indicates the presence of the older 64-bit
19421    format.  As written, the code can't detect (old format) lengths
19422    greater than 4GB.  If it becomes necessary to handle lengths
19423    somewhat larger than 4GB, we could allow other small values (such
19424    as the non-sensical values of 1, 2, and 3) to also be used as
19425    escape values indicating the presence of the old format.
19426
19427    The value returned via bytes_read should be used to increment the
19428    relevant pointer after calling read_initial_length().
19429
19430    [ Note:  read_initial_length() and read_offset() are based on the
19431      document entitled "DWARF Debugging Information Format", revision
19432      3, draft 8, dated November 19, 2001.  This document was obtained
19433      from:
19434
19435         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19436
19437      This document is only a draft and is subject to change.  (So beware.)
19438
19439      Details regarding the older, non-standard 64-bit format were
19440      determined empirically by examining 64-bit ELF files produced by
19441      the SGI toolchain on an IRIX 6.5 machine.
19442
19443      - Kevin, July 16, 2002
19444    ] */
19445
19446 static LONGEST
19447 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19448 {
19449   LONGEST length = bfd_get_32 (abfd, buf);
19450
19451   if (length == 0xffffffff)
19452     {
19453       length = bfd_get_64 (abfd, buf + 4);
19454       *bytes_read = 12;
19455     }
19456   else if (length == 0)
19457     {
19458       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19459       length = bfd_get_64 (abfd, buf);
19460       *bytes_read = 8;
19461     }
19462   else
19463     {
19464       *bytes_read = 4;
19465     }
19466
19467   return length;
19468 }
19469
19470 /* Cover function for read_initial_length.
19471    Returns the length of the object at BUF, and stores the size of the
19472    initial length in *BYTES_READ and stores the size that offsets will be in
19473    *OFFSET_SIZE.
19474    If the initial length size is not equivalent to that specified in
19475    CU_HEADER then issue a complaint.
19476    This is useful when reading non-comp-unit headers.  */
19477
19478 static LONGEST
19479 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19480                                         const struct comp_unit_head *cu_header,
19481                                         unsigned int *bytes_read,
19482                                         unsigned int *offset_size)
19483 {
19484   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19485
19486   gdb_assert (cu_header->initial_length_size == 4
19487               || cu_header->initial_length_size == 8
19488               || cu_header->initial_length_size == 12);
19489
19490   if (cu_header->initial_length_size != *bytes_read)
19491     complaint (&symfile_complaints,
19492                _("intermixed 32-bit and 64-bit DWARF sections"));
19493
19494   *offset_size = (*bytes_read == 4) ? 4 : 8;
19495   return length;
19496 }
19497
19498 /* Read an offset from the data stream.  The size of the offset is
19499    given by cu_header->offset_size.  */
19500
19501 static LONGEST
19502 read_offset (bfd *abfd, const gdb_byte *buf,
19503              const struct comp_unit_head *cu_header,
19504              unsigned int *bytes_read)
19505 {
19506   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19507
19508   *bytes_read = cu_header->offset_size;
19509   return offset;
19510 }
19511
19512 /* Read an offset from the data stream.  */
19513
19514 static LONGEST
19515 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19516 {
19517   LONGEST retval = 0;
19518
19519   switch (offset_size)
19520     {
19521     case 4:
19522       retval = bfd_get_32 (abfd, buf);
19523       break;
19524     case 8:
19525       retval = bfd_get_64 (abfd, buf);
19526       break;
19527     default:
19528       internal_error (__FILE__, __LINE__,
19529                       _("read_offset_1: bad switch [in module %s]"),
19530                       bfd_get_filename (abfd));
19531     }
19532
19533   return retval;
19534 }
19535
19536 static const gdb_byte *
19537 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19538 {
19539   /* If the size of a host char is 8 bits, we can return a pointer
19540      to the buffer, otherwise we have to copy the data to a buffer
19541      allocated on the temporary obstack.  */
19542   gdb_assert (HOST_CHAR_BIT == 8);
19543   return buf;
19544 }
19545
19546 static const char *
19547 read_direct_string (bfd *abfd, const gdb_byte *buf,
19548                     unsigned int *bytes_read_ptr)
19549 {
19550   /* If the size of a host char is 8 bits, we can return a pointer
19551      to the string, otherwise we have to copy the string to a buffer
19552      allocated on the temporary obstack.  */
19553   gdb_assert (HOST_CHAR_BIT == 8);
19554   if (*buf == '\0')
19555     {
19556       *bytes_read_ptr = 1;
19557       return NULL;
19558     }
19559   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19560   return (const char *) buf;
19561 }
19562
19563 /* Return pointer to string at section SECT offset STR_OFFSET with error
19564    reporting strings FORM_NAME and SECT_NAME.  */
19565
19566 static const char *
19567 read_indirect_string_at_offset_from (struct objfile *objfile,
19568                                      bfd *abfd, LONGEST str_offset,
19569                                      struct dwarf2_section_info *sect,
19570                                      const char *form_name,
19571                                      const char *sect_name)
19572 {
19573   dwarf2_read_section (objfile, sect);
19574   if (sect->buffer == NULL)
19575     error (_("%s used without %s section [in module %s]"),
19576            form_name, sect_name, bfd_get_filename (abfd));
19577   if (str_offset >= sect->size)
19578     error (_("%s pointing outside of %s section [in module %s]"),
19579            form_name, sect_name, bfd_get_filename (abfd));
19580   gdb_assert (HOST_CHAR_BIT == 8);
19581   if (sect->buffer[str_offset] == '\0')
19582     return NULL;
19583   return (const char *) (sect->buffer + str_offset);
19584 }
19585
19586 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19587
19588 static const char *
19589 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19590                                 bfd *abfd, LONGEST str_offset)
19591 {
19592   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19593                                               abfd, str_offset,
19594                                               &dwarf2_per_objfile->str,
19595                                               "DW_FORM_strp", ".debug_str");
19596 }
19597
19598 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19599
19600 static const char *
19601 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19602                                      bfd *abfd, LONGEST str_offset)
19603 {
19604   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19605                                               abfd, str_offset,
19606                                               &dwarf2_per_objfile->line_str,
19607                                               "DW_FORM_line_strp",
19608                                               ".debug_line_str");
19609 }
19610
19611 /* Read a string at offset STR_OFFSET in the .debug_str section from
19612    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19613    the string consists of a single NUL byte, return NULL; otherwise
19614    return a pointer to the string.  */
19615
19616 static const char *
19617 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19618                                LONGEST str_offset)
19619 {
19620   dwarf2_read_section (objfile, &dwz->str);
19621
19622   if (dwz->str.buffer == NULL)
19623     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19624              "section [in module %s]"),
19625            bfd_get_filename (dwz->dwz_bfd));
19626   if (str_offset >= dwz->str.size)
19627     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19628              ".debug_str section [in module %s]"),
19629            bfd_get_filename (dwz->dwz_bfd));
19630   gdb_assert (HOST_CHAR_BIT == 8);
19631   if (dwz->str.buffer[str_offset] == '\0')
19632     return NULL;
19633   return (const char *) (dwz->str.buffer + str_offset);
19634 }
19635
19636 /* Return pointer to string at .debug_str offset as read from BUF.
19637    BUF is assumed to be in a compilation unit described by CU_HEADER.
19638    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19639
19640 static const char *
19641 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19642                       const gdb_byte *buf,
19643                       const struct comp_unit_head *cu_header,
19644                       unsigned int *bytes_read_ptr)
19645 {
19646   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19647
19648   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19649 }
19650
19651 /* Return pointer to string at .debug_line_str offset as read from BUF.
19652    BUF is assumed to be in a compilation unit described by CU_HEADER.
19653    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19654
19655 static const char *
19656 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19657                            bfd *abfd, const gdb_byte *buf,
19658                            const struct comp_unit_head *cu_header,
19659                            unsigned int *bytes_read_ptr)
19660 {
19661   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19662
19663   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19664                                               str_offset);
19665 }
19666
19667 ULONGEST
19668 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19669                           unsigned int *bytes_read_ptr)
19670 {
19671   ULONGEST result;
19672   unsigned int num_read;
19673   int shift;
19674   unsigned char byte;
19675
19676   result = 0;
19677   shift = 0;
19678   num_read = 0;
19679   while (1)
19680     {
19681       byte = bfd_get_8 (abfd, buf);
19682       buf++;
19683       num_read++;
19684       result |= ((ULONGEST) (byte & 127) << shift);
19685       if ((byte & 128) == 0)
19686         {
19687           break;
19688         }
19689       shift += 7;
19690     }
19691   *bytes_read_ptr = num_read;
19692   return result;
19693 }
19694
19695 static LONGEST
19696 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19697                     unsigned int *bytes_read_ptr)
19698 {
19699   LONGEST result;
19700   int shift, num_read;
19701   unsigned char byte;
19702
19703   result = 0;
19704   shift = 0;
19705   num_read = 0;
19706   while (1)
19707     {
19708       byte = bfd_get_8 (abfd, buf);
19709       buf++;
19710       num_read++;
19711       result |= ((LONGEST) (byte & 127) << shift);
19712       shift += 7;
19713       if ((byte & 128) == 0)
19714         {
19715           break;
19716         }
19717     }
19718   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19719     result |= -(((LONGEST) 1) << shift);
19720   *bytes_read_ptr = num_read;
19721   return result;
19722 }
19723
19724 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19725    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19726    ADDR_SIZE is the size of addresses from the CU header.  */
19727
19728 static CORE_ADDR
19729 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19730                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19731 {
19732   struct objfile *objfile = dwarf2_per_objfile->objfile;
19733   bfd *abfd = objfile->obfd;
19734   const gdb_byte *info_ptr;
19735
19736   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19737   if (dwarf2_per_objfile->addr.buffer == NULL)
19738     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19739            objfile_name (objfile));
19740   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19741     error (_("DW_FORM_addr_index pointing outside of "
19742              ".debug_addr section [in module %s]"),
19743            objfile_name (objfile));
19744   info_ptr = (dwarf2_per_objfile->addr.buffer
19745               + addr_base + addr_index * addr_size);
19746   if (addr_size == 4)
19747     return bfd_get_32 (abfd, info_ptr);
19748   else
19749     return bfd_get_64 (abfd, info_ptr);
19750 }
19751
19752 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19753
19754 static CORE_ADDR
19755 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19756 {
19757   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19758                             cu->addr_base, cu->header.addr_size);
19759 }
19760
19761 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19762
19763 static CORE_ADDR
19764 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19765                              unsigned int *bytes_read)
19766 {
19767   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19768   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19769
19770   return read_addr_index (cu, addr_index);
19771 }
19772
19773 /* Data structure to pass results from dwarf2_read_addr_index_reader
19774    back to dwarf2_read_addr_index.  */
19775
19776 struct dwarf2_read_addr_index_data
19777 {
19778   ULONGEST addr_base;
19779   int addr_size;
19780 };
19781
19782 /* die_reader_func for dwarf2_read_addr_index.  */
19783
19784 static void
19785 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19786                                const gdb_byte *info_ptr,
19787                                struct die_info *comp_unit_die,
19788                                int has_children,
19789                                void *data)
19790 {
19791   struct dwarf2_cu *cu = reader->cu;
19792   struct dwarf2_read_addr_index_data *aidata =
19793     (struct dwarf2_read_addr_index_data *) data;
19794
19795   aidata->addr_base = cu->addr_base;
19796   aidata->addr_size = cu->header.addr_size;
19797 }
19798
19799 /* Given an index in .debug_addr, fetch the value.
19800    NOTE: This can be called during dwarf expression evaluation,
19801    long after the debug information has been read, and thus per_cu->cu
19802    may no longer exist.  */
19803
19804 CORE_ADDR
19805 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19806                         unsigned int addr_index)
19807 {
19808   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19809   struct objfile *objfile = dwarf2_per_objfile->objfile;
19810   struct dwarf2_cu *cu = per_cu->cu;
19811   ULONGEST addr_base;
19812   int addr_size;
19813
19814   /* We need addr_base and addr_size.
19815      If we don't have PER_CU->cu, we have to get it.
19816      Nasty, but the alternative is storing the needed info in PER_CU,
19817      which at this point doesn't seem justified: it's not clear how frequently
19818      it would get used and it would increase the size of every PER_CU.
19819      Entry points like dwarf2_per_cu_addr_size do a similar thing
19820      so we're not in uncharted territory here.
19821      Alas we need to be a bit more complicated as addr_base is contained
19822      in the DIE.
19823
19824      We don't need to read the entire CU(/TU).
19825      We just need the header and top level die.
19826
19827      IWBN to use the aging mechanism to let us lazily later discard the CU.
19828      For now we skip this optimization.  */
19829
19830   if (cu != NULL)
19831     {
19832       addr_base = cu->addr_base;
19833       addr_size = cu->header.addr_size;
19834     }
19835   else
19836     {
19837       struct dwarf2_read_addr_index_data aidata;
19838
19839       /* Note: We can't use init_cutu_and_read_dies_simple here,
19840          we need addr_base.  */
19841       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
19842                                dwarf2_read_addr_index_reader, &aidata);
19843       addr_base = aidata.addr_base;
19844       addr_size = aidata.addr_size;
19845     }
19846
19847   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19848                             addr_size);
19849 }
19850
19851 /* Given a DW_FORM_GNU_str_index, fetch the string.
19852    This is only used by the Fission support.  */
19853
19854 static const char *
19855 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19856 {
19857   struct dwarf2_cu *cu = reader->cu;
19858   struct dwarf2_per_objfile *dwarf2_per_objfile
19859     = cu->per_cu->dwarf2_per_objfile;
19860   struct objfile *objfile = dwarf2_per_objfile->objfile;
19861   const char *objf_name = objfile_name (objfile);
19862   bfd *abfd = objfile->obfd;
19863   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19864   struct dwarf2_section_info *str_offsets_section =
19865     &reader->dwo_file->sections.str_offsets;
19866   const gdb_byte *info_ptr;
19867   ULONGEST str_offset;
19868   static const char form_name[] = "DW_FORM_GNU_str_index";
19869
19870   dwarf2_read_section (objfile, str_section);
19871   dwarf2_read_section (objfile, str_offsets_section);
19872   if (str_section->buffer == NULL)
19873     error (_("%s used without .debug_str.dwo section"
19874              " in CU at offset 0x%x [in module %s]"),
19875            form_name, to_underlying (cu->header.sect_off), objf_name);
19876   if (str_offsets_section->buffer == NULL)
19877     error (_("%s used without .debug_str_offsets.dwo section"
19878              " in CU at offset 0x%x [in module %s]"),
19879            form_name, to_underlying (cu->header.sect_off), objf_name);
19880   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19881     error (_("%s pointing outside of .debug_str_offsets.dwo"
19882              " section in CU at offset 0x%x [in module %s]"),
19883            form_name, to_underlying (cu->header.sect_off), objf_name);
19884   info_ptr = (str_offsets_section->buffer
19885               + str_index * cu->header.offset_size);
19886   if (cu->header.offset_size == 4)
19887     str_offset = bfd_get_32 (abfd, info_ptr);
19888   else
19889     str_offset = bfd_get_64 (abfd, info_ptr);
19890   if (str_offset >= str_section->size)
19891     error (_("Offset from %s pointing outside of"
19892              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
19893            form_name, to_underlying (cu->header.sect_off), objf_name);
19894   return (const char *) (str_section->buffer + str_offset);
19895 }
19896
19897 /* Return the length of an LEB128 number in BUF.  */
19898
19899 static int
19900 leb128_size (const gdb_byte *buf)
19901 {
19902   const gdb_byte *begin = buf;
19903   gdb_byte byte;
19904
19905   while (1)
19906     {
19907       byte = *buf++;
19908       if ((byte & 128) == 0)
19909         return buf - begin;
19910     }
19911 }
19912
19913 static void
19914 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19915 {
19916   switch (lang)
19917     {
19918     case DW_LANG_C89:
19919     case DW_LANG_C99:
19920     case DW_LANG_C11:
19921     case DW_LANG_C:
19922     case DW_LANG_UPC:
19923       cu->language = language_c;
19924       break;
19925     case DW_LANG_Java:
19926     case DW_LANG_C_plus_plus:
19927     case DW_LANG_C_plus_plus_11:
19928     case DW_LANG_C_plus_plus_14:
19929       cu->language = language_cplus;
19930       break;
19931     case DW_LANG_D:
19932       cu->language = language_d;
19933       break;
19934     case DW_LANG_Fortran77:
19935     case DW_LANG_Fortran90:
19936     case DW_LANG_Fortran95:
19937     case DW_LANG_Fortran03:
19938     case DW_LANG_Fortran08:
19939       cu->language = language_fortran;
19940       break;
19941     case DW_LANG_Go:
19942       cu->language = language_go;
19943       break;
19944     case DW_LANG_Mips_Assembler:
19945       cu->language = language_asm;
19946       break;
19947     case DW_LANG_Ada83:
19948     case DW_LANG_Ada95:
19949       cu->language = language_ada;
19950       break;
19951     case DW_LANG_Modula2:
19952       cu->language = language_m2;
19953       break;
19954     case DW_LANG_Pascal83:
19955       cu->language = language_pascal;
19956       break;
19957     case DW_LANG_ObjC:
19958       cu->language = language_objc;
19959       break;
19960     case DW_LANG_Rust:
19961     case DW_LANG_Rust_old:
19962       cu->language = language_rust;
19963       break;
19964     case DW_LANG_Cobol74:
19965     case DW_LANG_Cobol85:
19966     default:
19967       cu->language = language_minimal;
19968       break;
19969     }
19970   cu->language_defn = language_def (cu->language);
19971 }
19972
19973 /* Return the named attribute or NULL if not there.  */
19974
19975 static struct attribute *
19976 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19977 {
19978   for (;;)
19979     {
19980       unsigned int i;
19981       struct attribute *spec = NULL;
19982
19983       for (i = 0; i < die->num_attrs; ++i)
19984         {
19985           if (die->attrs[i].name == name)
19986             return &die->attrs[i];
19987           if (die->attrs[i].name == DW_AT_specification
19988               || die->attrs[i].name == DW_AT_abstract_origin)
19989             spec = &die->attrs[i];
19990         }
19991
19992       if (!spec)
19993         break;
19994
19995       die = follow_die_ref (die, spec, &cu);
19996     }
19997
19998   return NULL;
19999 }
20000
20001 /* Return the named attribute or NULL if not there,
20002    but do not follow DW_AT_specification, etc.
20003    This is for use in contexts where we're reading .debug_types dies.
20004    Following DW_AT_specification, DW_AT_abstract_origin will take us
20005    back up the chain, and we want to go down.  */
20006
20007 static struct attribute *
20008 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
20009 {
20010   unsigned int i;
20011
20012   for (i = 0; i < die->num_attrs; ++i)
20013     if (die->attrs[i].name == name)
20014       return &die->attrs[i];
20015
20016   return NULL;
20017 }
20018
20019 /* Return the string associated with a string-typed attribute, or NULL if it
20020    is either not found or is of an incorrect type.  */
20021
20022 static const char *
20023 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
20024 {
20025   struct attribute *attr;
20026   const char *str = NULL;
20027
20028   attr = dwarf2_attr (die, name, cu);
20029
20030   if (attr != NULL)
20031     {
20032       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
20033           || attr->form == DW_FORM_string
20034           || attr->form == DW_FORM_GNU_str_index
20035           || attr->form == DW_FORM_GNU_strp_alt)
20036         str = DW_STRING (attr);
20037       else
20038         complaint (&symfile_complaints,
20039                    _("string type expected for attribute %s for "
20040                      "DIE at 0x%x in module %s"),
20041                    dwarf_attr_name (name), to_underlying (die->sect_off),
20042                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
20043     }
20044
20045   return str;
20046 }
20047
20048 /* Return non-zero iff the attribute NAME is defined for the given DIE,
20049    and holds a non-zero value.  This function should only be used for
20050    DW_FORM_flag or DW_FORM_flag_present attributes.  */
20051
20052 static int
20053 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
20054 {
20055   struct attribute *attr = dwarf2_attr (die, name, cu);
20056
20057   return (attr && DW_UNSND (attr));
20058 }
20059
20060 static int
20061 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
20062 {
20063   /* A DIE is a declaration if it has a DW_AT_declaration attribute
20064      which value is non-zero.  However, we have to be careful with
20065      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
20066      (via dwarf2_flag_true_p) follows this attribute.  So we may
20067      end up accidently finding a declaration attribute that belongs
20068      to a different DIE referenced by the specification attribute,
20069      even though the given DIE does not have a declaration attribute.  */
20070   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
20071           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
20072 }
20073
20074 /* Return the die giving the specification for DIE, if there is
20075    one.  *SPEC_CU is the CU containing DIE on input, and the CU
20076    containing the return value on output.  If there is no
20077    specification, but there is an abstract origin, that is
20078    returned.  */
20079
20080 static struct die_info *
20081 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
20082 {
20083   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
20084                                              *spec_cu);
20085
20086   if (spec_attr == NULL)
20087     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
20088
20089   if (spec_attr == NULL)
20090     return NULL;
20091   else
20092     return follow_die_ref (die, spec_attr, spec_cu);
20093 }
20094
20095 /* Stub for free_line_header to match void * callback types.  */
20096
20097 static void
20098 free_line_header_voidp (void *arg)
20099 {
20100   struct line_header *lh = (struct line_header *) arg;
20101
20102   delete lh;
20103 }
20104
20105 void
20106 line_header::add_include_dir (const char *include_dir)
20107 {
20108   if (dwarf_line_debug >= 2)
20109     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
20110                         include_dirs.size () + 1, include_dir);
20111
20112   include_dirs.push_back (include_dir);
20113 }
20114
20115 void
20116 line_header::add_file_name (const char *name,
20117                             dir_index d_index,
20118                             unsigned int mod_time,
20119                             unsigned int length)
20120 {
20121   if (dwarf_line_debug >= 2)
20122     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
20123                         (unsigned) file_names.size () + 1, name);
20124
20125   file_names.emplace_back (name, d_index, mod_time, length);
20126 }
20127
20128 /* A convenience function to find the proper .debug_line section for a CU.  */
20129
20130 static struct dwarf2_section_info *
20131 get_debug_line_section (struct dwarf2_cu *cu)
20132 {
20133   struct dwarf2_section_info *section;
20134   struct dwarf2_per_objfile *dwarf2_per_objfile
20135     = cu->per_cu->dwarf2_per_objfile;
20136
20137   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
20138      DWO file.  */
20139   if (cu->dwo_unit && cu->per_cu->is_debug_types)
20140     section = &cu->dwo_unit->dwo_file->sections.line;
20141   else if (cu->per_cu->is_dwz)
20142     {
20143       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
20144
20145       section = &dwz->line;
20146     }
20147   else
20148     section = &dwarf2_per_objfile->line;
20149
20150   return section;
20151 }
20152
20153 /* Read directory or file name entry format, starting with byte of
20154    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20155    entries count and the entries themselves in the described entry
20156    format.  */
20157
20158 static void
20159 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20160                         bfd *abfd, const gdb_byte **bufp,
20161                         struct line_header *lh,
20162                         const struct comp_unit_head *cu_header,
20163                         void (*callback) (struct line_header *lh,
20164                                           const char *name,
20165                                           dir_index d_index,
20166                                           unsigned int mod_time,
20167                                           unsigned int length))
20168 {
20169   gdb_byte format_count, formati;
20170   ULONGEST data_count, datai;
20171   const gdb_byte *buf = *bufp;
20172   const gdb_byte *format_header_data;
20173   unsigned int bytes_read;
20174
20175   format_count = read_1_byte (abfd, buf);
20176   buf += 1;
20177   format_header_data = buf;
20178   for (formati = 0; formati < format_count; formati++)
20179     {
20180       read_unsigned_leb128 (abfd, buf, &bytes_read);
20181       buf += bytes_read;
20182       read_unsigned_leb128 (abfd, buf, &bytes_read);
20183       buf += bytes_read;
20184     }
20185
20186   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20187   buf += bytes_read;
20188   for (datai = 0; datai < data_count; datai++)
20189     {
20190       const gdb_byte *format = format_header_data;
20191       struct file_entry fe;
20192
20193       for (formati = 0; formati < format_count; formati++)
20194         {
20195           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20196           format += bytes_read;
20197
20198           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20199           format += bytes_read;
20200
20201           gdb::optional<const char *> string;
20202           gdb::optional<unsigned int> uint;
20203
20204           switch (form)
20205             {
20206             case DW_FORM_string:
20207               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20208               buf += bytes_read;
20209               break;
20210
20211             case DW_FORM_line_strp:
20212               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20213                                                          abfd, buf,
20214                                                          cu_header,
20215                                                          &bytes_read));
20216               buf += bytes_read;
20217               break;
20218
20219             case DW_FORM_data1:
20220               uint.emplace (read_1_byte (abfd, buf));
20221               buf += 1;
20222               break;
20223
20224             case DW_FORM_data2:
20225               uint.emplace (read_2_bytes (abfd, buf));
20226               buf += 2;
20227               break;
20228
20229             case DW_FORM_data4:
20230               uint.emplace (read_4_bytes (abfd, buf));
20231               buf += 4;
20232               break;
20233
20234             case DW_FORM_data8:
20235               uint.emplace (read_8_bytes (abfd, buf));
20236               buf += 8;
20237               break;
20238
20239             case DW_FORM_udata:
20240               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20241               buf += bytes_read;
20242               break;
20243
20244             case DW_FORM_block:
20245               /* It is valid only for DW_LNCT_timestamp which is ignored by
20246                  current GDB.  */
20247               break;
20248             }
20249
20250           switch (content_type)
20251             {
20252             case DW_LNCT_path:
20253               if (string.has_value ())
20254                 fe.name = *string;
20255               break;
20256             case DW_LNCT_directory_index:
20257               if (uint.has_value ())
20258                 fe.d_index = (dir_index) *uint;
20259               break;
20260             case DW_LNCT_timestamp:
20261               if (uint.has_value ())
20262                 fe.mod_time = *uint;
20263               break;
20264             case DW_LNCT_size:
20265               if (uint.has_value ())
20266                 fe.length = *uint;
20267               break;
20268             case DW_LNCT_MD5:
20269               break;
20270             default:
20271               complaint (&symfile_complaints,
20272                          _("Unknown format content type %s"),
20273                          pulongest (content_type));
20274             }
20275         }
20276
20277       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20278     }
20279
20280   *bufp = buf;
20281 }
20282
20283 /* Read the statement program header starting at OFFSET in
20284    .debug_line, or .debug_line.dwo.  Return a pointer
20285    to a struct line_header, allocated using xmalloc.
20286    Returns NULL if there is a problem reading the header, e.g., if it
20287    has a version we don't understand.
20288
20289    NOTE: the strings in the include directory and file name tables of
20290    the returned object point into the dwarf line section buffer,
20291    and must not be freed.  */
20292
20293 static line_header_up
20294 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20295 {
20296   const gdb_byte *line_ptr;
20297   unsigned int bytes_read, offset_size;
20298   int i;
20299   const char *cur_dir, *cur_file;
20300   struct dwarf2_section_info *section;
20301   bfd *abfd;
20302   struct dwarf2_per_objfile *dwarf2_per_objfile
20303     = cu->per_cu->dwarf2_per_objfile;
20304
20305   section = get_debug_line_section (cu);
20306   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20307   if (section->buffer == NULL)
20308     {
20309       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20310         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
20311       else
20312         complaint (&symfile_complaints, _("missing .debug_line section"));
20313       return 0;
20314     }
20315
20316   /* We can't do this until we know the section is non-empty.
20317      Only then do we know we have such a section.  */
20318   abfd = get_section_bfd_owner (section);
20319
20320   /* Make sure that at least there's room for the total_length field.
20321      That could be 12 bytes long, but we're just going to fudge that.  */
20322   if (to_underlying (sect_off) + 4 >= section->size)
20323     {
20324       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20325       return 0;
20326     }
20327
20328   line_header_up lh (new line_header ());
20329
20330   lh->sect_off = sect_off;
20331   lh->offset_in_dwz = cu->per_cu->is_dwz;
20332
20333   line_ptr = section->buffer + to_underlying (sect_off);
20334
20335   /* Read in the header.  */
20336   lh->total_length =
20337     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20338                                             &bytes_read, &offset_size);
20339   line_ptr += bytes_read;
20340   if (line_ptr + lh->total_length > (section->buffer + section->size))
20341     {
20342       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20343       return 0;
20344     }
20345   lh->statement_program_end = line_ptr + lh->total_length;
20346   lh->version = read_2_bytes (abfd, line_ptr);
20347   line_ptr += 2;
20348   if (lh->version > 5)
20349     {
20350       /* This is a version we don't understand.  The format could have
20351          changed in ways we don't handle properly so just punt.  */
20352       complaint (&symfile_complaints,
20353                  _("unsupported version in .debug_line section"));
20354       return NULL;
20355     }
20356   if (lh->version >= 5)
20357     {
20358       gdb_byte segment_selector_size;
20359
20360       /* Skip address size.  */
20361       read_1_byte (abfd, line_ptr);
20362       line_ptr += 1;
20363
20364       segment_selector_size = read_1_byte (abfd, line_ptr);
20365       line_ptr += 1;
20366       if (segment_selector_size != 0)
20367         {
20368           complaint (&symfile_complaints,
20369                      _("unsupported segment selector size %u "
20370                        "in .debug_line section"),
20371                      segment_selector_size);
20372           return NULL;
20373         }
20374     }
20375   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20376   line_ptr += offset_size;
20377   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20378   line_ptr += 1;
20379   if (lh->version >= 4)
20380     {
20381       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20382       line_ptr += 1;
20383     }
20384   else
20385     lh->maximum_ops_per_instruction = 1;
20386
20387   if (lh->maximum_ops_per_instruction == 0)
20388     {
20389       lh->maximum_ops_per_instruction = 1;
20390       complaint (&symfile_complaints,
20391                  _("invalid maximum_ops_per_instruction "
20392                    "in `.debug_line' section"));
20393     }
20394
20395   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20396   line_ptr += 1;
20397   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20398   line_ptr += 1;
20399   lh->line_range = read_1_byte (abfd, line_ptr);
20400   line_ptr += 1;
20401   lh->opcode_base = read_1_byte (abfd, line_ptr);
20402   line_ptr += 1;
20403   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20404
20405   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20406   for (i = 1; i < lh->opcode_base; ++i)
20407     {
20408       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20409       line_ptr += 1;
20410     }
20411
20412   if (lh->version >= 5)
20413     {
20414       /* Read directory table.  */
20415       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20416                               &cu->header,
20417                               [] (struct line_header *lh, const char *name,
20418                                   dir_index d_index, unsigned int mod_time,
20419                                   unsigned int length)
20420         {
20421           lh->add_include_dir (name);
20422         });
20423
20424       /* Read file name table.  */
20425       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20426                               &cu->header,
20427                               [] (struct line_header *lh, const char *name,
20428                                   dir_index d_index, unsigned int mod_time,
20429                                   unsigned int length)
20430         {
20431           lh->add_file_name (name, d_index, mod_time, length);
20432         });
20433     }
20434   else
20435     {
20436       /* Read directory table.  */
20437       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20438         {
20439           line_ptr += bytes_read;
20440           lh->add_include_dir (cur_dir);
20441         }
20442       line_ptr += bytes_read;
20443
20444       /* Read file name table.  */
20445       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20446         {
20447           unsigned int mod_time, length;
20448           dir_index d_index;
20449
20450           line_ptr += bytes_read;
20451           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20452           line_ptr += bytes_read;
20453           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20454           line_ptr += bytes_read;
20455           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20456           line_ptr += bytes_read;
20457
20458           lh->add_file_name (cur_file, d_index, mod_time, length);
20459         }
20460       line_ptr += bytes_read;
20461     }
20462   lh->statement_program_start = line_ptr;
20463
20464   if (line_ptr > (section->buffer + section->size))
20465     complaint (&symfile_complaints,
20466                _("line number info header doesn't "
20467                  "fit in `.debug_line' section"));
20468
20469   return lh;
20470 }
20471
20472 /* Subroutine of dwarf_decode_lines to simplify it.
20473    Return the file name of the psymtab for included file FILE_INDEX
20474    in line header LH of PST.
20475    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20476    If space for the result is malloc'd, it will be freed by a cleanup.
20477    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
20478
20479    The function creates dangling cleanup registration.  */
20480
20481 static const char *
20482 psymtab_include_file_name (const struct line_header *lh, int file_index,
20483                            const struct partial_symtab *pst,
20484                            const char *comp_dir)
20485 {
20486   const file_entry &fe = lh->file_names[file_index];
20487   const char *include_name = fe.name;
20488   const char *include_name_to_compare = include_name;
20489   const char *pst_filename;
20490   char *copied_name = NULL;
20491   int file_is_pst;
20492
20493   const char *dir_name = fe.include_dir (lh);
20494
20495   if (!IS_ABSOLUTE_PATH (include_name)
20496       && (dir_name != NULL || comp_dir != NULL))
20497     {
20498       /* Avoid creating a duplicate psymtab for PST.
20499          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20500          Before we do the comparison, however, we need to account
20501          for DIR_NAME and COMP_DIR.
20502          First prepend dir_name (if non-NULL).  If we still don't
20503          have an absolute path prepend comp_dir (if non-NULL).
20504          However, the directory we record in the include-file's
20505          psymtab does not contain COMP_DIR (to match the
20506          corresponding symtab(s)).
20507
20508          Example:
20509
20510          bash$ cd /tmp
20511          bash$ gcc -g ./hello.c
20512          include_name = "hello.c"
20513          dir_name = "."
20514          DW_AT_comp_dir = comp_dir = "/tmp"
20515          DW_AT_name = "./hello.c"
20516
20517       */
20518
20519       if (dir_name != NULL)
20520         {
20521           char *tem = concat (dir_name, SLASH_STRING,
20522                               include_name, (char *)NULL);
20523
20524           make_cleanup (xfree, tem);
20525           include_name = tem;
20526           include_name_to_compare = include_name;
20527         }
20528       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20529         {
20530           char *tem = concat (comp_dir, SLASH_STRING,
20531                               include_name, (char *)NULL);
20532
20533           make_cleanup (xfree, tem);
20534           include_name_to_compare = tem;
20535         }
20536     }
20537
20538   pst_filename = pst->filename;
20539   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20540     {
20541       copied_name = concat (pst->dirname, SLASH_STRING,
20542                             pst_filename, (char *)NULL);
20543       pst_filename = copied_name;
20544     }
20545
20546   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20547
20548   if (copied_name != NULL)
20549     xfree (copied_name);
20550
20551   if (file_is_pst)
20552     return NULL;
20553   return include_name;
20554 }
20555
20556 /* State machine to track the state of the line number program.  */
20557
20558 class lnp_state_machine
20559 {
20560 public:
20561   /* Initialize a machine state for the start of a line number
20562      program.  */
20563   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20564
20565   file_entry *current_file ()
20566   {
20567     /* lh->file_names is 0-based, but the file name numbers in the
20568        statement program are 1-based.  */
20569     return m_line_header->file_name_at (m_file);
20570   }
20571
20572   /* Record the line in the state machine.  END_SEQUENCE is true if
20573      we're processing the end of a sequence.  */
20574   void record_line (bool end_sequence);
20575
20576   /* Check address and if invalid nop-out the rest of the lines in this
20577      sequence.  */
20578   void check_line_address (struct dwarf2_cu *cu,
20579                            const gdb_byte *line_ptr,
20580                            CORE_ADDR lowpc, CORE_ADDR address);
20581
20582   void handle_set_discriminator (unsigned int discriminator)
20583   {
20584     m_discriminator = discriminator;
20585     m_line_has_non_zero_discriminator |= discriminator != 0;
20586   }
20587
20588   /* Handle DW_LNE_set_address.  */
20589   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20590   {
20591     m_op_index = 0;
20592     address += baseaddr;
20593     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20594   }
20595
20596   /* Handle DW_LNS_advance_pc.  */
20597   void handle_advance_pc (CORE_ADDR adjust);
20598
20599   /* Handle a special opcode.  */
20600   void handle_special_opcode (unsigned char op_code);
20601
20602   /* Handle DW_LNS_advance_line.  */
20603   void handle_advance_line (int line_delta)
20604   {
20605     advance_line (line_delta);
20606   }
20607
20608   /* Handle DW_LNS_set_file.  */
20609   void handle_set_file (file_name_index file);
20610
20611   /* Handle DW_LNS_negate_stmt.  */
20612   void handle_negate_stmt ()
20613   {
20614     m_is_stmt = !m_is_stmt;
20615   }
20616
20617   /* Handle DW_LNS_const_add_pc.  */
20618   void handle_const_add_pc ();
20619
20620   /* Handle DW_LNS_fixed_advance_pc.  */
20621   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20622   {
20623     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20624     m_op_index = 0;
20625   }
20626
20627   /* Handle DW_LNS_copy.  */
20628   void handle_copy ()
20629   {
20630     record_line (false);
20631     m_discriminator = 0;
20632   }
20633
20634   /* Handle DW_LNE_end_sequence.  */
20635   void handle_end_sequence ()
20636   {
20637     m_record_line_callback = ::record_line;
20638   }
20639
20640 private:
20641   /* Advance the line by LINE_DELTA.  */
20642   void advance_line (int line_delta)
20643   {
20644     m_line += line_delta;
20645
20646     if (line_delta != 0)
20647       m_line_has_non_zero_discriminator = m_discriminator != 0;
20648   }
20649
20650   gdbarch *m_gdbarch;
20651
20652   /* True if we're recording lines.
20653      Otherwise we're building partial symtabs and are just interested in
20654      finding include files mentioned by the line number program.  */
20655   bool m_record_lines_p;
20656
20657   /* The line number header.  */
20658   line_header *m_line_header;
20659
20660   /* These are part of the standard DWARF line number state machine,
20661      and initialized according to the DWARF spec.  */
20662
20663   unsigned char m_op_index = 0;
20664   /* The line table index (1-based) of the current file.  */
20665   file_name_index m_file = (file_name_index) 1;
20666   unsigned int m_line = 1;
20667
20668   /* These are initialized in the constructor.  */
20669
20670   CORE_ADDR m_address;
20671   bool m_is_stmt;
20672   unsigned int m_discriminator;
20673
20674   /* Additional bits of state we need to track.  */
20675
20676   /* The last file that we called dwarf2_start_subfile for.
20677      This is only used for TLLs.  */
20678   unsigned int m_last_file = 0;
20679   /* The last file a line number was recorded for.  */
20680   struct subfile *m_last_subfile = NULL;
20681
20682   /* The function to call to record a line.  */
20683   record_line_ftype *m_record_line_callback = NULL;
20684
20685   /* The last line number that was recorded, used to coalesce
20686      consecutive entries for the same line.  This can happen, for
20687      example, when discriminators are present.  PR 17276.  */
20688   unsigned int m_last_line = 0;
20689   bool m_line_has_non_zero_discriminator = false;
20690 };
20691
20692 void
20693 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20694 {
20695   CORE_ADDR addr_adj = (((m_op_index + adjust)
20696                          / m_line_header->maximum_ops_per_instruction)
20697                         * m_line_header->minimum_instruction_length);
20698   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20699   m_op_index = ((m_op_index + adjust)
20700                 % m_line_header->maximum_ops_per_instruction);
20701 }
20702
20703 void
20704 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20705 {
20706   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20707   CORE_ADDR addr_adj = (((m_op_index
20708                           + (adj_opcode / m_line_header->line_range))
20709                          / m_line_header->maximum_ops_per_instruction)
20710                         * m_line_header->minimum_instruction_length);
20711   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20712   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20713                 % m_line_header->maximum_ops_per_instruction);
20714
20715   int line_delta = (m_line_header->line_base
20716                     + (adj_opcode % m_line_header->line_range));
20717   advance_line (line_delta);
20718   record_line (false);
20719   m_discriminator = 0;
20720 }
20721
20722 void
20723 lnp_state_machine::handle_set_file (file_name_index file)
20724 {
20725   m_file = file;
20726
20727   const file_entry *fe = current_file ();
20728   if (fe == NULL)
20729     dwarf2_debug_line_missing_file_complaint ();
20730   else if (m_record_lines_p)
20731     {
20732       const char *dir = fe->include_dir (m_line_header);
20733
20734       m_last_subfile = current_subfile;
20735       m_line_has_non_zero_discriminator = m_discriminator != 0;
20736       dwarf2_start_subfile (fe->name, dir);
20737     }
20738 }
20739
20740 void
20741 lnp_state_machine::handle_const_add_pc ()
20742 {
20743   CORE_ADDR adjust
20744     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20745
20746   CORE_ADDR addr_adj
20747     = (((m_op_index + adjust)
20748         / m_line_header->maximum_ops_per_instruction)
20749        * m_line_header->minimum_instruction_length);
20750
20751   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20752   m_op_index = ((m_op_index + adjust)
20753                 % m_line_header->maximum_ops_per_instruction);
20754 }
20755
20756 /* Ignore this record_line request.  */
20757
20758 static void
20759 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20760 {
20761   return;
20762 }
20763
20764 /* Return non-zero if we should add LINE to the line number table.
20765    LINE is the line to add, LAST_LINE is the last line that was added,
20766    LAST_SUBFILE is the subfile for LAST_LINE.
20767    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20768    had a non-zero discriminator.
20769
20770    We have to be careful in the presence of discriminators.
20771    E.g., for this line:
20772
20773      for (i = 0; i < 100000; i++);
20774
20775    clang can emit four line number entries for that one line,
20776    each with a different discriminator.
20777    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20778
20779    However, we want gdb to coalesce all four entries into one.
20780    Otherwise the user could stepi into the middle of the line and
20781    gdb would get confused about whether the pc really was in the
20782    middle of the line.
20783
20784    Things are further complicated by the fact that two consecutive
20785    line number entries for the same line is a heuristic used by gcc
20786    to denote the end of the prologue.  So we can't just discard duplicate
20787    entries, we have to be selective about it.  The heuristic we use is
20788    that we only collapse consecutive entries for the same line if at least
20789    one of those entries has a non-zero discriminator.  PR 17276.
20790
20791    Note: Addresses in the line number state machine can never go backwards
20792    within one sequence, thus this coalescing is ok.  */
20793
20794 static int
20795 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20796                      int line_has_non_zero_discriminator,
20797                      struct subfile *last_subfile)
20798 {
20799   if (current_subfile != last_subfile)
20800     return 1;
20801   if (line != last_line)
20802     return 1;
20803   /* Same line for the same file that we've seen already.
20804      As a last check, for pr 17276, only record the line if the line
20805      has never had a non-zero discriminator.  */
20806   if (!line_has_non_zero_discriminator)
20807     return 1;
20808   return 0;
20809 }
20810
20811 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20812    in the line table of subfile SUBFILE.  */
20813
20814 static void
20815 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20816                      unsigned int line, CORE_ADDR address,
20817                      record_line_ftype p_record_line)
20818 {
20819   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20820
20821   if (dwarf_line_debug)
20822     {
20823       fprintf_unfiltered (gdb_stdlog,
20824                           "Recording line %u, file %s, address %s\n",
20825                           line, lbasename (subfile->name),
20826                           paddress (gdbarch, address));
20827     }
20828
20829   (*p_record_line) (subfile, line, addr);
20830 }
20831
20832 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20833    Mark the end of a set of line number records.
20834    The arguments are the same as for dwarf_record_line_1.
20835    If SUBFILE is NULL the request is ignored.  */
20836
20837 static void
20838 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20839                    CORE_ADDR address, record_line_ftype p_record_line)
20840 {
20841   if (subfile == NULL)
20842     return;
20843
20844   if (dwarf_line_debug)
20845     {
20846       fprintf_unfiltered (gdb_stdlog,
20847                           "Finishing current line, file %s, address %s\n",
20848                           lbasename (subfile->name),
20849                           paddress (gdbarch, address));
20850     }
20851
20852   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20853 }
20854
20855 void
20856 lnp_state_machine::record_line (bool end_sequence)
20857 {
20858   if (dwarf_line_debug)
20859     {
20860       fprintf_unfiltered (gdb_stdlog,
20861                           "Processing actual line %u: file %u,"
20862                           " address %s, is_stmt %u, discrim %u\n",
20863                           m_line, to_underlying (m_file),
20864                           paddress (m_gdbarch, m_address),
20865                           m_is_stmt, m_discriminator);
20866     }
20867
20868   file_entry *fe = current_file ();
20869
20870   if (fe == NULL)
20871     dwarf2_debug_line_missing_file_complaint ();
20872   /* For now we ignore lines not starting on an instruction boundary.
20873      But not when processing end_sequence for compatibility with the
20874      previous version of the code.  */
20875   else if (m_op_index == 0 || end_sequence)
20876     {
20877       fe->included_p = 1;
20878       if (m_record_lines_p && m_is_stmt)
20879         {
20880           if (m_last_subfile != current_subfile || end_sequence)
20881             {
20882               dwarf_finish_line (m_gdbarch, m_last_subfile,
20883                                  m_address, m_record_line_callback);
20884             }
20885
20886           if (!end_sequence)
20887             {
20888               if (dwarf_record_line_p (m_line, m_last_line,
20889                                        m_line_has_non_zero_discriminator,
20890                                        m_last_subfile))
20891                 {
20892                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20893                                        m_line, m_address,
20894                                        m_record_line_callback);
20895                 }
20896               m_last_subfile = current_subfile;
20897               m_last_line = m_line;
20898             }
20899         }
20900     }
20901 }
20902
20903 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20904                                       bool record_lines_p)
20905 {
20906   m_gdbarch = arch;
20907   m_record_lines_p = record_lines_p;
20908   m_line_header = lh;
20909
20910   m_record_line_callback = ::record_line;
20911
20912   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20913      was a line entry for it so that the backend has a chance to adjust it
20914      and also record it in case it needs it.  This is currently used by MIPS
20915      code, cf. `mips_adjust_dwarf2_line'.  */
20916   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20917   m_is_stmt = lh->default_is_stmt;
20918   m_discriminator = 0;
20919 }
20920
20921 void
20922 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20923                                        const gdb_byte *line_ptr,
20924                                        CORE_ADDR lowpc, CORE_ADDR address)
20925 {
20926   /* If address < lowpc then it's not a usable value, it's outside the
20927      pc range of the CU.  However, we restrict the test to only address
20928      values of zero to preserve GDB's previous behaviour which is to
20929      handle the specific case of a function being GC'd by the linker.  */
20930
20931   if (address == 0 && address < lowpc)
20932     {
20933       /* This line table is for a function which has been
20934          GCd by the linker.  Ignore it.  PR gdb/12528 */
20935
20936       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20937       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20938
20939       complaint (&symfile_complaints,
20940                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20941                  line_offset, objfile_name (objfile));
20942       m_record_line_callback = noop_record_line;
20943       /* Note: record_line_callback is left as noop_record_line until
20944          we see DW_LNE_end_sequence.  */
20945     }
20946 }
20947
20948 /* Subroutine of dwarf_decode_lines to simplify it.
20949    Process the line number information in LH.
20950    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20951    program in order to set included_p for every referenced header.  */
20952
20953 static void
20954 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20955                       const int decode_for_pst_p, CORE_ADDR lowpc)
20956 {
20957   const gdb_byte *line_ptr, *extended_end;
20958   const gdb_byte *line_end;
20959   unsigned int bytes_read, extended_len;
20960   unsigned char op_code, extended_op;
20961   CORE_ADDR baseaddr;
20962   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20963   bfd *abfd = objfile->obfd;
20964   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20965   /* True if we're recording line info (as opposed to building partial
20966      symtabs and just interested in finding include files mentioned by
20967      the line number program).  */
20968   bool record_lines_p = !decode_for_pst_p;
20969
20970   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20971
20972   line_ptr = lh->statement_program_start;
20973   line_end = lh->statement_program_end;
20974
20975   /* Read the statement sequences until there's nothing left.  */
20976   while (line_ptr < line_end)
20977     {
20978       /* The DWARF line number program state machine.  Reset the state
20979          machine at the start of each sequence.  */
20980       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20981       bool end_sequence = false;
20982
20983       if (record_lines_p)
20984         {
20985           /* Start a subfile for the current file of the state
20986              machine.  */
20987           const file_entry *fe = state_machine.current_file ();
20988
20989           if (fe != NULL)
20990             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20991         }
20992
20993       /* Decode the table.  */
20994       while (line_ptr < line_end && !end_sequence)
20995         {
20996           op_code = read_1_byte (abfd, line_ptr);
20997           line_ptr += 1;
20998
20999           if (op_code >= lh->opcode_base)
21000             {
21001               /* Special opcode.  */
21002               state_machine.handle_special_opcode (op_code);
21003             }
21004           else switch (op_code)
21005             {
21006             case DW_LNS_extended_op:
21007               extended_len = read_unsigned_leb128 (abfd, line_ptr,
21008                                                    &bytes_read);
21009               line_ptr += bytes_read;
21010               extended_end = line_ptr + extended_len;
21011               extended_op = read_1_byte (abfd, line_ptr);
21012               line_ptr += 1;
21013               switch (extended_op)
21014                 {
21015                 case DW_LNE_end_sequence:
21016                   state_machine.handle_end_sequence ();
21017                   end_sequence = true;
21018                   break;
21019                 case DW_LNE_set_address:
21020                   {
21021                     CORE_ADDR address
21022                       = read_address (abfd, line_ptr, cu, &bytes_read);
21023                     line_ptr += bytes_read;
21024
21025                     state_machine.check_line_address (cu, line_ptr,
21026                                                       lowpc, address);
21027                     state_machine.handle_set_address (baseaddr, address);
21028                   }
21029                   break;
21030                 case DW_LNE_define_file:
21031                   {
21032                     const char *cur_file;
21033                     unsigned int mod_time, length;
21034                     dir_index dindex;
21035
21036                     cur_file = read_direct_string (abfd, line_ptr,
21037                                                    &bytes_read);
21038                     line_ptr += bytes_read;
21039                     dindex = (dir_index)
21040                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21041                     line_ptr += bytes_read;
21042                     mod_time =
21043                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21044                     line_ptr += bytes_read;
21045                     length =
21046                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21047                     line_ptr += bytes_read;
21048                     lh->add_file_name (cur_file, dindex, mod_time, length);
21049                   }
21050                   break;
21051                 case DW_LNE_set_discriminator:
21052                   {
21053                     /* The discriminator is not interesting to the
21054                        debugger; just ignore it.  We still need to
21055                        check its value though:
21056                        if there are consecutive entries for the same
21057                        (non-prologue) line we want to coalesce them.
21058                        PR 17276.  */
21059                     unsigned int discr
21060                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21061                     line_ptr += bytes_read;
21062
21063                     state_machine.handle_set_discriminator (discr);
21064                   }
21065                   break;
21066                 default:
21067                   complaint (&symfile_complaints,
21068                              _("mangled .debug_line section"));
21069                   return;
21070                 }
21071               /* Make sure that we parsed the extended op correctly.  If e.g.
21072                  we expected a different address size than the producer used,
21073                  we may have read the wrong number of bytes.  */
21074               if (line_ptr != extended_end)
21075                 {
21076                   complaint (&symfile_complaints,
21077                              _("mangled .debug_line section"));
21078                   return;
21079                 }
21080               break;
21081             case DW_LNS_copy:
21082               state_machine.handle_copy ();
21083               break;
21084             case DW_LNS_advance_pc:
21085               {
21086                 CORE_ADDR adjust
21087                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21088                 line_ptr += bytes_read;
21089
21090                 state_machine.handle_advance_pc (adjust);
21091               }
21092               break;
21093             case DW_LNS_advance_line:
21094               {
21095                 int line_delta
21096                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
21097                 line_ptr += bytes_read;
21098
21099                 state_machine.handle_advance_line (line_delta);
21100               }
21101               break;
21102             case DW_LNS_set_file:
21103               {
21104                 file_name_index file
21105                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
21106                                                             &bytes_read);
21107                 line_ptr += bytes_read;
21108
21109                 state_machine.handle_set_file (file);
21110               }
21111               break;
21112             case DW_LNS_set_column:
21113               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21114               line_ptr += bytes_read;
21115               break;
21116             case DW_LNS_negate_stmt:
21117               state_machine.handle_negate_stmt ();
21118               break;
21119             case DW_LNS_set_basic_block:
21120               break;
21121             /* Add to the address register of the state machine the
21122                address increment value corresponding to special opcode
21123                255.  I.e., this value is scaled by the minimum
21124                instruction length since special opcode 255 would have
21125                scaled the increment.  */
21126             case DW_LNS_const_add_pc:
21127               state_machine.handle_const_add_pc ();
21128               break;
21129             case DW_LNS_fixed_advance_pc:
21130               {
21131                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
21132                 line_ptr += 2;
21133
21134                 state_machine.handle_fixed_advance_pc (addr_adj);
21135               }
21136               break;
21137             default:
21138               {
21139                 /* Unknown standard opcode, ignore it.  */
21140                 int i;
21141
21142                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
21143                   {
21144                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
21145                     line_ptr += bytes_read;
21146                   }
21147               }
21148             }
21149         }
21150
21151       if (!end_sequence)
21152         dwarf2_debug_line_missing_end_sequence_complaint ();
21153
21154       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
21155          in which case we still finish recording the last line).  */
21156       state_machine.record_line (true);
21157     }
21158 }
21159
21160 /* Decode the Line Number Program (LNP) for the given line_header
21161    structure and CU.  The actual information extracted and the type
21162    of structures created from the LNP depends on the value of PST.
21163
21164    1. If PST is NULL, then this procedure uses the data from the program
21165       to create all necessary symbol tables, and their linetables.
21166
21167    2. If PST is not NULL, this procedure reads the program to determine
21168       the list of files included by the unit represented by PST, and
21169       builds all the associated partial symbol tables.
21170
21171    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21172    It is used for relative paths in the line table.
21173    NOTE: When processing partial symtabs (pst != NULL),
21174    comp_dir == pst->dirname.
21175
21176    NOTE: It is important that psymtabs have the same file name (via strcmp)
21177    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21178    symtab we don't use it in the name of the psymtabs we create.
21179    E.g. expand_line_sal requires this when finding psymtabs to expand.
21180    A good testcase for this is mb-inline.exp.
21181
21182    LOWPC is the lowest address in CU (or 0 if not known).
21183
21184    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21185    for its PC<->lines mapping information.  Otherwise only the filename
21186    table is read in.  */
21187
21188 static void
21189 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21190                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21191                     CORE_ADDR lowpc, int decode_mapping)
21192 {
21193   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21194   const int decode_for_pst_p = (pst != NULL);
21195
21196   if (decode_mapping)
21197     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21198
21199   if (decode_for_pst_p)
21200     {
21201       int file_index;
21202
21203       /* Now that we're done scanning the Line Header Program, we can
21204          create the psymtab of each included file.  */
21205       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21206         if (lh->file_names[file_index].included_p == 1)
21207           {
21208             const char *include_name =
21209               psymtab_include_file_name (lh, file_index, pst, comp_dir);
21210             if (include_name != NULL)
21211               dwarf2_create_include_psymtab (include_name, pst, objfile);
21212           }
21213     }
21214   else
21215     {
21216       /* Make sure a symtab is created for every file, even files
21217          which contain only variables (i.e. no code with associated
21218          line numbers).  */
21219       struct compunit_symtab *cust = buildsym_compunit_symtab ();
21220       int i;
21221
21222       for (i = 0; i < lh->file_names.size (); i++)
21223         {
21224           file_entry &fe = lh->file_names[i];
21225
21226           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
21227
21228           if (current_subfile->symtab == NULL)
21229             {
21230               current_subfile->symtab
21231                 = allocate_symtab (cust, current_subfile->name);
21232             }
21233           fe.symtab = current_subfile->symtab;
21234         }
21235     }
21236 }
21237
21238 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21239    DIRNAME the name of the source directory which contains FILENAME
21240    or NULL if not known.
21241    This routine tries to keep line numbers from identical absolute and
21242    relative file names in a common subfile.
21243
21244    Using the `list' example from the GDB testsuite, which resides in
21245    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21246    of /srcdir/list0.c yields the following debugging information for list0.c:
21247
21248    DW_AT_name:          /srcdir/list0.c
21249    DW_AT_comp_dir:      /compdir
21250    files.files[0].name: list0.h
21251    files.files[0].dir:  /srcdir
21252    files.files[1].name: list0.c
21253    files.files[1].dir:  /srcdir
21254
21255    The line number information for list0.c has to end up in a single
21256    subfile, so that `break /srcdir/list0.c:1' works as expected.
21257    start_subfile will ensure that this happens provided that we pass the
21258    concatenation of files.files[1].dir and files.files[1].name as the
21259    subfile's name.  */
21260
21261 static void
21262 dwarf2_start_subfile (const char *filename, const char *dirname)
21263 {
21264   char *copy = NULL;
21265
21266   /* In order not to lose the line information directory,
21267      we concatenate it to the filename when it makes sense.
21268      Note that the Dwarf3 standard says (speaking of filenames in line
21269      information): ``The directory index is ignored for file names
21270      that represent full path names''.  Thus ignoring dirname in the
21271      `else' branch below isn't an issue.  */
21272
21273   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21274     {
21275       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21276       filename = copy;
21277     }
21278
21279   start_subfile (filename);
21280
21281   if (copy != NULL)
21282     xfree (copy);
21283 }
21284
21285 /* Start a symtab for DWARF.
21286    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21287
21288 static struct compunit_symtab *
21289 dwarf2_start_symtab (struct dwarf2_cu *cu,
21290                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21291 {
21292   struct compunit_symtab *cust
21293     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21294                     low_pc, cu->language);
21295
21296   record_debugformat ("DWARF 2");
21297   record_producer (cu->producer);
21298
21299   /* We assume that we're processing GCC output.  */
21300   processing_gcc_compilation = 2;
21301
21302   cu->processing_has_namespace_info = 0;
21303
21304   return cust;
21305 }
21306
21307 static void
21308 var_decode_location (struct attribute *attr, struct symbol *sym,
21309                      struct dwarf2_cu *cu)
21310 {
21311   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21312   struct comp_unit_head *cu_header = &cu->header;
21313
21314   /* NOTE drow/2003-01-30: There used to be a comment and some special
21315      code here to turn a symbol with DW_AT_external and a
21316      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21317      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21318      with some versions of binutils) where shared libraries could have
21319      relocations against symbols in their debug information - the
21320      minimal symbol would have the right address, but the debug info
21321      would not.  It's no longer necessary, because we will explicitly
21322      apply relocations when we read in the debug information now.  */
21323
21324   /* A DW_AT_location attribute with no contents indicates that a
21325      variable has been optimized away.  */
21326   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21327     {
21328       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21329       return;
21330     }
21331
21332   /* Handle one degenerate form of location expression specially, to
21333      preserve GDB's previous behavior when section offsets are
21334      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21335      then mark this symbol as LOC_STATIC.  */
21336
21337   if (attr_form_is_block (attr)
21338       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21339            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21340           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21341               && (DW_BLOCK (attr)->size
21342                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21343     {
21344       unsigned int dummy;
21345
21346       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21347         SYMBOL_VALUE_ADDRESS (sym) =
21348           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21349       else
21350         SYMBOL_VALUE_ADDRESS (sym) =
21351           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21352       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21353       fixup_symbol_section (sym, objfile);
21354       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21355                                               SYMBOL_SECTION (sym));
21356       return;
21357     }
21358
21359   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21360      expression evaluator, and use LOC_COMPUTED only when necessary
21361      (i.e. when the value of a register or memory location is
21362      referenced, or a thread-local block, etc.).  Then again, it might
21363      not be worthwhile.  I'm assuming that it isn't unless performance
21364      or memory numbers show me otherwise.  */
21365
21366   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21367
21368   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21369     cu->has_loclist = 1;
21370 }
21371
21372 /* Given a pointer to a DWARF information entry, figure out if we need
21373    to make a symbol table entry for it, and if so, create a new entry
21374    and return a pointer to it.
21375    If TYPE is NULL, determine symbol type from the die, otherwise
21376    used the passed type.
21377    If SPACE is not NULL, use it to hold the new symbol.  If it is
21378    NULL, allocate a new symbol on the objfile's obstack.  */
21379
21380 static struct symbol *
21381 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21382             struct symbol *space)
21383 {
21384   struct dwarf2_per_objfile *dwarf2_per_objfile
21385     = cu->per_cu->dwarf2_per_objfile;
21386   struct objfile *objfile = dwarf2_per_objfile->objfile;
21387   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21388   struct symbol *sym = NULL;
21389   const char *name;
21390   struct attribute *attr = NULL;
21391   struct attribute *attr2 = NULL;
21392   CORE_ADDR baseaddr;
21393   struct pending **list_to_add = NULL;
21394
21395   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21396
21397   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21398
21399   name = dwarf2_name (die, cu);
21400   if (name)
21401     {
21402       const char *linkagename;
21403       int suppress_add = 0;
21404
21405       if (space)
21406         sym = space;
21407       else
21408         sym = allocate_symbol (objfile);
21409       OBJSTAT (objfile, n_syms++);
21410
21411       /* Cache this symbol's name and the name's demangled form (if any).  */
21412       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21413       linkagename = dwarf2_physname (name, die, cu);
21414       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21415
21416       /* Fortran does not have mangling standard and the mangling does differ
21417          between gfortran, iFort etc.  */
21418       if (cu->language == language_fortran
21419           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21420         symbol_set_demangled_name (&(sym->ginfo),
21421                                    dwarf2_full_name (name, die, cu),
21422                                    NULL);
21423
21424       /* Default assumptions.
21425          Use the passed type or decode it from the die.  */
21426       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21427       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21428       if (type != NULL)
21429         SYMBOL_TYPE (sym) = type;
21430       else
21431         SYMBOL_TYPE (sym) = die_type (die, cu);
21432       attr = dwarf2_attr (die,
21433                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21434                           cu);
21435       if (attr)
21436         {
21437           SYMBOL_LINE (sym) = DW_UNSND (attr);
21438         }
21439
21440       attr = dwarf2_attr (die,
21441                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21442                           cu);
21443       if (attr)
21444         {
21445           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21446           struct file_entry *fe;
21447
21448           if (cu->line_header != NULL)
21449             fe = cu->line_header->file_name_at (file_index);
21450           else
21451             fe = NULL;
21452
21453           if (fe == NULL)
21454             complaint (&symfile_complaints,
21455                        _("file index out of range"));
21456           else
21457             symbol_set_symtab (sym, fe->symtab);
21458         }
21459
21460       switch (die->tag)
21461         {
21462         case DW_TAG_label:
21463           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21464           if (attr)
21465             {
21466               CORE_ADDR addr;
21467
21468               addr = attr_value_as_address (attr);
21469               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21470               SYMBOL_VALUE_ADDRESS (sym) = addr;
21471             }
21472           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21473           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21474           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21475           add_symbol_to_list (sym, cu->list_in_scope);
21476           break;
21477         case DW_TAG_subprogram:
21478           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21479              finish_block.  */
21480           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21481           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21482           if ((attr2 && (DW_UNSND (attr2) != 0))
21483               || cu->language == language_ada)
21484             {
21485               /* Subprograms marked external are stored as a global symbol.
21486                  Ada subprograms, whether marked external or not, are always
21487                  stored as a global symbol, because we want to be able to
21488                  access them globally.  For instance, we want to be able
21489                  to break on a nested subprogram without having to
21490                  specify the context.  */
21491               list_to_add = &global_symbols;
21492             }
21493           else
21494             {
21495               list_to_add = cu->list_in_scope;
21496             }
21497           break;
21498         case DW_TAG_inlined_subroutine:
21499           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21500              finish_block.  */
21501           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21502           SYMBOL_INLINED (sym) = 1;
21503           list_to_add = cu->list_in_scope;
21504           break;
21505         case DW_TAG_template_value_param:
21506           suppress_add = 1;
21507           /* Fall through.  */
21508         case DW_TAG_constant:
21509         case DW_TAG_variable:
21510         case DW_TAG_member:
21511           /* Compilation with minimal debug info may result in
21512              variables with missing type entries.  Change the
21513              misleading `void' type to something sensible.  */
21514           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21515             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21516
21517           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21518           /* In the case of DW_TAG_member, we should only be called for
21519              static const members.  */
21520           if (die->tag == DW_TAG_member)
21521             {
21522               /* dwarf2_add_field uses die_is_declaration,
21523                  so we do the same.  */
21524               gdb_assert (die_is_declaration (die, cu));
21525               gdb_assert (attr);
21526             }
21527           if (attr)
21528             {
21529               dwarf2_const_value (attr, sym, cu);
21530               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21531               if (!suppress_add)
21532                 {
21533                   if (attr2 && (DW_UNSND (attr2) != 0))
21534                     list_to_add = &global_symbols;
21535                   else
21536                     list_to_add = cu->list_in_scope;
21537                 }
21538               break;
21539             }
21540           attr = dwarf2_attr (die, DW_AT_location, cu);
21541           if (attr)
21542             {
21543               var_decode_location (attr, sym, cu);
21544               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21545
21546               /* Fortran explicitly imports any global symbols to the local
21547                  scope by DW_TAG_common_block.  */
21548               if (cu->language == language_fortran && die->parent
21549                   && die->parent->tag == DW_TAG_common_block)
21550                 attr2 = NULL;
21551
21552               if (SYMBOL_CLASS (sym) == LOC_STATIC
21553                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21554                   && !dwarf2_per_objfile->has_section_at_zero)
21555                 {
21556                   /* When a static variable is eliminated by the linker,
21557                      the corresponding debug information is not stripped
21558                      out, but the variable address is set to null;
21559                      do not add such variables into symbol table.  */
21560                 }
21561               else if (attr2 && (DW_UNSND (attr2) != 0))
21562                 {
21563                   /* Workaround gfortran PR debug/40040 - it uses
21564                      DW_AT_location for variables in -fPIC libraries which may
21565                      get overriden by other libraries/executable and get
21566                      a different address.  Resolve it by the minimal symbol
21567                      which may come from inferior's executable using copy
21568                      relocation.  Make this workaround only for gfortran as for
21569                      other compilers GDB cannot guess the minimal symbol
21570                      Fortran mangling kind.  */
21571                   if (cu->language == language_fortran && die->parent
21572                       && die->parent->tag == DW_TAG_module
21573                       && cu->producer
21574                       && startswith (cu->producer, "GNU Fortran"))
21575                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21576
21577                   /* A variable with DW_AT_external is never static,
21578                      but it may be block-scoped.  */
21579                   list_to_add = (cu->list_in_scope == &file_symbols
21580                                  ? &global_symbols : cu->list_in_scope);
21581                 }
21582               else
21583                 list_to_add = cu->list_in_scope;
21584             }
21585           else
21586             {
21587               /* We do not know the address of this symbol.
21588                  If it is an external symbol and we have type information
21589                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21590                  The address of the variable will then be determined from
21591                  the minimal symbol table whenever the variable is
21592                  referenced.  */
21593               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21594
21595               /* Fortran explicitly imports any global symbols to the local
21596                  scope by DW_TAG_common_block.  */
21597               if (cu->language == language_fortran && die->parent
21598                   && die->parent->tag == DW_TAG_common_block)
21599                 {
21600                   /* SYMBOL_CLASS doesn't matter here because
21601                      read_common_block is going to reset it.  */
21602                   if (!suppress_add)
21603                     list_to_add = cu->list_in_scope;
21604                 }
21605               else if (attr2 && (DW_UNSND (attr2) != 0)
21606                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21607                 {
21608                   /* A variable with DW_AT_external is never static, but it
21609                      may be block-scoped.  */
21610                   list_to_add = (cu->list_in_scope == &file_symbols
21611                                  ? &global_symbols : cu->list_in_scope);
21612
21613                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21614                 }
21615               else if (!die_is_declaration (die, cu))
21616                 {
21617                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21618                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21619                   if (!suppress_add)
21620                     list_to_add = cu->list_in_scope;
21621                 }
21622             }
21623           break;
21624         case DW_TAG_formal_parameter:
21625           /* If we are inside a function, mark this as an argument.  If
21626              not, we might be looking at an argument to an inlined function
21627              when we do not have enough information to show inlined frames;
21628              pretend it's a local variable in that case so that the user can
21629              still see it.  */
21630           if (context_stack_depth > 0
21631               && context_stack[context_stack_depth - 1].name != NULL)
21632             SYMBOL_IS_ARGUMENT (sym) = 1;
21633           attr = dwarf2_attr (die, DW_AT_location, cu);
21634           if (attr)
21635             {
21636               var_decode_location (attr, sym, cu);
21637             }
21638           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21639           if (attr)
21640             {
21641               dwarf2_const_value (attr, sym, cu);
21642             }
21643
21644           list_to_add = cu->list_in_scope;
21645           break;
21646         case DW_TAG_unspecified_parameters:
21647           /* From varargs functions; gdb doesn't seem to have any
21648              interest in this information, so just ignore it for now.
21649              (FIXME?) */
21650           break;
21651         case DW_TAG_template_type_param:
21652           suppress_add = 1;
21653           /* Fall through.  */
21654         case DW_TAG_class_type:
21655         case DW_TAG_interface_type:
21656         case DW_TAG_structure_type:
21657         case DW_TAG_union_type:
21658         case DW_TAG_set_type:
21659         case DW_TAG_enumeration_type:
21660           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21661           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21662
21663           {
21664             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21665                really ever be static objects: otherwise, if you try
21666                to, say, break of a class's method and you're in a file
21667                which doesn't mention that class, it won't work unless
21668                the check for all static symbols in lookup_symbol_aux
21669                saves you.  See the OtherFileClass tests in
21670                gdb.c++/namespace.exp.  */
21671
21672             if (!suppress_add)
21673               {
21674                 list_to_add = (cu->list_in_scope == &file_symbols
21675                                && cu->language == language_cplus
21676                                ? &global_symbols : cu->list_in_scope);
21677
21678                 /* The semantics of C++ state that "struct foo {
21679                    ... }" also defines a typedef for "foo".  */
21680                 if (cu->language == language_cplus
21681                     || cu->language == language_ada
21682                     || cu->language == language_d
21683                     || cu->language == language_rust)
21684                   {
21685                     /* The symbol's name is already allocated along
21686                        with this objfile, so we don't need to
21687                        duplicate it for the type.  */
21688                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21689                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21690                   }
21691               }
21692           }
21693           break;
21694         case DW_TAG_typedef:
21695           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21696           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21697           list_to_add = cu->list_in_scope;
21698           break;
21699         case DW_TAG_base_type:
21700         case DW_TAG_subrange_type:
21701           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21702           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21703           list_to_add = cu->list_in_scope;
21704           break;
21705         case DW_TAG_enumerator:
21706           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21707           if (attr)
21708             {
21709               dwarf2_const_value (attr, sym, cu);
21710             }
21711           {
21712             /* NOTE: carlton/2003-11-10: See comment above in the
21713                DW_TAG_class_type, etc. block.  */
21714
21715             list_to_add = (cu->list_in_scope == &file_symbols
21716                            && cu->language == language_cplus
21717                            ? &global_symbols : cu->list_in_scope);
21718           }
21719           break;
21720         case DW_TAG_imported_declaration:
21721         case DW_TAG_namespace:
21722           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21723           list_to_add = &global_symbols;
21724           break;
21725         case DW_TAG_module:
21726           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21727           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21728           list_to_add = &global_symbols;
21729           break;
21730         case DW_TAG_common_block:
21731           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21732           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21733           add_symbol_to_list (sym, cu->list_in_scope);
21734           break;
21735         default:
21736           /* Not a tag we recognize.  Hopefully we aren't processing
21737              trash data, but since we must specifically ignore things
21738              we don't recognize, there is nothing else we should do at
21739              this point.  */
21740           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
21741                      dwarf_tag_name (die->tag));
21742           break;
21743         }
21744
21745       if (suppress_add)
21746         {
21747           sym->hash_next = objfile->template_symbols;
21748           objfile->template_symbols = sym;
21749           list_to_add = NULL;
21750         }
21751
21752       if (list_to_add != NULL)
21753         add_symbol_to_list (sym, list_to_add);
21754
21755       /* For the benefit of old versions of GCC, check for anonymous
21756          namespaces based on the demangled name.  */
21757       if (!cu->processing_has_namespace_info
21758           && cu->language == language_cplus)
21759         cp_scan_for_anonymous_namespaces (sym, objfile);
21760     }
21761   return (sym);
21762 }
21763
21764 /* Given an attr with a DW_FORM_dataN value in host byte order,
21765    zero-extend it as appropriate for the symbol's type.  The DWARF
21766    standard (v4) is not entirely clear about the meaning of using
21767    DW_FORM_dataN for a constant with a signed type, where the type is
21768    wider than the data.  The conclusion of a discussion on the DWARF
21769    list was that this is unspecified.  We choose to always zero-extend
21770    because that is the interpretation long in use by GCC.  */
21771
21772 static gdb_byte *
21773 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21774                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21775 {
21776   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21777   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21778                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21779   LONGEST l = DW_UNSND (attr);
21780
21781   if (bits < sizeof (*value) * 8)
21782     {
21783       l &= ((LONGEST) 1 << bits) - 1;
21784       *value = l;
21785     }
21786   else if (bits == sizeof (*value) * 8)
21787     *value = l;
21788   else
21789     {
21790       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21791       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21792       return bytes;
21793     }
21794
21795   return NULL;
21796 }
21797
21798 /* Read a constant value from an attribute.  Either set *VALUE, or if
21799    the value does not fit in *VALUE, set *BYTES - either already
21800    allocated on the objfile obstack, or newly allocated on OBSTACK,
21801    or, set *BATON, if we translated the constant to a location
21802    expression.  */
21803
21804 static void
21805 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21806                          const char *name, struct obstack *obstack,
21807                          struct dwarf2_cu *cu,
21808                          LONGEST *value, const gdb_byte **bytes,
21809                          struct dwarf2_locexpr_baton **baton)
21810 {
21811   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21812   struct comp_unit_head *cu_header = &cu->header;
21813   struct dwarf_block *blk;
21814   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21815                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21816
21817   *value = 0;
21818   *bytes = NULL;
21819   *baton = NULL;
21820
21821   switch (attr->form)
21822     {
21823     case DW_FORM_addr:
21824     case DW_FORM_GNU_addr_index:
21825       {
21826         gdb_byte *data;
21827
21828         if (TYPE_LENGTH (type) != cu_header->addr_size)
21829           dwarf2_const_value_length_mismatch_complaint (name,
21830                                                         cu_header->addr_size,
21831                                                         TYPE_LENGTH (type));
21832         /* Symbols of this form are reasonably rare, so we just
21833            piggyback on the existing location code rather than writing
21834            a new implementation of symbol_computed_ops.  */
21835         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21836         (*baton)->per_cu = cu->per_cu;
21837         gdb_assert ((*baton)->per_cu);
21838
21839         (*baton)->size = 2 + cu_header->addr_size;
21840         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21841         (*baton)->data = data;
21842
21843         data[0] = DW_OP_addr;
21844         store_unsigned_integer (&data[1], cu_header->addr_size,
21845                                 byte_order, DW_ADDR (attr));
21846         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21847       }
21848       break;
21849     case DW_FORM_string:
21850     case DW_FORM_strp:
21851     case DW_FORM_GNU_str_index:
21852     case DW_FORM_GNU_strp_alt:
21853       /* DW_STRING is already allocated on the objfile obstack, point
21854          directly to it.  */
21855       *bytes = (const gdb_byte *) DW_STRING (attr);
21856       break;
21857     case DW_FORM_block1:
21858     case DW_FORM_block2:
21859     case DW_FORM_block4:
21860     case DW_FORM_block:
21861     case DW_FORM_exprloc:
21862     case DW_FORM_data16:
21863       blk = DW_BLOCK (attr);
21864       if (TYPE_LENGTH (type) != blk->size)
21865         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21866                                                       TYPE_LENGTH (type));
21867       *bytes = blk->data;
21868       break;
21869
21870       /* The DW_AT_const_value attributes are supposed to carry the
21871          symbol's value "represented as it would be on the target
21872          architecture."  By the time we get here, it's already been
21873          converted to host endianness, so we just need to sign- or
21874          zero-extend it as appropriate.  */
21875     case DW_FORM_data1:
21876       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21877       break;
21878     case DW_FORM_data2:
21879       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21880       break;
21881     case DW_FORM_data4:
21882       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21883       break;
21884     case DW_FORM_data8:
21885       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21886       break;
21887
21888     case DW_FORM_sdata:
21889     case DW_FORM_implicit_const:
21890       *value = DW_SND (attr);
21891       break;
21892
21893     case DW_FORM_udata:
21894       *value = DW_UNSND (attr);
21895       break;
21896
21897     default:
21898       complaint (&symfile_complaints,
21899                  _("unsupported const value attribute form: '%s'"),
21900                  dwarf_form_name (attr->form));
21901       *value = 0;
21902       break;
21903     }
21904 }
21905
21906
21907 /* Copy constant value from an attribute to a symbol.  */
21908
21909 static void
21910 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21911                     struct dwarf2_cu *cu)
21912 {
21913   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21914   LONGEST value;
21915   const gdb_byte *bytes;
21916   struct dwarf2_locexpr_baton *baton;
21917
21918   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21919                            SYMBOL_PRINT_NAME (sym),
21920                            &objfile->objfile_obstack, cu,
21921                            &value, &bytes, &baton);
21922
21923   if (baton != NULL)
21924     {
21925       SYMBOL_LOCATION_BATON (sym) = baton;
21926       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21927     }
21928   else if (bytes != NULL)
21929      {
21930       SYMBOL_VALUE_BYTES (sym) = bytes;
21931       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21932     }
21933   else
21934     {
21935       SYMBOL_VALUE (sym) = value;
21936       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21937     }
21938 }
21939
21940 /* Return the type of the die in question using its DW_AT_type attribute.  */
21941
21942 static struct type *
21943 die_type (struct die_info *die, struct dwarf2_cu *cu)
21944 {
21945   struct attribute *type_attr;
21946
21947   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21948   if (!type_attr)
21949     {
21950       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21951       /* A missing DW_AT_type represents a void type.  */
21952       return objfile_type (objfile)->builtin_void;
21953     }
21954
21955   return lookup_die_type (die, type_attr, cu);
21956 }
21957
21958 /* True iff CU's producer generates GNAT Ada auxiliary information
21959    that allows to find parallel types through that information instead
21960    of having to do expensive parallel lookups by type name.  */
21961
21962 static int
21963 need_gnat_info (struct dwarf2_cu *cu)
21964 {
21965   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
21966      of GNAT produces this auxiliary information, without any indication
21967      that it is produced.  Part of enhancing the FSF version of GNAT
21968      to produce that information will be to put in place an indicator
21969      that we can use in order to determine whether the descriptive type
21970      info is available or not.  One suggestion that has been made is
21971      to use a new attribute, attached to the CU die.  For now, assume
21972      that the descriptive type info is not available.  */
21973   return 0;
21974 }
21975
21976 /* Return the auxiliary type of the die in question using its
21977    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21978    attribute is not present.  */
21979
21980 static struct type *
21981 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21982 {
21983   struct attribute *type_attr;
21984
21985   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21986   if (!type_attr)
21987     return NULL;
21988
21989   return lookup_die_type (die, type_attr, cu);
21990 }
21991
21992 /* If DIE has a descriptive_type attribute, then set the TYPE's
21993    descriptive type accordingly.  */
21994
21995 static void
21996 set_descriptive_type (struct type *type, struct die_info *die,
21997                       struct dwarf2_cu *cu)
21998 {
21999   struct type *descriptive_type = die_descriptive_type (die, cu);
22000
22001   if (descriptive_type)
22002     {
22003       ALLOCATE_GNAT_AUX_TYPE (type);
22004       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
22005     }
22006 }
22007
22008 /* Return the containing type of the die in question using its
22009    DW_AT_containing_type attribute.  */
22010
22011 static struct type *
22012 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
22013 {
22014   struct attribute *type_attr;
22015   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22016
22017   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
22018   if (!type_attr)
22019     error (_("Dwarf Error: Problem turning containing type into gdb type "
22020              "[in module %s]"), objfile_name (objfile));
22021
22022   return lookup_die_type (die, type_attr, cu);
22023 }
22024
22025 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
22026
22027 static struct type *
22028 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
22029 {
22030   struct dwarf2_per_objfile *dwarf2_per_objfile
22031     = cu->per_cu->dwarf2_per_objfile;
22032   struct objfile *objfile = dwarf2_per_objfile->objfile;
22033   char *message, *saved;
22034
22035   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
22036                         objfile_name (objfile),
22037                         to_underlying (cu->header.sect_off),
22038                         to_underlying (die->sect_off));
22039   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
22040                                   message, strlen (message));
22041   xfree (message);
22042
22043   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
22044 }
22045
22046 /* Look up the type of DIE in CU using its type attribute ATTR.
22047    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
22048    DW_AT_containing_type.
22049    If there is no type substitute an error marker.  */
22050
22051 static struct type *
22052 lookup_die_type (struct die_info *die, const struct attribute *attr,
22053                  struct dwarf2_cu *cu)
22054 {
22055   struct dwarf2_per_objfile *dwarf2_per_objfile
22056     = cu->per_cu->dwarf2_per_objfile;
22057   struct objfile *objfile = dwarf2_per_objfile->objfile;
22058   struct type *this_type;
22059
22060   gdb_assert (attr->name == DW_AT_type
22061               || attr->name == DW_AT_GNAT_descriptive_type
22062               || attr->name == DW_AT_containing_type);
22063
22064   /* First see if we have it cached.  */
22065
22066   if (attr->form == DW_FORM_GNU_ref_alt)
22067     {
22068       struct dwarf2_per_cu_data *per_cu;
22069       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22070
22071       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
22072                                                  dwarf2_per_objfile);
22073       this_type = get_die_type_at_offset (sect_off, per_cu);
22074     }
22075   else if (attr_form_is_ref (attr))
22076     {
22077       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22078
22079       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
22080     }
22081   else if (attr->form == DW_FORM_ref_sig8)
22082     {
22083       ULONGEST signature = DW_SIGNATURE (attr);
22084
22085       return get_signatured_type (die, signature, cu);
22086     }
22087   else
22088     {
22089       complaint (&symfile_complaints,
22090                  _("Dwarf Error: Bad type attribute %s in DIE"
22091                    " at 0x%x [in module %s]"),
22092                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
22093                  objfile_name (objfile));
22094       return build_error_marker_type (cu, die);
22095     }
22096
22097   /* If not cached we need to read it in.  */
22098
22099   if (this_type == NULL)
22100     {
22101       struct die_info *type_die = NULL;
22102       struct dwarf2_cu *type_cu = cu;
22103
22104       if (attr_form_is_ref (attr))
22105         type_die = follow_die_ref (die, attr, &type_cu);
22106       if (type_die == NULL)
22107         return build_error_marker_type (cu, die);
22108       /* If we find the type now, it's probably because the type came
22109          from an inter-CU reference and the type's CU got expanded before
22110          ours.  */
22111       this_type = read_type_die (type_die, type_cu);
22112     }
22113
22114   /* If we still don't have a type use an error marker.  */
22115
22116   if (this_type == NULL)
22117     return build_error_marker_type (cu, die);
22118
22119   return this_type;
22120 }
22121
22122 /* Return the type in DIE, CU.
22123    Returns NULL for invalid types.
22124
22125    This first does a lookup in die_type_hash,
22126    and only reads the die in if necessary.
22127
22128    NOTE: This can be called when reading in partial or full symbols.  */
22129
22130 static struct type *
22131 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
22132 {
22133   struct type *this_type;
22134
22135   this_type = get_die_type (die, cu);
22136   if (this_type)
22137     return this_type;
22138
22139   return read_type_die_1 (die, cu);
22140 }
22141
22142 /* Read the type in DIE, CU.
22143    Returns NULL for invalid types.  */
22144
22145 static struct type *
22146 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
22147 {
22148   struct type *this_type = NULL;
22149
22150   switch (die->tag)
22151     {
22152     case DW_TAG_class_type:
22153     case DW_TAG_interface_type:
22154     case DW_TAG_structure_type:
22155     case DW_TAG_union_type:
22156       this_type = read_structure_type (die, cu);
22157       break;
22158     case DW_TAG_enumeration_type:
22159       this_type = read_enumeration_type (die, cu);
22160       break;
22161     case DW_TAG_subprogram:
22162     case DW_TAG_subroutine_type:
22163     case DW_TAG_inlined_subroutine:
22164       this_type = read_subroutine_type (die, cu);
22165       break;
22166     case DW_TAG_array_type:
22167       this_type = read_array_type (die, cu);
22168       break;
22169     case DW_TAG_set_type:
22170       this_type = read_set_type (die, cu);
22171       break;
22172     case DW_TAG_pointer_type:
22173       this_type = read_tag_pointer_type (die, cu);
22174       break;
22175     case DW_TAG_ptr_to_member_type:
22176       this_type = read_tag_ptr_to_member_type (die, cu);
22177       break;
22178     case DW_TAG_reference_type:
22179       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22180       break;
22181     case DW_TAG_rvalue_reference_type:
22182       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22183       break;
22184     case DW_TAG_const_type:
22185       this_type = read_tag_const_type (die, cu);
22186       break;
22187     case DW_TAG_volatile_type:
22188       this_type = read_tag_volatile_type (die, cu);
22189       break;
22190     case DW_TAG_restrict_type:
22191       this_type = read_tag_restrict_type (die, cu);
22192       break;
22193     case DW_TAG_string_type:
22194       this_type = read_tag_string_type (die, cu);
22195       break;
22196     case DW_TAG_typedef:
22197       this_type = read_typedef (die, cu);
22198       break;
22199     case DW_TAG_subrange_type:
22200       this_type = read_subrange_type (die, cu);
22201       break;
22202     case DW_TAG_base_type:
22203       this_type = read_base_type (die, cu);
22204       break;
22205     case DW_TAG_unspecified_type:
22206       this_type = read_unspecified_type (die, cu);
22207       break;
22208     case DW_TAG_namespace:
22209       this_type = read_namespace_type (die, cu);
22210       break;
22211     case DW_TAG_module:
22212       this_type = read_module_type (die, cu);
22213       break;
22214     case DW_TAG_atomic_type:
22215       this_type = read_tag_atomic_type (die, cu);
22216       break;
22217     default:
22218       complaint (&symfile_complaints,
22219                  _("unexpected tag in read_type_die: '%s'"),
22220                  dwarf_tag_name (die->tag));
22221       break;
22222     }
22223
22224   return this_type;
22225 }
22226
22227 /* See if we can figure out if the class lives in a namespace.  We do
22228    this by looking for a member function; its demangled name will
22229    contain namespace info, if there is any.
22230    Return the computed name or NULL.
22231    Space for the result is allocated on the objfile's obstack.
22232    This is the full-die version of guess_partial_die_structure_name.
22233    In this case we know DIE has no useful parent.  */
22234
22235 static char *
22236 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22237 {
22238   struct die_info *spec_die;
22239   struct dwarf2_cu *spec_cu;
22240   struct die_info *child;
22241   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22242
22243   spec_cu = cu;
22244   spec_die = die_specification (die, &spec_cu);
22245   if (spec_die != NULL)
22246     {
22247       die = spec_die;
22248       cu = spec_cu;
22249     }
22250
22251   for (child = die->child;
22252        child != NULL;
22253        child = child->sibling)
22254     {
22255       if (child->tag == DW_TAG_subprogram)
22256         {
22257           const char *linkage_name = dw2_linkage_name (child, cu);
22258
22259           if (linkage_name != NULL)
22260             {
22261               char *actual_name
22262                 = language_class_name_from_physname (cu->language_defn,
22263                                                      linkage_name);
22264               char *name = NULL;
22265
22266               if (actual_name != NULL)
22267                 {
22268                   const char *die_name = dwarf2_name (die, cu);
22269
22270                   if (die_name != NULL
22271                       && strcmp (die_name, actual_name) != 0)
22272                     {
22273                       /* Strip off the class name from the full name.
22274                          We want the prefix.  */
22275                       int die_name_len = strlen (die_name);
22276                       int actual_name_len = strlen (actual_name);
22277
22278                       /* Test for '::' as a sanity check.  */
22279                       if (actual_name_len > die_name_len + 2
22280                           && actual_name[actual_name_len
22281                                          - die_name_len - 1] == ':')
22282                         name = (char *) obstack_copy0 (
22283                           &objfile->per_bfd->storage_obstack,
22284                           actual_name, actual_name_len - die_name_len - 2);
22285                     }
22286                 }
22287               xfree (actual_name);
22288               return name;
22289             }
22290         }
22291     }
22292
22293   return NULL;
22294 }
22295
22296 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22297    prefix part in such case.  See
22298    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22299
22300 static const char *
22301 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22302 {
22303   struct attribute *attr;
22304   const char *base;
22305
22306   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22307       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22308     return NULL;
22309
22310   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22311     return NULL;
22312
22313   attr = dw2_linkage_name_attr (die, cu);
22314   if (attr == NULL || DW_STRING (attr) == NULL)
22315     return NULL;
22316
22317   /* dwarf2_name had to be already called.  */
22318   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22319
22320   /* Strip the base name, keep any leading namespaces/classes.  */
22321   base = strrchr (DW_STRING (attr), ':');
22322   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22323     return "";
22324
22325   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22326   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22327                                  DW_STRING (attr),
22328                                  &base[-1] - DW_STRING (attr));
22329 }
22330
22331 /* Return the name of the namespace/class that DIE is defined within,
22332    or "" if we can't tell.  The caller should not xfree the result.
22333
22334    For example, if we're within the method foo() in the following
22335    code:
22336
22337    namespace N {
22338      class C {
22339        void foo () {
22340        }
22341      };
22342    }
22343
22344    then determine_prefix on foo's die will return "N::C".  */
22345
22346 static const char *
22347 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22348 {
22349   struct dwarf2_per_objfile *dwarf2_per_objfile
22350     = cu->per_cu->dwarf2_per_objfile;
22351   struct die_info *parent, *spec_die;
22352   struct dwarf2_cu *spec_cu;
22353   struct type *parent_type;
22354   const char *retval;
22355
22356   if (cu->language != language_cplus
22357       && cu->language != language_fortran && cu->language != language_d
22358       && cu->language != language_rust)
22359     return "";
22360
22361   retval = anonymous_struct_prefix (die, cu);
22362   if (retval)
22363     return retval;
22364
22365   /* We have to be careful in the presence of DW_AT_specification.
22366      For example, with GCC 3.4, given the code
22367
22368      namespace N {
22369        void foo() {
22370          // Definition of N::foo.
22371        }
22372      }
22373
22374      then we'll have a tree of DIEs like this:
22375
22376      1: DW_TAG_compile_unit
22377        2: DW_TAG_namespace        // N
22378          3: DW_TAG_subprogram     // declaration of N::foo
22379        4: DW_TAG_subprogram       // definition of N::foo
22380             DW_AT_specification   // refers to die #3
22381
22382      Thus, when processing die #4, we have to pretend that we're in
22383      the context of its DW_AT_specification, namely the contex of die
22384      #3.  */
22385   spec_cu = cu;
22386   spec_die = die_specification (die, &spec_cu);
22387   if (spec_die == NULL)
22388     parent = die->parent;
22389   else
22390     {
22391       parent = spec_die->parent;
22392       cu = spec_cu;
22393     }
22394
22395   if (parent == NULL)
22396     return "";
22397   else if (parent->building_fullname)
22398     {
22399       const char *name;
22400       const char *parent_name;
22401
22402       /* It has been seen on RealView 2.2 built binaries,
22403          DW_TAG_template_type_param types actually _defined_ as
22404          children of the parent class:
22405
22406          enum E {};
22407          template class <class Enum> Class{};
22408          Class<enum E> class_e;
22409
22410          1: DW_TAG_class_type (Class)
22411            2: DW_TAG_enumeration_type (E)
22412              3: DW_TAG_enumerator (enum1:0)
22413              3: DW_TAG_enumerator (enum2:1)
22414              ...
22415            2: DW_TAG_template_type_param
22416               DW_AT_type  DW_FORM_ref_udata (E)
22417
22418          Besides being broken debug info, it can put GDB into an
22419          infinite loop.  Consider:
22420
22421          When we're building the full name for Class<E>, we'll start
22422          at Class, and go look over its template type parameters,
22423          finding E.  We'll then try to build the full name of E, and
22424          reach here.  We're now trying to build the full name of E,
22425          and look over the parent DIE for containing scope.  In the
22426          broken case, if we followed the parent DIE of E, we'd again
22427          find Class, and once again go look at its template type
22428          arguments, etc., etc.  Simply don't consider such parent die
22429          as source-level parent of this die (it can't be, the language
22430          doesn't allow it), and break the loop here.  */
22431       name = dwarf2_name (die, cu);
22432       parent_name = dwarf2_name (parent, cu);
22433       complaint (&symfile_complaints,
22434                  _("template param type '%s' defined within parent '%s'"),
22435                  name ? name : "<unknown>",
22436                  parent_name ? parent_name : "<unknown>");
22437       return "";
22438     }
22439   else
22440     switch (parent->tag)
22441       {
22442       case DW_TAG_namespace:
22443         parent_type = read_type_die (parent, cu);
22444         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22445            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22446            Work around this problem here.  */
22447         if (cu->language == language_cplus
22448             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
22449           return "";
22450         /* We give a name to even anonymous namespaces.  */
22451         return TYPE_TAG_NAME (parent_type);
22452       case DW_TAG_class_type:
22453       case DW_TAG_interface_type:
22454       case DW_TAG_structure_type:
22455       case DW_TAG_union_type:
22456       case DW_TAG_module:
22457         parent_type = read_type_die (parent, cu);
22458         if (TYPE_TAG_NAME (parent_type) != NULL)
22459           return TYPE_TAG_NAME (parent_type);
22460         else
22461           /* An anonymous structure is only allowed non-static data
22462              members; no typedefs, no member functions, et cetera.
22463              So it does not need a prefix.  */
22464           return "";
22465       case DW_TAG_compile_unit:
22466       case DW_TAG_partial_unit:
22467         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22468         if (cu->language == language_cplus
22469             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22470             && die->child != NULL
22471             && (die->tag == DW_TAG_class_type
22472                 || die->tag == DW_TAG_structure_type
22473                 || die->tag == DW_TAG_union_type))
22474           {
22475             char *name = guess_full_die_structure_name (die, cu);
22476             if (name != NULL)
22477               return name;
22478           }
22479         return "";
22480       case DW_TAG_enumeration_type:
22481         parent_type = read_type_die (parent, cu);
22482         if (TYPE_DECLARED_CLASS (parent_type))
22483           {
22484             if (TYPE_TAG_NAME (parent_type) != NULL)
22485               return TYPE_TAG_NAME (parent_type);
22486             return "";
22487           }
22488         /* Fall through.  */
22489       default:
22490         return determine_prefix (parent, cu);
22491       }
22492 }
22493
22494 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22495    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22496    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22497    an obconcat, otherwise allocate storage for the result.  The CU argument is
22498    used to determine the language and hence, the appropriate separator.  */
22499
22500 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22501
22502 static char *
22503 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22504                  int physname, struct dwarf2_cu *cu)
22505 {
22506   const char *lead = "";
22507   const char *sep;
22508
22509   if (suffix == NULL || suffix[0] == '\0'
22510       || prefix == NULL || prefix[0] == '\0')
22511     sep = "";
22512   else if (cu->language == language_d)
22513     {
22514       /* For D, the 'main' function could be defined in any module, but it
22515          should never be prefixed.  */
22516       if (strcmp (suffix, "D main") == 0)
22517         {
22518           prefix = "";
22519           sep = "";
22520         }
22521       else
22522         sep = ".";
22523     }
22524   else if (cu->language == language_fortran && physname)
22525     {
22526       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22527          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22528
22529       lead = "__";
22530       sep = "_MOD_";
22531     }
22532   else
22533     sep = "::";
22534
22535   if (prefix == NULL)
22536     prefix = "";
22537   if (suffix == NULL)
22538     suffix = "";
22539
22540   if (obs == NULL)
22541     {
22542       char *retval
22543         = ((char *)
22544            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22545
22546       strcpy (retval, lead);
22547       strcat (retval, prefix);
22548       strcat (retval, sep);
22549       strcat (retval, suffix);
22550       return retval;
22551     }
22552   else
22553     {
22554       /* We have an obstack.  */
22555       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22556     }
22557 }
22558
22559 /* Return sibling of die, NULL if no sibling.  */
22560
22561 static struct die_info *
22562 sibling_die (struct die_info *die)
22563 {
22564   return die->sibling;
22565 }
22566
22567 /* Get name of a die, return NULL if not found.  */
22568
22569 static const char *
22570 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22571                           struct obstack *obstack)
22572 {
22573   if (name && cu->language == language_cplus)
22574     {
22575       std::string canon_name = cp_canonicalize_string (name);
22576
22577       if (!canon_name.empty ())
22578         {
22579           if (canon_name != name)
22580             name = (const char *) obstack_copy0 (obstack,
22581                                                  canon_name.c_str (),
22582                                                  canon_name.length ());
22583         }
22584     }
22585
22586   return name;
22587 }
22588
22589 /* Get name of a die, return NULL if not found.
22590    Anonymous namespaces are converted to their magic string.  */
22591
22592 static const char *
22593 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22594 {
22595   struct attribute *attr;
22596   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22597
22598   attr = dwarf2_attr (die, DW_AT_name, cu);
22599   if ((!attr || !DW_STRING (attr))
22600       && die->tag != DW_TAG_namespace
22601       && die->tag != DW_TAG_class_type
22602       && die->tag != DW_TAG_interface_type
22603       && die->tag != DW_TAG_structure_type
22604       && die->tag != DW_TAG_union_type)
22605     return NULL;
22606
22607   switch (die->tag)
22608     {
22609     case DW_TAG_compile_unit:
22610     case DW_TAG_partial_unit:
22611       /* Compilation units have a DW_AT_name that is a filename, not
22612          a source language identifier.  */
22613     case DW_TAG_enumeration_type:
22614     case DW_TAG_enumerator:
22615       /* These tags always have simple identifiers already; no need
22616          to canonicalize them.  */
22617       return DW_STRING (attr);
22618
22619     case DW_TAG_namespace:
22620       if (attr != NULL && DW_STRING (attr) != NULL)
22621         return DW_STRING (attr);
22622       return CP_ANONYMOUS_NAMESPACE_STR;
22623
22624     case DW_TAG_class_type:
22625     case DW_TAG_interface_type:
22626     case DW_TAG_structure_type:
22627     case DW_TAG_union_type:
22628       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22629          structures or unions.  These were of the form "._%d" in GCC 4.1,
22630          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22631          and GCC 4.4.  We work around this problem by ignoring these.  */
22632       if (attr && DW_STRING (attr)
22633           && (startswith (DW_STRING (attr), "._")
22634               || startswith (DW_STRING (attr), "<anonymous")))
22635         return NULL;
22636
22637       /* GCC might emit a nameless typedef that has a linkage name.  See
22638          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22639       if (!attr || DW_STRING (attr) == NULL)
22640         {
22641           char *demangled = NULL;
22642
22643           attr = dw2_linkage_name_attr (die, cu);
22644           if (attr == NULL || DW_STRING (attr) == NULL)
22645             return NULL;
22646
22647           /* Avoid demangling DW_STRING (attr) the second time on a second
22648              call for the same DIE.  */
22649           if (!DW_STRING_IS_CANONICAL (attr))
22650             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22651
22652           if (demangled)
22653             {
22654               const char *base;
22655
22656               /* FIXME: we already did this for the partial symbol... */
22657               DW_STRING (attr)
22658                 = ((const char *)
22659                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22660                                   demangled, strlen (demangled)));
22661               DW_STRING_IS_CANONICAL (attr) = 1;
22662               xfree (demangled);
22663
22664               /* Strip any leading namespaces/classes, keep only the base name.
22665                  DW_AT_name for named DIEs does not contain the prefixes.  */
22666               base = strrchr (DW_STRING (attr), ':');
22667               if (base && base > DW_STRING (attr) && base[-1] == ':')
22668                 return &base[1];
22669               else
22670                 return DW_STRING (attr);
22671             }
22672         }
22673       break;
22674
22675     default:
22676       break;
22677     }
22678
22679   if (!DW_STRING_IS_CANONICAL (attr))
22680     {
22681       DW_STRING (attr)
22682         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22683                                     &objfile->per_bfd->storage_obstack);
22684       DW_STRING_IS_CANONICAL (attr) = 1;
22685     }
22686   return DW_STRING (attr);
22687 }
22688
22689 /* Return the die that this die in an extension of, or NULL if there
22690    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22691    containing the return value on output.  */
22692
22693 static struct die_info *
22694 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22695 {
22696   struct attribute *attr;
22697
22698   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22699   if (attr == NULL)
22700     return NULL;
22701
22702   return follow_die_ref (die, attr, ext_cu);
22703 }
22704
22705 /* Convert a DIE tag into its string name.  */
22706
22707 static const char *
22708 dwarf_tag_name (unsigned tag)
22709 {
22710   const char *name = get_DW_TAG_name (tag);
22711
22712   if (name == NULL)
22713     return "DW_TAG_<unknown>";
22714
22715   return name;
22716 }
22717
22718 /* Convert a DWARF attribute code into its string name.  */
22719
22720 static const char *
22721 dwarf_attr_name (unsigned attr)
22722 {
22723   const char *name;
22724
22725 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22726   if (attr == DW_AT_MIPS_fde)
22727     return "DW_AT_MIPS_fde";
22728 #else
22729   if (attr == DW_AT_HP_block_index)
22730     return "DW_AT_HP_block_index";
22731 #endif
22732
22733   name = get_DW_AT_name (attr);
22734
22735   if (name == NULL)
22736     return "DW_AT_<unknown>";
22737
22738   return name;
22739 }
22740
22741 /* Convert a DWARF value form code into its string name.  */
22742
22743 static const char *
22744 dwarf_form_name (unsigned form)
22745 {
22746   const char *name = get_DW_FORM_name (form);
22747
22748   if (name == NULL)
22749     return "DW_FORM_<unknown>";
22750
22751   return name;
22752 }
22753
22754 static const char *
22755 dwarf_bool_name (unsigned mybool)
22756 {
22757   if (mybool)
22758     return "TRUE";
22759   else
22760     return "FALSE";
22761 }
22762
22763 /* Convert a DWARF type code into its string name.  */
22764
22765 static const char *
22766 dwarf_type_encoding_name (unsigned enc)
22767 {
22768   const char *name = get_DW_ATE_name (enc);
22769
22770   if (name == NULL)
22771     return "DW_ATE_<unknown>";
22772
22773   return name;
22774 }
22775
22776 static void
22777 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22778 {
22779   unsigned int i;
22780
22781   print_spaces (indent, f);
22782   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
22783                       dwarf_tag_name (die->tag), die->abbrev,
22784                       to_underlying (die->sect_off));
22785
22786   if (die->parent != NULL)
22787     {
22788       print_spaces (indent, f);
22789       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
22790                           to_underlying (die->parent->sect_off));
22791     }
22792
22793   print_spaces (indent, f);
22794   fprintf_unfiltered (f, "  has children: %s\n",
22795            dwarf_bool_name (die->child != NULL));
22796
22797   print_spaces (indent, f);
22798   fprintf_unfiltered (f, "  attributes:\n");
22799
22800   for (i = 0; i < die->num_attrs; ++i)
22801     {
22802       print_spaces (indent, f);
22803       fprintf_unfiltered (f, "    %s (%s) ",
22804                dwarf_attr_name (die->attrs[i].name),
22805                dwarf_form_name (die->attrs[i].form));
22806
22807       switch (die->attrs[i].form)
22808         {
22809         case DW_FORM_addr:
22810         case DW_FORM_GNU_addr_index:
22811           fprintf_unfiltered (f, "address: ");
22812           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22813           break;
22814         case DW_FORM_block2:
22815         case DW_FORM_block4:
22816         case DW_FORM_block:
22817         case DW_FORM_block1:
22818           fprintf_unfiltered (f, "block: size %s",
22819                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22820           break;
22821         case DW_FORM_exprloc:
22822           fprintf_unfiltered (f, "expression: size %s",
22823                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22824           break;
22825         case DW_FORM_data16:
22826           fprintf_unfiltered (f, "constant of 16 bytes");
22827           break;
22828         case DW_FORM_ref_addr:
22829           fprintf_unfiltered (f, "ref address: ");
22830           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22831           break;
22832         case DW_FORM_GNU_ref_alt:
22833           fprintf_unfiltered (f, "alt ref address: ");
22834           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22835           break;
22836         case DW_FORM_ref1:
22837         case DW_FORM_ref2:
22838         case DW_FORM_ref4:
22839         case DW_FORM_ref8:
22840         case DW_FORM_ref_udata:
22841           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22842                               (long) (DW_UNSND (&die->attrs[i])));
22843           break;
22844         case DW_FORM_data1:
22845         case DW_FORM_data2:
22846         case DW_FORM_data4:
22847         case DW_FORM_data8:
22848         case DW_FORM_udata:
22849         case DW_FORM_sdata:
22850           fprintf_unfiltered (f, "constant: %s",
22851                               pulongest (DW_UNSND (&die->attrs[i])));
22852           break;
22853         case DW_FORM_sec_offset:
22854           fprintf_unfiltered (f, "section offset: %s",
22855                               pulongest (DW_UNSND (&die->attrs[i])));
22856           break;
22857         case DW_FORM_ref_sig8:
22858           fprintf_unfiltered (f, "signature: %s",
22859                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22860           break;
22861         case DW_FORM_string:
22862         case DW_FORM_strp:
22863         case DW_FORM_line_strp:
22864         case DW_FORM_GNU_str_index:
22865         case DW_FORM_GNU_strp_alt:
22866           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22867                    DW_STRING (&die->attrs[i])
22868                    ? DW_STRING (&die->attrs[i]) : "",
22869                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22870           break;
22871         case DW_FORM_flag:
22872           if (DW_UNSND (&die->attrs[i]))
22873             fprintf_unfiltered (f, "flag: TRUE");
22874           else
22875             fprintf_unfiltered (f, "flag: FALSE");
22876           break;
22877         case DW_FORM_flag_present:
22878           fprintf_unfiltered (f, "flag: TRUE");
22879           break;
22880         case DW_FORM_indirect:
22881           /* The reader will have reduced the indirect form to
22882              the "base form" so this form should not occur.  */
22883           fprintf_unfiltered (f, 
22884                               "unexpected attribute form: DW_FORM_indirect");
22885           break;
22886         case DW_FORM_implicit_const:
22887           fprintf_unfiltered (f, "constant: %s",
22888                               plongest (DW_SND (&die->attrs[i])));
22889           break;
22890         default:
22891           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22892                    die->attrs[i].form);
22893           break;
22894         }
22895       fprintf_unfiltered (f, "\n");
22896     }
22897 }
22898
22899 static void
22900 dump_die_for_error (struct die_info *die)
22901 {
22902   dump_die_shallow (gdb_stderr, 0, die);
22903 }
22904
22905 static void
22906 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22907 {
22908   int indent = level * 4;
22909
22910   gdb_assert (die != NULL);
22911
22912   if (level >= max_level)
22913     return;
22914
22915   dump_die_shallow (f, indent, die);
22916
22917   if (die->child != NULL)
22918     {
22919       print_spaces (indent, f);
22920       fprintf_unfiltered (f, "  Children:");
22921       if (level + 1 < max_level)
22922         {
22923           fprintf_unfiltered (f, "\n");
22924           dump_die_1 (f, level + 1, max_level, die->child);
22925         }
22926       else
22927         {
22928           fprintf_unfiltered (f,
22929                               " [not printed, max nesting level reached]\n");
22930         }
22931     }
22932
22933   if (die->sibling != NULL && level > 0)
22934     {
22935       dump_die_1 (f, level, max_level, die->sibling);
22936     }
22937 }
22938
22939 /* This is called from the pdie macro in gdbinit.in.
22940    It's not static so gcc will keep a copy callable from gdb.  */
22941
22942 void
22943 dump_die (struct die_info *die, int max_level)
22944 {
22945   dump_die_1 (gdb_stdlog, 0, max_level, die);
22946 }
22947
22948 static void
22949 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22950 {
22951   void **slot;
22952
22953   slot = htab_find_slot_with_hash (cu->die_hash, die,
22954                                    to_underlying (die->sect_off),
22955                                    INSERT);
22956
22957   *slot = die;
22958 }
22959
22960 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22961    required kind.  */
22962
22963 static sect_offset
22964 dwarf2_get_ref_die_offset (const struct attribute *attr)
22965 {
22966   if (attr_form_is_ref (attr))
22967     return (sect_offset) DW_UNSND (attr);
22968
22969   complaint (&symfile_complaints,
22970              _("unsupported die ref attribute form: '%s'"),
22971              dwarf_form_name (attr->form));
22972   return {};
22973 }
22974
22975 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22976  * the value held by the attribute is not constant.  */
22977
22978 static LONGEST
22979 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22980 {
22981   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22982     return DW_SND (attr);
22983   else if (attr->form == DW_FORM_udata
22984            || attr->form == DW_FORM_data1
22985            || attr->form == DW_FORM_data2
22986            || attr->form == DW_FORM_data4
22987            || attr->form == DW_FORM_data8)
22988     return DW_UNSND (attr);
22989   else
22990     {
22991       /* For DW_FORM_data16 see attr_form_is_constant.  */
22992       complaint (&symfile_complaints,
22993                  _("Attribute value is not a constant (%s)"),
22994                  dwarf_form_name (attr->form));
22995       return default_value;
22996     }
22997 }
22998
22999 /* Follow reference or signature attribute ATTR of SRC_DIE.
23000    On entry *REF_CU is the CU of SRC_DIE.
23001    On exit *REF_CU is the CU of the result.  */
23002
23003 static struct die_info *
23004 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
23005                        struct dwarf2_cu **ref_cu)
23006 {
23007   struct die_info *die;
23008
23009   if (attr_form_is_ref (attr))
23010     die = follow_die_ref (src_die, attr, ref_cu);
23011   else if (attr->form == DW_FORM_ref_sig8)
23012     die = follow_die_sig (src_die, attr, ref_cu);
23013   else
23014     {
23015       dump_die_for_error (src_die);
23016       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
23017              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23018     }
23019
23020   return die;
23021 }
23022
23023 /* Follow reference OFFSET.
23024    On entry *REF_CU is the CU of the source die referencing OFFSET.
23025    On exit *REF_CU is the CU of the result.
23026    Returns NULL if OFFSET is invalid.  */
23027
23028 static struct die_info *
23029 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
23030                    struct dwarf2_cu **ref_cu)
23031 {
23032   struct die_info temp_die;
23033   struct dwarf2_cu *target_cu, *cu = *ref_cu;
23034   struct dwarf2_per_objfile *dwarf2_per_objfile
23035     = cu->per_cu->dwarf2_per_objfile;
23036   struct objfile *objfile = dwarf2_per_objfile->objfile;
23037
23038   gdb_assert (cu->per_cu != NULL);
23039
23040   target_cu = cu;
23041
23042   if (cu->per_cu->is_debug_types)
23043     {
23044       /* .debug_types CUs cannot reference anything outside their CU.
23045          If they need to, they have to reference a signatured type via
23046          DW_FORM_ref_sig8.  */
23047       if (!offset_in_cu_p (&cu->header, sect_off))
23048         return NULL;
23049     }
23050   else if (offset_in_dwz != cu->per_cu->is_dwz
23051            || !offset_in_cu_p (&cu->header, sect_off))
23052     {
23053       struct dwarf2_per_cu_data *per_cu;
23054
23055       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
23056                                                  dwarf2_per_objfile);
23057
23058       /* If necessary, add it to the queue and load its DIEs.  */
23059       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
23060         load_full_comp_unit (per_cu, cu->language);
23061
23062       target_cu = per_cu->cu;
23063     }
23064   else if (cu->dies == NULL)
23065     {
23066       /* We're loading full DIEs during partial symbol reading.  */
23067       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
23068       load_full_comp_unit (cu->per_cu, language_minimal);
23069     }
23070
23071   *ref_cu = target_cu;
23072   temp_die.sect_off = sect_off;
23073   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
23074                                                   &temp_die,
23075                                                   to_underlying (sect_off));
23076 }
23077
23078 /* Follow reference attribute ATTR of SRC_DIE.
23079    On entry *REF_CU is the CU of SRC_DIE.
23080    On exit *REF_CU is the CU of the result.  */
23081
23082 static struct die_info *
23083 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
23084                 struct dwarf2_cu **ref_cu)
23085 {
23086   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
23087   struct dwarf2_cu *cu = *ref_cu;
23088   struct die_info *die;
23089
23090   die = follow_die_offset (sect_off,
23091                            (attr->form == DW_FORM_GNU_ref_alt
23092                             || cu->per_cu->is_dwz),
23093                            ref_cu);
23094   if (!die)
23095     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
23096            "at 0x%x [in module %s]"),
23097            to_underlying (sect_off), to_underlying (src_die->sect_off),
23098            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
23099
23100   return die;
23101 }
23102
23103 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
23104    Returned value is intended for DW_OP_call*.  Returned
23105    dwarf2_locexpr_baton->data has lifetime of
23106    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
23107
23108 struct dwarf2_locexpr_baton
23109 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
23110                                struct dwarf2_per_cu_data *per_cu,
23111                                CORE_ADDR (*get_frame_pc) (void *baton),
23112                                void *baton)
23113 {
23114   struct dwarf2_cu *cu;
23115   struct die_info *die;
23116   struct attribute *attr;
23117   struct dwarf2_locexpr_baton retval;
23118   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23119   struct dwarf2_per_objfile *dwarf2_per_objfile
23120     = get_dwarf2_per_objfile (objfile);
23121
23122   if (per_cu->cu == NULL)
23123     load_cu (per_cu);
23124   cu = per_cu->cu;
23125   if (cu == NULL)
23126     {
23127       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23128          Instead just throw an error, not much else we can do.  */
23129       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23130              to_underlying (sect_off), objfile_name (objfile));
23131     }
23132
23133   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23134   if (!die)
23135     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23136            to_underlying (sect_off), objfile_name (objfile));
23137
23138   attr = dwarf2_attr (die, DW_AT_location, cu);
23139   if (!attr)
23140     {
23141       /* DWARF: "If there is no such attribute, then there is no effect.".
23142          DATA is ignored if SIZE is 0.  */
23143
23144       retval.data = NULL;
23145       retval.size = 0;
23146     }
23147   else if (attr_form_is_section_offset (attr))
23148     {
23149       struct dwarf2_loclist_baton loclist_baton;
23150       CORE_ADDR pc = (*get_frame_pc) (baton);
23151       size_t size;
23152
23153       fill_in_loclist_baton (cu, &loclist_baton, attr);
23154
23155       retval.data = dwarf2_find_location_expression (&loclist_baton,
23156                                                      &size, pc);
23157       retval.size = size;
23158     }
23159   else
23160     {
23161       if (!attr_form_is_block (attr))
23162         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
23163                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23164                to_underlying (sect_off), objfile_name (objfile));
23165
23166       retval.data = DW_BLOCK (attr)->data;
23167       retval.size = DW_BLOCK (attr)->size;
23168     }
23169   retval.per_cu = cu->per_cu;
23170
23171   age_cached_comp_units (dwarf2_per_objfile);
23172
23173   return retval;
23174 }
23175
23176 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23177    offset.  */
23178
23179 struct dwarf2_locexpr_baton
23180 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23181                              struct dwarf2_per_cu_data *per_cu,
23182                              CORE_ADDR (*get_frame_pc) (void *baton),
23183                              void *baton)
23184 {
23185   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23186
23187   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23188 }
23189
23190 /* Write a constant of a given type as target-ordered bytes into
23191    OBSTACK.  */
23192
23193 static const gdb_byte *
23194 write_constant_as_bytes (struct obstack *obstack,
23195                          enum bfd_endian byte_order,
23196                          struct type *type,
23197                          ULONGEST value,
23198                          LONGEST *len)
23199 {
23200   gdb_byte *result;
23201
23202   *len = TYPE_LENGTH (type);
23203   result = (gdb_byte *) obstack_alloc (obstack, *len);
23204   store_unsigned_integer (result, *len, byte_order, value);
23205
23206   return result;
23207 }
23208
23209 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23210    pointer to the constant bytes and set LEN to the length of the
23211    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23212    does not have a DW_AT_const_value, return NULL.  */
23213
23214 const gdb_byte *
23215 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23216                              struct dwarf2_per_cu_data *per_cu,
23217                              struct obstack *obstack,
23218                              LONGEST *len)
23219 {
23220   struct dwarf2_cu *cu;
23221   struct die_info *die;
23222   struct attribute *attr;
23223   const gdb_byte *result = NULL;
23224   struct type *type;
23225   LONGEST value;
23226   enum bfd_endian byte_order;
23227   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23228
23229   if (per_cu->cu == NULL)
23230     load_cu (per_cu);
23231   cu = per_cu->cu;
23232   if (cu == NULL)
23233     {
23234       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23235          Instead just throw an error, not much else we can do.  */
23236       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
23237              to_underlying (sect_off), objfile_name (objfile));
23238     }
23239
23240   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23241   if (!die)
23242     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
23243            to_underlying (sect_off), objfile_name (objfile));
23244
23245
23246   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23247   if (attr == NULL)
23248     return NULL;
23249
23250   byte_order = (bfd_big_endian (objfile->obfd)
23251                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23252
23253   switch (attr->form)
23254     {
23255     case DW_FORM_addr:
23256     case DW_FORM_GNU_addr_index:
23257       {
23258         gdb_byte *tem;
23259
23260         *len = cu->header.addr_size;
23261         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23262         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23263         result = tem;
23264       }
23265       break;
23266     case DW_FORM_string:
23267     case DW_FORM_strp:
23268     case DW_FORM_GNU_str_index:
23269     case DW_FORM_GNU_strp_alt:
23270       /* DW_STRING is already allocated on the objfile obstack, point
23271          directly to it.  */
23272       result = (const gdb_byte *) DW_STRING (attr);
23273       *len = strlen (DW_STRING (attr));
23274       break;
23275     case DW_FORM_block1:
23276     case DW_FORM_block2:
23277     case DW_FORM_block4:
23278     case DW_FORM_block:
23279     case DW_FORM_exprloc:
23280     case DW_FORM_data16:
23281       result = DW_BLOCK (attr)->data;
23282       *len = DW_BLOCK (attr)->size;
23283       break;
23284
23285       /* The DW_AT_const_value attributes are supposed to carry the
23286          symbol's value "represented as it would be on the target
23287          architecture."  By the time we get here, it's already been
23288          converted to host endianness, so we just need to sign- or
23289          zero-extend it as appropriate.  */
23290     case DW_FORM_data1:
23291       type = die_type (die, cu);
23292       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23293       if (result == NULL)
23294         result = write_constant_as_bytes (obstack, byte_order,
23295                                           type, value, len);
23296       break;
23297     case DW_FORM_data2:
23298       type = die_type (die, cu);
23299       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23300       if (result == NULL)
23301         result = write_constant_as_bytes (obstack, byte_order,
23302                                           type, value, len);
23303       break;
23304     case DW_FORM_data4:
23305       type = die_type (die, cu);
23306       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23307       if (result == NULL)
23308         result = write_constant_as_bytes (obstack, byte_order,
23309                                           type, value, len);
23310       break;
23311     case DW_FORM_data8:
23312       type = die_type (die, cu);
23313       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23314       if (result == NULL)
23315         result = write_constant_as_bytes (obstack, byte_order,
23316                                           type, value, len);
23317       break;
23318
23319     case DW_FORM_sdata:
23320     case DW_FORM_implicit_const:
23321       type = die_type (die, cu);
23322       result = write_constant_as_bytes (obstack, byte_order,
23323                                         type, DW_SND (attr), len);
23324       break;
23325
23326     case DW_FORM_udata:
23327       type = die_type (die, cu);
23328       result = write_constant_as_bytes (obstack, byte_order,
23329                                         type, DW_UNSND (attr), len);
23330       break;
23331
23332     default:
23333       complaint (&symfile_complaints,
23334                  _("unsupported const value attribute form: '%s'"),
23335                  dwarf_form_name (attr->form));
23336       break;
23337     }
23338
23339   return result;
23340 }
23341
23342 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23343    valid type for this die is found.  */
23344
23345 struct type *
23346 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23347                                 struct dwarf2_per_cu_data *per_cu)
23348 {
23349   struct dwarf2_cu *cu;
23350   struct die_info *die;
23351
23352   if (per_cu->cu == NULL)
23353     load_cu (per_cu);
23354   cu = per_cu->cu;
23355   if (!cu)
23356     return NULL;
23357
23358   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23359   if (!die)
23360     return NULL;
23361
23362   return die_type (die, cu);
23363 }
23364
23365 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23366    PER_CU.  */
23367
23368 struct type *
23369 dwarf2_get_die_type (cu_offset die_offset,
23370                      struct dwarf2_per_cu_data *per_cu)
23371 {
23372   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23373   return get_die_type_at_offset (die_offset_sect, per_cu);
23374 }
23375
23376 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23377    On entry *REF_CU is the CU of SRC_DIE.
23378    On exit *REF_CU is the CU of the result.
23379    Returns NULL if the referenced DIE isn't found.  */
23380
23381 static struct die_info *
23382 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23383                   struct dwarf2_cu **ref_cu)
23384 {
23385   struct die_info temp_die;
23386   struct dwarf2_cu *sig_cu;
23387   struct die_info *die;
23388
23389   /* While it might be nice to assert sig_type->type == NULL here,
23390      we can get here for DW_AT_imported_declaration where we need
23391      the DIE not the type.  */
23392
23393   /* If necessary, add it to the queue and load its DIEs.  */
23394
23395   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23396     read_signatured_type (sig_type);
23397
23398   sig_cu = sig_type->per_cu.cu;
23399   gdb_assert (sig_cu != NULL);
23400   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23401   temp_die.sect_off = sig_type->type_offset_in_section;
23402   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23403                                                  to_underlying (temp_die.sect_off));
23404   if (die)
23405     {
23406       struct dwarf2_per_objfile *dwarf2_per_objfile
23407         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23408
23409       /* For .gdb_index version 7 keep track of included TUs.
23410          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23411       if (dwarf2_per_objfile->index_table != NULL
23412           && dwarf2_per_objfile->index_table->version <= 7)
23413         {
23414           VEC_safe_push (dwarf2_per_cu_ptr,
23415                          (*ref_cu)->per_cu->imported_symtabs,
23416                          sig_cu->per_cu);
23417         }
23418
23419       *ref_cu = sig_cu;
23420       return die;
23421     }
23422
23423   return NULL;
23424 }
23425
23426 /* Follow signatured type referenced by ATTR in SRC_DIE.
23427    On entry *REF_CU is the CU of SRC_DIE.
23428    On exit *REF_CU is the CU of the result.
23429    The result is the DIE of the type.
23430    If the referenced type cannot be found an error is thrown.  */
23431
23432 static struct die_info *
23433 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23434                 struct dwarf2_cu **ref_cu)
23435 {
23436   ULONGEST signature = DW_SIGNATURE (attr);
23437   struct signatured_type *sig_type;
23438   struct die_info *die;
23439
23440   gdb_assert (attr->form == DW_FORM_ref_sig8);
23441
23442   sig_type = lookup_signatured_type (*ref_cu, signature);
23443   /* sig_type will be NULL if the signatured type is missing from
23444      the debug info.  */
23445   if (sig_type == NULL)
23446     {
23447       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23448                " from DIE at 0x%x [in module %s]"),
23449              hex_string (signature), to_underlying (src_die->sect_off),
23450              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23451     }
23452
23453   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23454   if (die == NULL)
23455     {
23456       dump_die_for_error (src_die);
23457       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23458                " from DIE at 0x%x [in module %s]"),
23459              hex_string (signature), to_underlying (src_die->sect_off),
23460              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23461     }
23462
23463   return die;
23464 }
23465
23466 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23467    reading in and processing the type unit if necessary.  */
23468
23469 static struct type *
23470 get_signatured_type (struct die_info *die, ULONGEST signature,
23471                      struct dwarf2_cu *cu)
23472 {
23473   struct dwarf2_per_objfile *dwarf2_per_objfile
23474     = cu->per_cu->dwarf2_per_objfile;
23475   struct signatured_type *sig_type;
23476   struct dwarf2_cu *type_cu;
23477   struct die_info *type_die;
23478   struct type *type;
23479
23480   sig_type = lookup_signatured_type (cu, signature);
23481   /* sig_type will be NULL if the signatured type is missing from
23482      the debug info.  */
23483   if (sig_type == NULL)
23484     {
23485       complaint (&symfile_complaints,
23486                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
23487                    " from DIE at 0x%x [in module %s]"),
23488                  hex_string (signature), to_underlying (die->sect_off),
23489                  objfile_name (dwarf2_per_objfile->objfile));
23490       return build_error_marker_type (cu, die);
23491     }
23492
23493   /* If we already know the type we're done.  */
23494   if (sig_type->type != NULL)
23495     return sig_type->type;
23496
23497   type_cu = cu;
23498   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23499   if (type_die != NULL)
23500     {
23501       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23502          is created.  This is important, for example, because for c++ classes
23503          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23504       type = read_type_die (type_die, type_cu);
23505       if (type == NULL)
23506         {
23507           complaint (&symfile_complaints,
23508                      _("Dwarf Error: Cannot build signatured type %s"
23509                        " referenced from DIE at 0x%x [in module %s]"),
23510                      hex_string (signature), to_underlying (die->sect_off),
23511                      objfile_name (dwarf2_per_objfile->objfile));
23512           type = build_error_marker_type (cu, die);
23513         }
23514     }
23515   else
23516     {
23517       complaint (&symfile_complaints,
23518                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
23519                    " from DIE at 0x%x [in module %s]"),
23520                  hex_string (signature), to_underlying (die->sect_off),
23521                  objfile_name (dwarf2_per_objfile->objfile));
23522       type = build_error_marker_type (cu, die);
23523     }
23524   sig_type->type = type;
23525
23526   return type;
23527 }
23528
23529 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23530    reading in and processing the type unit if necessary.  */
23531
23532 static struct type *
23533 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23534                           struct dwarf2_cu *cu) /* ARI: editCase function */
23535 {
23536   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23537   if (attr_form_is_ref (attr))
23538     {
23539       struct dwarf2_cu *type_cu = cu;
23540       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23541
23542       return read_type_die (type_die, type_cu);
23543     }
23544   else if (attr->form == DW_FORM_ref_sig8)
23545     {
23546       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23547     }
23548   else
23549     {
23550       struct dwarf2_per_objfile *dwarf2_per_objfile
23551         = cu->per_cu->dwarf2_per_objfile;
23552
23553       complaint (&symfile_complaints,
23554                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23555                    " at 0x%x [in module %s]"),
23556                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
23557                  objfile_name (dwarf2_per_objfile->objfile));
23558       return build_error_marker_type (cu, die);
23559     }
23560 }
23561
23562 /* Load the DIEs associated with type unit PER_CU into memory.  */
23563
23564 static void
23565 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23566 {
23567   struct signatured_type *sig_type;
23568
23569   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23570   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23571
23572   /* We have the per_cu, but we need the signatured_type.
23573      Fortunately this is an easy translation.  */
23574   gdb_assert (per_cu->is_debug_types);
23575   sig_type = (struct signatured_type *) per_cu;
23576
23577   gdb_assert (per_cu->cu == NULL);
23578
23579   read_signatured_type (sig_type);
23580
23581   gdb_assert (per_cu->cu != NULL);
23582 }
23583
23584 /* die_reader_func for read_signatured_type.
23585    This is identical to load_full_comp_unit_reader,
23586    but is kept separate for now.  */
23587
23588 static void
23589 read_signatured_type_reader (const struct die_reader_specs *reader,
23590                              const gdb_byte *info_ptr,
23591                              struct die_info *comp_unit_die,
23592                              int has_children,
23593                              void *data)
23594 {
23595   struct dwarf2_cu *cu = reader->cu;
23596
23597   gdb_assert (cu->die_hash == NULL);
23598   cu->die_hash =
23599     htab_create_alloc_ex (cu->header.length / 12,
23600                           die_hash,
23601                           die_eq,
23602                           NULL,
23603                           &cu->comp_unit_obstack,
23604                           hashtab_obstack_allocate,
23605                           dummy_obstack_deallocate);
23606
23607   if (has_children)
23608     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23609                                                   &info_ptr, comp_unit_die);
23610   cu->dies = comp_unit_die;
23611   /* comp_unit_die is not stored in die_hash, no need.  */
23612
23613   /* We try not to read any attributes in this function, because not
23614      all CUs needed for references have been loaded yet, and symbol
23615      table processing isn't initialized.  But we have to set the CU language,
23616      or we won't be able to build types correctly.
23617      Similarly, if we do not read the producer, we can not apply
23618      producer-specific interpretation.  */
23619   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23620 }
23621
23622 /* Read in a signatured type and build its CU and DIEs.
23623    If the type is a stub for the real type in a DWO file,
23624    read in the real type from the DWO file as well.  */
23625
23626 static void
23627 read_signatured_type (struct signatured_type *sig_type)
23628 {
23629   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23630
23631   gdb_assert (per_cu->is_debug_types);
23632   gdb_assert (per_cu->cu == NULL);
23633
23634   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
23635                            read_signatured_type_reader, NULL);
23636   sig_type->per_cu.tu_read = 1;
23637 }
23638
23639 /* Decode simple location descriptions.
23640    Given a pointer to a dwarf block that defines a location, compute
23641    the location and return the value.
23642
23643    NOTE drow/2003-11-18: This function is called in two situations
23644    now: for the address of static or global variables (partial symbols
23645    only) and for offsets into structures which are expected to be
23646    (more or less) constant.  The partial symbol case should go away,
23647    and only the constant case should remain.  That will let this
23648    function complain more accurately.  A few special modes are allowed
23649    without complaint for global variables (for instance, global
23650    register values and thread-local values).
23651
23652    A location description containing no operations indicates that the
23653    object is optimized out.  The return value is 0 for that case.
23654    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23655    callers will only want a very basic result and this can become a
23656    complaint.
23657
23658    Note that stack[0] is unused except as a default error return.  */
23659
23660 static CORE_ADDR
23661 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23662 {
23663   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23664   size_t i;
23665   size_t size = blk->size;
23666   const gdb_byte *data = blk->data;
23667   CORE_ADDR stack[64];
23668   int stacki;
23669   unsigned int bytes_read, unsnd;
23670   gdb_byte op;
23671
23672   i = 0;
23673   stacki = 0;
23674   stack[stacki] = 0;
23675   stack[++stacki] = 0;
23676
23677   while (i < size)
23678     {
23679       op = data[i++];
23680       switch (op)
23681         {
23682         case DW_OP_lit0:
23683         case DW_OP_lit1:
23684         case DW_OP_lit2:
23685         case DW_OP_lit3:
23686         case DW_OP_lit4:
23687         case DW_OP_lit5:
23688         case DW_OP_lit6:
23689         case DW_OP_lit7:
23690         case DW_OP_lit8:
23691         case DW_OP_lit9:
23692         case DW_OP_lit10:
23693         case DW_OP_lit11:
23694         case DW_OP_lit12:
23695         case DW_OP_lit13:
23696         case DW_OP_lit14:
23697         case DW_OP_lit15:
23698         case DW_OP_lit16:
23699         case DW_OP_lit17:
23700         case DW_OP_lit18:
23701         case DW_OP_lit19:
23702         case DW_OP_lit20:
23703         case DW_OP_lit21:
23704         case DW_OP_lit22:
23705         case DW_OP_lit23:
23706         case DW_OP_lit24:
23707         case DW_OP_lit25:
23708         case DW_OP_lit26:
23709         case DW_OP_lit27:
23710         case DW_OP_lit28:
23711         case DW_OP_lit29:
23712         case DW_OP_lit30:
23713         case DW_OP_lit31:
23714           stack[++stacki] = op - DW_OP_lit0;
23715           break;
23716
23717         case DW_OP_reg0:
23718         case DW_OP_reg1:
23719         case DW_OP_reg2:
23720         case DW_OP_reg3:
23721         case DW_OP_reg4:
23722         case DW_OP_reg5:
23723         case DW_OP_reg6:
23724         case DW_OP_reg7:
23725         case DW_OP_reg8:
23726         case DW_OP_reg9:
23727         case DW_OP_reg10:
23728         case DW_OP_reg11:
23729         case DW_OP_reg12:
23730         case DW_OP_reg13:
23731         case DW_OP_reg14:
23732         case DW_OP_reg15:
23733         case DW_OP_reg16:
23734         case DW_OP_reg17:
23735         case DW_OP_reg18:
23736         case DW_OP_reg19:
23737         case DW_OP_reg20:
23738         case DW_OP_reg21:
23739         case DW_OP_reg22:
23740         case DW_OP_reg23:
23741         case DW_OP_reg24:
23742         case DW_OP_reg25:
23743         case DW_OP_reg26:
23744         case DW_OP_reg27:
23745         case DW_OP_reg28:
23746         case DW_OP_reg29:
23747         case DW_OP_reg30:
23748         case DW_OP_reg31:
23749           stack[++stacki] = op - DW_OP_reg0;
23750           if (i < size)
23751             dwarf2_complex_location_expr_complaint ();
23752           break;
23753
23754         case DW_OP_regx:
23755           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23756           i += bytes_read;
23757           stack[++stacki] = unsnd;
23758           if (i < size)
23759             dwarf2_complex_location_expr_complaint ();
23760           break;
23761
23762         case DW_OP_addr:
23763           stack[++stacki] = read_address (objfile->obfd, &data[i],
23764                                           cu, &bytes_read);
23765           i += bytes_read;
23766           break;
23767
23768         case DW_OP_const1u:
23769           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23770           i += 1;
23771           break;
23772
23773         case DW_OP_const1s:
23774           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23775           i += 1;
23776           break;
23777
23778         case DW_OP_const2u:
23779           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23780           i += 2;
23781           break;
23782
23783         case DW_OP_const2s:
23784           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23785           i += 2;
23786           break;
23787
23788         case DW_OP_const4u:
23789           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23790           i += 4;
23791           break;
23792
23793         case DW_OP_const4s:
23794           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23795           i += 4;
23796           break;
23797
23798         case DW_OP_const8u:
23799           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23800           i += 8;
23801           break;
23802
23803         case DW_OP_constu:
23804           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23805                                                   &bytes_read);
23806           i += bytes_read;
23807           break;
23808
23809         case DW_OP_consts:
23810           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23811           i += bytes_read;
23812           break;
23813
23814         case DW_OP_dup:
23815           stack[stacki + 1] = stack[stacki];
23816           stacki++;
23817           break;
23818
23819         case DW_OP_plus:
23820           stack[stacki - 1] += stack[stacki];
23821           stacki--;
23822           break;
23823
23824         case DW_OP_plus_uconst:
23825           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23826                                                  &bytes_read);
23827           i += bytes_read;
23828           break;
23829
23830         case DW_OP_minus:
23831           stack[stacki - 1] -= stack[stacki];
23832           stacki--;
23833           break;
23834
23835         case DW_OP_deref:
23836           /* If we're not the last op, then we definitely can't encode
23837              this using GDB's address_class enum.  This is valid for partial
23838              global symbols, although the variable's address will be bogus
23839              in the psymtab.  */
23840           if (i < size)
23841             dwarf2_complex_location_expr_complaint ();
23842           break;
23843
23844         case DW_OP_GNU_push_tls_address:
23845         case DW_OP_form_tls_address:
23846           /* The top of the stack has the offset from the beginning
23847              of the thread control block at which the variable is located.  */
23848           /* Nothing should follow this operator, so the top of stack would
23849              be returned.  */
23850           /* This is valid for partial global symbols, but the variable's
23851              address will be bogus in the psymtab.  Make it always at least
23852              non-zero to not look as a variable garbage collected by linker
23853              which have DW_OP_addr 0.  */
23854           if (i < size)
23855             dwarf2_complex_location_expr_complaint ();
23856           stack[stacki]++;
23857           break;
23858
23859         case DW_OP_GNU_uninit:
23860           break;
23861
23862         case DW_OP_GNU_addr_index:
23863         case DW_OP_GNU_const_index:
23864           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23865                                                          &bytes_read);
23866           i += bytes_read;
23867           break;
23868
23869         default:
23870           {
23871             const char *name = get_DW_OP_name (op);
23872
23873             if (name)
23874               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
23875                          name);
23876             else
23877               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
23878                          op);
23879           }
23880
23881           return (stack[stacki]);
23882         }
23883
23884       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23885          outside of the allocated space.  Also enforce minimum>0.  */
23886       if (stacki >= ARRAY_SIZE (stack) - 1)
23887         {
23888           complaint (&symfile_complaints,
23889                      _("location description stack overflow"));
23890           return 0;
23891         }
23892
23893       if (stacki <= 0)
23894         {
23895           complaint (&symfile_complaints,
23896                      _("location description stack underflow"));
23897           return 0;
23898         }
23899     }
23900   return (stack[stacki]);
23901 }
23902
23903 /* memory allocation interface */
23904
23905 static struct dwarf_block *
23906 dwarf_alloc_block (struct dwarf2_cu *cu)
23907 {
23908   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23909 }
23910
23911 static struct die_info *
23912 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23913 {
23914   struct die_info *die;
23915   size_t size = sizeof (struct die_info);
23916
23917   if (num_attrs > 1)
23918     size += (num_attrs - 1) * sizeof (struct attribute);
23919
23920   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23921   memset (die, 0, sizeof (struct die_info));
23922   return (die);
23923 }
23924
23925 \f
23926 /* Macro support.  */
23927
23928 /* Return file name relative to the compilation directory of file number I in
23929    *LH's file name table.  The result is allocated using xmalloc; the caller is
23930    responsible for freeing it.  */
23931
23932 static char *
23933 file_file_name (int file, struct line_header *lh)
23934 {
23935   /* Is the file number a valid index into the line header's file name
23936      table?  Remember that file numbers start with one, not zero.  */
23937   if (1 <= file && file <= lh->file_names.size ())
23938     {
23939       const file_entry &fe = lh->file_names[file - 1];
23940
23941       if (!IS_ABSOLUTE_PATH (fe.name))
23942         {
23943           const char *dir = fe.include_dir (lh);
23944           if (dir != NULL)
23945             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23946         }
23947       return xstrdup (fe.name);
23948     }
23949   else
23950     {
23951       /* The compiler produced a bogus file number.  We can at least
23952          record the macro definitions made in the file, even if we
23953          won't be able to find the file by name.  */
23954       char fake_name[80];
23955
23956       xsnprintf (fake_name, sizeof (fake_name),
23957                  "<bad macro file number %d>", file);
23958
23959       complaint (&symfile_complaints,
23960                  _("bad file number in macro information (%d)"),
23961                  file);
23962
23963       return xstrdup (fake_name);
23964     }
23965 }
23966
23967 /* Return the full name of file number I in *LH's file name table.
23968    Use COMP_DIR as the name of the current directory of the
23969    compilation.  The result is allocated using xmalloc; the caller is
23970    responsible for freeing it.  */
23971 static char *
23972 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23973 {
23974   /* Is the file number a valid index into the line header's file name
23975      table?  Remember that file numbers start with one, not zero.  */
23976   if (1 <= file && file <= lh->file_names.size ())
23977     {
23978       char *relative = file_file_name (file, lh);
23979
23980       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23981         return relative;
23982       return reconcat (relative, comp_dir, SLASH_STRING,
23983                        relative, (char *) NULL);
23984     }
23985   else
23986     return file_file_name (file, lh);
23987 }
23988
23989
23990 static struct macro_source_file *
23991 macro_start_file (int file, int line,
23992                   struct macro_source_file *current_file,
23993                   struct line_header *lh)
23994 {
23995   /* File name relative to the compilation directory of this source file.  */
23996   char *file_name = file_file_name (file, lh);
23997
23998   if (! current_file)
23999     {
24000       /* Note: We don't create a macro table for this compilation unit
24001          at all until we actually get a filename.  */
24002       struct macro_table *macro_table = get_macro_table ();
24003
24004       /* If we have no current file, then this must be the start_file
24005          directive for the compilation unit's main source file.  */
24006       current_file = macro_set_main (macro_table, file_name);
24007       macro_define_special (macro_table);
24008     }
24009   else
24010     current_file = macro_include (current_file, line, file_name);
24011
24012   xfree (file_name);
24013
24014   return current_file;
24015 }
24016
24017 static const char *
24018 consume_improper_spaces (const char *p, const char *body)
24019 {
24020   if (*p == ' ')
24021     {
24022       complaint (&symfile_complaints,
24023                  _("macro definition contains spaces "
24024                    "in formal argument list:\n`%s'"),
24025                  body);
24026
24027       while (*p == ' ')
24028         p++;
24029     }
24030
24031   return p;
24032 }
24033
24034
24035 static void
24036 parse_macro_definition (struct macro_source_file *file, int line,
24037                         const char *body)
24038 {
24039   const char *p;
24040
24041   /* The body string takes one of two forms.  For object-like macro
24042      definitions, it should be:
24043
24044         <macro name> " " <definition>
24045
24046      For function-like macro definitions, it should be:
24047
24048         <macro name> "() " <definition>
24049      or
24050         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
24051
24052      Spaces may appear only where explicitly indicated, and in the
24053      <definition>.
24054
24055      The Dwarf 2 spec says that an object-like macro's name is always
24056      followed by a space, but versions of GCC around March 2002 omit
24057      the space when the macro's definition is the empty string.
24058
24059      The Dwarf 2 spec says that there should be no spaces between the
24060      formal arguments in a function-like macro's formal argument list,
24061      but versions of GCC around March 2002 include spaces after the
24062      commas.  */
24063
24064
24065   /* Find the extent of the macro name.  The macro name is terminated
24066      by either a space or null character (for an object-like macro) or
24067      an opening paren (for a function-like macro).  */
24068   for (p = body; *p; p++)
24069     if (*p == ' ' || *p == '(')
24070       break;
24071
24072   if (*p == ' ' || *p == '\0')
24073     {
24074       /* It's an object-like macro.  */
24075       int name_len = p - body;
24076       char *name = savestring (body, name_len);
24077       const char *replacement;
24078
24079       if (*p == ' ')
24080         replacement = body + name_len + 1;
24081       else
24082         {
24083           dwarf2_macro_malformed_definition_complaint (body);
24084           replacement = body + name_len;
24085         }
24086
24087       macro_define_object (file, line, name, replacement);
24088
24089       xfree (name);
24090     }
24091   else if (*p == '(')
24092     {
24093       /* It's a function-like macro.  */
24094       char *name = savestring (body, p - body);
24095       int argc = 0;
24096       int argv_size = 1;
24097       char **argv = XNEWVEC (char *, argv_size);
24098
24099       p++;
24100
24101       p = consume_improper_spaces (p, body);
24102
24103       /* Parse the formal argument list.  */
24104       while (*p && *p != ')')
24105         {
24106           /* Find the extent of the current argument name.  */
24107           const char *arg_start = p;
24108
24109           while (*p && *p != ',' && *p != ')' && *p != ' ')
24110             p++;
24111
24112           if (! *p || p == arg_start)
24113             dwarf2_macro_malformed_definition_complaint (body);
24114           else
24115             {
24116               /* Make sure argv has room for the new argument.  */
24117               if (argc >= argv_size)
24118                 {
24119                   argv_size *= 2;
24120                   argv = XRESIZEVEC (char *, argv, argv_size);
24121                 }
24122
24123               argv[argc++] = savestring (arg_start, p - arg_start);
24124             }
24125
24126           p = consume_improper_spaces (p, body);
24127
24128           /* Consume the comma, if present.  */
24129           if (*p == ',')
24130             {
24131               p++;
24132
24133               p = consume_improper_spaces (p, body);
24134             }
24135         }
24136
24137       if (*p == ')')
24138         {
24139           p++;
24140
24141           if (*p == ' ')
24142             /* Perfectly formed definition, no complaints.  */
24143             macro_define_function (file, line, name,
24144                                    argc, (const char **) argv,
24145                                    p + 1);
24146           else if (*p == '\0')
24147             {
24148               /* Complain, but do define it.  */
24149               dwarf2_macro_malformed_definition_complaint (body);
24150               macro_define_function (file, line, name,
24151                                      argc, (const char **) argv,
24152                                      p);
24153             }
24154           else
24155             /* Just complain.  */
24156             dwarf2_macro_malformed_definition_complaint (body);
24157         }
24158       else
24159         /* Just complain.  */
24160         dwarf2_macro_malformed_definition_complaint (body);
24161
24162       xfree (name);
24163       {
24164         int i;
24165
24166         for (i = 0; i < argc; i++)
24167           xfree (argv[i]);
24168       }
24169       xfree (argv);
24170     }
24171   else
24172     dwarf2_macro_malformed_definition_complaint (body);
24173 }
24174
24175 /* Skip some bytes from BYTES according to the form given in FORM.
24176    Returns the new pointer.  */
24177
24178 static const gdb_byte *
24179 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24180                  enum dwarf_form form,
24181                  unsigned int offset_size,
24182                  struct dwarf2_section_info *section)
24183 {
24184   unsigned int bytes_read;
24185
24186   switch (form)
24187     {
24188     case DW_FORM_data1:
24189     case DW_FORM_flag:
24190       ++bytes;
24191       break;
24192
24193     case DW_FORM_data2:
24194       bytes += 2;
24195       break;
24196
24197     case DW_FORM_data4:
24198       bytes += 4;
24199       break;
24200
24201     case DW_FORM_data8:
24202       bytes += 8;
24203       break;
24204
24205     case DW_FORM_data16:
24206       bytes += 16;
24207       break;
24208
24209     case DW_FORM_string:
24210       read_direct_string (abfd, bytes, &bytes_read);
24211       bytes += bytes_read;
24212       break;
24213
24214     case DW_FORM_sec_offset:
24215     case DW_FORM_strp:
24216     case DW_FORM_GNU_strp_alt:
24217       bytes += offset_size;
24218       break;
24219
24220     case DW_FORM_block:
24221       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24222       bytes += bytes_read;
24223       break;
24224
24225     case DW_FORM_block1:
24226       bytes += 1 + read_1_byte (abfd, bytes);
24227       break;
24228     case DW_FORM_block2:
24229       bytes += 2 + read_2_bytes (abfd, bytes);
24230       break;
24231     case DW_FORM_block4:
24232       bytes += 4 + read_4_bytes (abfd, bytes);
24233       break;
24234
24235     case DW_FORM_sdata:
24236     case DW_FORM_udata:
24237     case DW_FORM_GNU_addr_index:
24238     case DW_FORM_GNU_str_index:
24239       bytes = gdb_skip_leb128 (bytes, buffer_end);
24240       if (bytes == NULL)
24241         {
24242           dwarf2_section_buffer_overflow_complaint (section);
24243           return NULL;
24244         }
24245       break;
24246
24247     case DW_FORM_implicit_const:
24248       break;
24249
24250     default:
24251       {
24252         complaint (&symfile_complaints,
24253                    _("invalid form 0x%x in `%s'"),
24254                    form, get_section_name (section));
24255         return NULL;
24256       }
24257     }
24258
24259   return bytes;
24260 }
24261
24262 /* A helper for dwarf_decode_macros that handles skipping an unknown
24263    opcode.  Returns an updated pointer to the macro data buffer; or,
24264    on error, issues a complaint and returns NULL.  */
24265
24266 static const gdb_byte *
24267 skip_unknown_opcode (unsigned int opcode,
24268                      const gdb_byte **opcode_definitions,
24269                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24270                      bfd *abfd,
24271                      unsigned int offset_size,
24272                      struct dwarf2_section_info *section)
24273 {
24274   unsigned int bytes_read, i;
24275   unsigned long arg;
24276   const gdb_byte *defn;
24277
24278   if (opcode_definitions[opcode] == NULL)
24279     {
24280       complaint (&symfile_complaints,
24281                  _("unrecognized DW_MACFINO opcode 0x%x"),
24282                  opcode);
24283       return NULL;
24284     }
24285
24286   defn = opcode_definitions[opcode];
24287   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24288   defn += bytes_read;
24289
24290   for (i = 0; i < arg; ++i)
24291     {
24292       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24293                                  (enum dwarf_form) defn[i], offset_size,
24294                                  section);
24295       if (mac_ptr == NULL)
24296         {
24297           /* skip_form_bytes already issued the complaint.  */
24298           return NULL;
24299         }
24300     }
24301
24302   return mac_ptr;
24303 }
24304
24305 /* A helper function which parses the header of a macro section.
24306    If the macro section is the extended (for now called "GNU") type,
24307    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24308    the header, or issues a complaint and returns NULL on error.  */
24309
24310 static const gdb_byte *
24311 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24312                           bfd *abfd,
24313                           const gdb_byte *mac_ptr,
24314                           unsigned int *offset_size,
24315                           int section_is_gnu)
24316 {
24317   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24318
24319   if (section_is_gnu)
24320     {
24321       unsigned int version, flags;
24322
24323       version = read_2_bytes (abfd, mac_ptr);
24324       if (version != 4 && version != 5)
24325         {
24326           complaint (&symfile_complaints,
24327                      _("unrecognized version `%d' in .debug_macro section"),
24328                      version);
24329           return NULL;
24330         }
24331       mac_ptr += 2;
24332
24333       flags = read_1_byte (abfd, mac_ptr);
24334       ++mac_ptr;
24335       *offset_size = (flags & 1) ? 8 : 4;
24336
24337       if ((flags & 2) != 0)
24338         /* We don't need the line table offset.  */
24339         mac_ptr += *offset_size;
24340
24341       /* Vendor opcode descriptions.  */
24342       if ((flags & 4) != 0)
24343         {
24344           unsigned int i, count;
24345
24346           count = read_1_byte (abfd, mac_ptr);
24347           ++mac_ptr;
24348           for (i = 0; i < count; ++i)
24349             {
24350               unsigned int opcode, bytes_read;
24351               unsigned long arg;
24352
24353               opcode = read_1_byte (abfd, mac_ptr);
24354               ++mac_ptr;
24355               opcode_definitions[opcode] = mac_ptr;
24356               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24357               mac_ptr += bytes_read;
24358               mac_ptr += arg;
24359             }
24360         }
24361     }
24362
24363   return mac_ptr;
24364 }
24365
24366 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24367    including DW_MACRO_import.  */
24368
24369 static void
24370 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24371                           bfd *abfd,
24372                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24373                           struct macro_source_file *current_file,
24374                           struct line_header *lh,
24375                           struct dwarf2_section_info *section,
24376                           int section_is_gnu, int section_is_dwz,
24377                           unsigned int offset_size,
24378                           htab_t include_hash)
24379 {
24380   struct objfile *objfile = dwarf2_per_objfile->objfile;
24381   enum dwarf_macro_record_type macinfo_type;
24382   int at_commandline;
24383   const gdb_byte *opcode_definitions[256];
24384
24385   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24386                                       &offset_size, section_is_gnu);
24387   if (mac_ptr == NULL)
24388     {
24389       /* We already issued a complaint.  */
24390       return;
24391     }
24392
24393   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24394      GDB is still reading the definitions from command line.  First
24395      DW_MACINFO_start_file will need to be ignored as it was already executed
24396      to create CURRENT_FILE for the main source holding also the command line
24397      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24398      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24399
24400   at_commandline = 1;
24401
24402   do
24403     {
24404       /* Do we at least have room for a macinfo type byte?  */
24405       if (mac_ptr >= mac_end)
24406         {
24407           dwarf2_section_buffer_overflow_complaint (section);
24408           break;
24409         }
24410
24411       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24412       mac_ptr++;
24413
24414       /* Note that we rely on the fact that the corresponding GNU and
24415          DWARF constants are the same.  */
24416       DIAGNOSTIC_PUSH
24417       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24418       switch (macinfo_type)
24419         {
24420           /* A zero macinfo type indicates the end of the macro
24421              information.  */
24422         case 0:
24423           break;
24424
24425         case DW_MACRO_define:
24426         case DW_MACRO_undef:
24427         case DW_MACRO_define_strp:
24428         case DW_MACRO_undef_strp:
24429         case DW_MACRO_define_sup:
24430         case DW_MACRO_undef_sup:
24431           {
24432             unsigned int bytes_read;
24433             int line;
24434             const char *body;
24435             int is_define;
24436
24437             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24438             mac_ptr += bytes_read;
24439
24440             if (macinfo_type == DW_MACRO_define
24441                 || macinfo_type == DW_MACRO_undef)
24442               {
24443                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24444                 mac_ptr += bytes_read;
24445               }
24446             else
24447               {
24448                 LONGEST str_offset;
24449
24450                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24451                 mac_ptr += offset_size;
24452
24453                 if (macinfo_type == DW_MACRO_define_sup
24454                     || macinfo_type == DW_MACRO_undef_sup
24455                     || section_is_dwz)
24456                   {
24457                     struct dwz_file *dwz
24458                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24459
24460                     body = read_indirect_string_from_dwz (objfile,
24461                                                           dwz, str_offset);
24462                   }
24463                 else
24464                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24465                                                          abfd, str_offset);
24466               }
24467
24468             is_define = (macinfo_type == DW_MACRO_define
24469                          || macinfo_type == DW_MACRO_define_strp
24470                          || macinfo_type == DW_MACRO_define_sup);
24471             if (! current_file)
24472               {
24473                 /* DWARF violation as no main source is present.  */
24474                 complaint (&symfile_complaints,
24475                            _("debug info with no main source gives macro %s "
24476                              "on line %d: %s"),
24477                            is_define ? _("definition") : _("undefinition"),
24478                            line, body);
24479                 break;
24480               }
24481             if ((line == 0 && !at_commandline)
24482                 || (line != 0 && at_commandline))
24483               complaint (&symfile_complaints,
24484                          _("debug info gives %s macro %s with %s line %d: %s"),
24485                          at_commandline ? _("command-line") : _("in-file"),
24486                          is_define ? _("definition") : _("undefinition"),
24487                          line == 0 ? _("zero") : _("non-zero"), line, body);
24488
24489             if (is_define)
24490               parse_macro_definition (current_file, line, body);
24491             else
24492               {
24493                 gdb_assert (macinfo_type == DW_MACRO_undef
24494                             || macinfo_type == DW_MACRO_undef_strp
24495                             || macinfo_type == DW_MACRO_undef_sup);
24496                 macro_undef (current_file, line, body);
24497               }
24498           }
24499           break;
24500
24501         case DW_MACRO_start_file:
24502           {
24503             unsigned int bytes_read;
24504             int line, file;
24505
24506             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24507             mac_ptr += bytes_read;
24508             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24509             mac_ptr += bytes_read;
24510
24511             if ((line == 0 && !at_commandline)
24512                 || (line != 0 && at_commandline))
24513               complaint (&symfile_complaints,
24514                          _("debug info gives source %d included "
24515                            "from %s at %s line %d"),
24516                          file, at_commandline ? _("command-line") : _("file"),
24517                          line == 0 ? _("zero") : _("non-zero"), line);
24518
24519             if (at_commandline)
24520               {
24521                 /* This DW_MACRO_start_file was executed in the
24522                    pass one.  */
24523                 at_commandline = 0;
24524               }
24525             else
24526               current_file = macro_start_file (file, line, current_file, lh);
24527           }
24528           break;
24529
24530         case DW_MACRO_end_file:
24531           if (! current_file)
24532             complaint (&symfile_complaints,
24533                        _("macro debug info has an unmatched "
24534                          "`close_file' directive"));
24535           else
24536             {
24537               current_file = current_file->included_by;
24538               if (! current_file)
24539                 {
24540                   enum dwarf_macro_record_type next_type;
24541
24542                   /* GCC circa March 2002 doesn't produce the zero
24543                      type byte marking the end of the compilation
24544                      unit.  Complain if it's not there, but exit no
24545                      matter what.  */
24546
24547                   /* Do we at least have room for a macinfo type byte?  */
24548                   if (mac_ptr >= mac_end)
24549                     {
24550                       dwarf2_section_buffer_overflow_complaint (section);
24551                       return;
24552                     }
24553
24554                   /* We don't increment mac_ptr here, so this is just
24555                      a look-ahead.  */
24556                   next_type
24557                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24558                                                                   mac_ptr);
24559                   if (next_type != 0)
24560                     complaint (&symfile_complaints,
24561                                _("no terminating 0-type entry for "
24562                                  "macros in `.debug_macinfo' section"));
24563
24564                   return;
24565                 }
24566             }
24567           break;
24568
24569         case DW_MACRO_import:
24570         case DW_MACRO_import_sup:
24571           {
24572             LONGEST offset;
24573             void **slot;
24574             bfd *include_bfd = abfd;
24575             struct dwarf2_section_info *include_section = section;
24576             const gdb_byte *include_mac_end = mac_end;
24577             int is_dwz = section_is_dwz;
24578             const gdb_byte *new_mac_ptr;
24579
24580             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24581             mac_ptr += offset_size;
24582
24583             if (macinfo_type == DW_MACRO_import_sup)
24584               {
24585                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24586
24587                 dwarf2_read_section (objfile, &dwz->macro);
24588
24589                 include_section = &dwz->macro;
24590                 include_bfd = get_section_bfd_owner (include_section);
24591                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24592                 is_dwz = 1;
24593               }
24594
24595             new_mac_ptr = include_section->buffer + offset;
24596             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24597
24598             if (*slot != NULL)
24599               {
24600                 /* This has actually happened; see
24601                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24602                 complaint (&symfile_complaints,
24603                            _("recursive DW_MACRO_import in "
24604                              ".debug_macro section"));
24605               }
24606             else
24607               {
24608                 *slot = (void *) new_mac_ptr;
24609
24610                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24611                                           include_bfd, new_mac_ptr,
24612                                           include_mac_end, current_file, lh,
24613                                           section, section_is_gnu, is_dwz,
24614                                           offset_size, include_hash);
24615
24616                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24617               }
24618           }
24619           break;
24620
24621         case DW_MACINFO_vendor_ext:
24622           if (!section_is_gnu)
24623             {
24624               unsigned int bytes_read;
24625
24626               /* This reads the constant, but since we don't recognize
24627                  any vendor extensions, we ignore it.  */
24628               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24629               mac_ptr += bytes_read;
24630               read_direct_string (abfd, mac_ptr, &bytes_read);
24631               mac_ptr += bytes_read;
24632
24633               /* We don't recognize any vendor extensions.  */
24634               break;
24635             }
24636           /* FALLTHROUGH */
24637
24638         default:
24639           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24640                                          mac_ptr, mac_end, abfd, offset_size,
24641                                          section);
24642           if (mac_ptr == NULL)
24643             return;
24644           break;
24645         }
24646       DIAGNOSTIC_POP
24647     } while (macinfo_type != 0);
24648 }
24649
24650 static void
24651 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24652                      int section_is_gnu)
24653 {
24654   struct dwarf2_per_objfile *dwarf2_per_objfile
24655     = cu->per_cu->dwarf2_per_objfile;
24656   struct objfile *objfile = dwarf2_per_objfile->objfile;
24657   struct line_header *lh = cu->line_header;
24658   bfd *abfd;
24659   const gdb_byte *mac_ptr, *mac_end;
24660   struct macro_source_file *current_file = 0;
24661   enum dwarf_macro_record_type macinfo_type;
24662   unsigned int offset_size = cu->header.offset_size;
24663   const gdb_byte *opcode_definitions[256];
24664   void **slot;
24665   struct dwarf2_section_info *section;
24666   const char *section_name;
24667
24668   if (cu->dwo_unit != NULL)
24669     {
24670       if (section_is_gnu)
24671         {
24672           section = &cu->dwo_unit->dwo_file->sections.macro;
24673           section_name = ".debug_macro.dwo";
24674         }
24675       else
24676         {
24677           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24678           section_name = ".debug_macinfo.dwo";
24679         }
24680     }
24681   else
24682     {
24683       if (section_is_gnu)
24684         {
24685           section = &dwarf2_per_objfile->macro;
24686           section_name = ".debug_macro";
24687         }
24688       else
24689         {
24690           section = &dwarf2_per_objfile->macinfo;
24691           section_name = ".debug_macinfo";
24692         }
24693     }
24694
24695   dwarf2_read_section (objfile, section);
24696   if (section->buffer == NULL)
24697     {
24698       complaint (&symfile_complaints, _("missing %s section"), section_name);
24699       return;
24700     }
24701   abfd = get_section_bfd_owner (section);
24702
24703   /* First pass: Find the name of the base filename.
24704      This filename is needed in order to process all macros whose definition
24705      (or undefinition) comes from the command line.  These macros are defined
24706      before the first DW_MACINFO_start_file entry, and yet still need to be
24707      associated to the base file.
24708
24709      To determine the base file name, we scan the macro definitions until we
24710      reach the first DW_MACINFO_start_file entry.  We then initialize
24711      CURRENT_FILE accordingly so that any macro definition found before the
24712      first DW_MACINFO_start_file can still be associated to the base file.  */
24713
24714   mac_ptr = section->buffer + offset;
24715   mac_end = section->buffer + section->size;
24716
24717   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24718                                       &offset_size, section_is_gnu);
24719   if (mac_ptr == NULL)
24720     {
24721       /* We already issued a complaint.  */
24722       return;
24723     }
24724
24725   do
24726     {
24727       /* Do we at least have room for a macinfo type byte?  */
24728       if (mac_ptr >= mac_end)
24729         {
24730           /* Complaint is printed during the second pass as GDB will probably
24731              stop the first pass earlier upon finding
24732              DW_MACINFO_start_file.  */
24733           break;
24734         }
24735
24736       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24737       mac_ptr++;
24738
24739       /* Note that we rely on the fact that the corresponding GNU and
24740          DWARF constants are the same.  */
24741       DIAGNOSTIC_PUSH
24742       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24743       switch (macinfo_type)
24744         {
24745           /* A zero macinfo type indicates the end of the macro
24746              information.  */
24747         case 0:
24748           break;
24749
24750         case DW_MACRO_define:
24751         case DW_MACRO_undef:
24752           /* Only skip the data by MAC_PTR.  */
24753           {
24754             unsigned int bytes_read;
24755
24756             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24757             mac_ptr += bytes_read;
24758             read_direct_string (abfd, mac_ptr, &bytes_read);
24759             mac_ptr += bytes_read;
24760           }
24761           break;
24762
24763         case DW_MACRO_start_file:
24764           {
24765             unsigned int bytes_read;
24766             int line, file;
24767
24768             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24769             mac_ptr += bytes_read;
24770             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24771             mac_ptr += bytes_read;
24772
24773             current_file = macro_start_file (file, line, current_file, lh);
24774           }
24775           break;
24776
24777         case DW_MACRO_end_file:
24778           /* No data to skip by MAC_PTR.  */
24779           break;
24780
24781         case DW_MACRO_define_strp:
24782         case DW_MACRO_undef_strp:
24783         case DW_MACRO_define_sup:
24784         case DW_MACRO_undef_sup:
24785           {
24786             unsigned int bytes_read;
24787
24788             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24789             mac_ptr += bytes_read;
24790             mac_ptr += offset_size;
24791           }
24792           break;
24793
24794         case DW_MACRO_import:
24795         case DW_MACRO_import_sup:
24796           /* Note that, according to the spec, a transparent include
24797              chain cannot call DW_MACRO_start_file.  So, we can just
24798              skip this opcode.  */
24799           mac_ptr += offset_size;
24800           break;
24801
24802         case DW_MACINFO_vendor_ext:
24803           /* Only skip the data by MAC_PTR.  */
24804           if (!section_is_gnu)
24805             {
24806               unsigned int bytes_read;
24807
24808               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24809               mac_ptr += bytes_read;
24810               read_direct_string (abfd, mac_ptr, &bytes_read);
24811               mac_ptr += bytes_read;
24812             }
24813           /* FALLTHROUGH */
24814
24815         default:
24816           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24817                                          mac_ptr, mac_end, abfd, offset_size,
24818                                          section);
24819           if (mac_ptr == NULL)
24820             return;
24821           break;
24822         }
24823       DIAGNOSTIC_POP
24824     } while (macinfo_type != 0 && current_file == NULL);
24825
24826   /* Second pass: Process all entries.
24827
24828      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24829      command-line macro definitions/undefinitions.  This flag is unset when we
24830      reach the first DW_MACINFO_start_file entry.  */
24831
24832   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24833                                            htab_eq_pointer,
24834                                            NULL, xcalloc, xfree));
24835   mac_ptr = section->buffer + offset;
24836   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24837   *slot = (void *) mac_ptr;
24838   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24839                             abfd, mac_ptr, mac_end,
24840                             current_file, lh, section,
24841                             section_is_gnu, 0, offset_size,
24842                             include_hash.get ());
24843 }
24844
24845 /* Check if the attribute's form is a DW_FORM_block*
24846    if so return true else false.  */
24847
24848 static int
24849 attr_form_is_block (const struct attribute *attr)
24850 {
24851   return (attr == NULL ? 0 :
24852       attr->form == DW_FORM_block1
24853       || attr->form == DW_FORM_block2
24854       || attr->form == DW_FORM_block4
24855       || attr->form == DW_FORM_block
24856       || attr->form == DW_FORM_exprloc);
24857 }
24858
24859 /* Return non-zero if ATTR's value is a section offset --- classes
24860    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24861    You may use DW_UNSND (attr) to retrieve such offsets.
24862
24863    Section 7.5.4, "Attribute Encodings", explains that no attribute
24864    may have a value that belongs to more than one of these classes; it
24865    would be ambiguous if we did, because we use the same forms for all
24866    of them.  */
24867
24868 static int
24869 attr_form_is_section_offset (const struct attribute *attr)
24870 {
24871   return (attr->form == DW_FORM_data4
24872           || attr->form == DW_FORM_data8
24873           || attr->form == DW_FORM_sec_offset);
24874 }
24875
24876 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24877    zero otherwise.  When this function returns true, you can apply
24878    dwarf2_get_attr_constant_value to it.
24879
24880    However, note that for some attributes you must check
24881    attr_form_is_section_offset before using this test.  DW_FORM_data4
24882    and DW_FORM_data8 are members of both the constant class, and of
24883    the classes that contain offsets into other debug sections
24884    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24885    that, if an attribute's can be either a constant or one of the
24886    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24887    taken as section offsets, not constants.
24888
24889    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24890    cannot handle that.  */
24891
24892 static int
24893 attr_form_is_constant (const struct attribute *attr)
24894 {
24895   switch (attr->form)
24896     {
24897     case DW_FORM_sdata:
24898     case DW_FORM_udata:
24899     case DW_FORM_data1:
24900     case DW_FORM_data2:
24901     case DW_FORM_data4:
24902     case DW_FORM_data8:
24903     case DW_FORM_implicit_const:
24904       return 1;
24905     default:
24906       return 0;
24907     }
24908 }
24909
24910
24911 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24912    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24913
24914 static int
24915 attr_form_is_ref (const struct attribute *attr)
24916 {
24917   switch (attr->form)
24918     {
24919     case DW_FORM_ref_addr:
24920     case DW_FORM_ref1:
24921     case DW_FORM_ref2:
24922     case DW_FORM_ref4:
24923     case DW_FORM_ref8:
24924     case DW_FORM_ref_udata:
24925     case DW_FORM_GNU_ref_alt:
24926       return 1;
24927     default:
24928       return 0;
24929     }
24930 }
24931
24932 /* Return the .debug_loc section to use for CU.
24933    For DWO files use .debug_loc.dwo.  */
24934
24935 static struct dwarf2_section_info *
24936 cu_debug_loc_section (struct dwarf2_cu *cu)
24937 {
24938   struct dwarf2_per_objfile *dwarf2_per_objfile
24939     = cu->per_cu->dwarf2_per_objfile;
24940
24941   if (cu->dwo_unit)
24942     {
24943       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24944       
24945       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24946     }
24947   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24948                                   : &dwarf2_per_objfile->loc);
24949 }
24950
24951 /* A helper function that fills in a dwarf2_loclist_baton.  */
24952
24953 static void
24954 fill_in_loclist_baton (struct dwarf2_cu *cu,
24955                        struct dwarf2_loclist_baton *baton,
24956                        const struct attribute *attr)
24957 {
24958   struct dwarf2_per_objfile *dwarf2_per_objfile
24959     = cu->per_cu->dwarf2_per_objfile;
24960   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24961
24962   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24963
24964   baton->per_cu = cu->per_cu;
24965   gdb_assert (baton->per_cu);
24966   /* We don't know how long the location list is, but make sure we
24967      don't run off the edge of the section.  */
24968   baton->size = section->size - DW_UNSND (attr);
24969   baton->data = section->buffer + DW_UNSND (attr);
24970   baton->base_address = cu->base_address;
24971   baton->from_dwo = cu->dwo_unit != NULL;
24972 }
24973
24974 static void
24975 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24976                              struct dwarf2_cu *cu, int is_block)
24977 {
24978   struct dwarf2_per_objfile *dwarf2_per_objfile
24979     = cu->per_cu->dwarf2_per_objfile;
24980   struct objfile *objfile = dwarf2_per_objfile->objfile;
24981   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24982
24983   if (attr_form_is_section_offset (attr)
24984       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24985          the section.  If so, fall through to the complaint in the
24986          other branch.  */
24987       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24988     {
24989       struct dwarf2_loclist_baton *baton;
24990
24991       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24992
24993       fill_in_loclist_baton (cu, baton, attr);
24994
24995       if (cu->base_known == 0)
24996         complaint (&symfile_complaints,
24997                    _("Location list used without "
24998                      "specifying the CU base address."));
24999
25000       SYMBOL_ACLASS_INDEX (sym) = (is_block
25001                                    ? dwarf2_loclist_block_index
25002                                    : dwarf2_loclist_index);
25003       SYMBOL_LOCATION_BATON (sym) = baton;
25004     }
25005   else
25006     {
25007       struct dwarf2_locexpr_baton *baton;
25008
25009       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
25010       baton->per_cu = cu->per_cu;
25011       gdb_assert (baton->per_cu);
25012
25013       if (attr_form_is_block (attr))
25014         {
25015           /* Note that we're just copying the block's data pointer
25016              here, not the actual data.  We're still pointing into the
25017              info_buffer for SYM's objfile; right now we never release
25018              that buffer, but when we do clean up properly this may
25019              need to change.  */
25020           baton->size = DW_BLOCK (attr)->size;
25021           baton->data = DW_BLOCK (attr)->data;
25022         }
25023       else
25024         {
25025           dwarf2_invalid_attrib_class_complaint ("location description",
25026                                                  SYMBOL_NATURAL_NAME (sym));
25027           baton->size = 0;
25028         }
25029
25030       SYMBOL_ACLASS_INDEX (sym) = (is_block
25031                                    ? dwarf2_locexpr_block_index
25032                                    : dwarf2_locexpr_index);
25033       SYMBOL_LOCATION_BATON (sym) = baton;
25034     }
25035 }
25036
25037 /* Return the OBJFILE associated with the compilation unit CU.  If CU
25038    came from a separate debuginfo file, then the master objfile is
25039    returned.  */
25040
25041 struct objfile *
25042 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
25043 {
25044   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25045
25046   /* Return the master objfile, so that we can report and look up the
25047      correct file containing this variable.  */
25048   if (objfile->separate_debug_objfile_backlink)
25049     objfile = objfile->separate_debug_objfile_backlink;
25050
25051   return objfile;
25052 }
25053
25054 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
25055    (CU_HEADERP is unused in such case) or prepare a temporary copy at
25056    CU_HEADERP first.  */
25057
25058 static const struct comp_unit_head *
25059 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
25060                        struct dwarf2_per_cu_data *per_cu)
25061 {
25062   const gdb_byte *info_ptr;
25063
25064   if (per_cu->cu)
25065     return &per_cu->cu->header;
25066
25067   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
25068
25069   memset (cu_headerp, 0, sizeof (*cu_headerp));
25070   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
25071                        rcuh_kind::COMPILE);
25072
25073   return cu_headerp;
25074 }
25075
25076 /* Return the address size given in the compilation unit header for CU.  */
25077
25078 int
25079 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
25080 {
25081   struct comp_unit_head cu_header_local;
25082   const struct comp_unit_head *cu_headerp;
25083
25084   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25085
25086   return cu_headerp->addr_size;
25087 }
25088
25089 /* Return the offset size given in the compilation unit header for CU.  */
25090
25091 int
25092 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
25093 {
25094   struct comp_unit_head cu_header_local;
25095   const struct comp_unit_head *cu_headerp;
25096
25097   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25098
25099   return cu_headerp->offset_size;
25100 }
25101
25102 /* See its dwarf2loc.h declaration.  */
25103
25104 int
25105 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
25106 {
25107   struct comp_unit_head cu_header_local;
25108   const struct comp_unit_head *cu_headerp;
25109
25110   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
25111
25112   if (cu_headerp->version == 2)
25113     return cu_headerp->addr_size;
25114   else
25115     return cu_headerp->offset_size;
25116 }
25117
25118 /* Return the text offset of the CU.  The returned offset comes from
25119    this CU's objfile.  If this objfile came from a separate debuginfo
25120    file, then the offset may be different from the corresponding
25121    offset in the parent objfile.  */
25122
25123 CORE_ADDR
25124 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
25125 {
25126   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
25127
25128   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
25129 }
25130
25131 /* Return DWARF version number of PER_CU.  */
25132
25133 short
25134 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
25135 {
25136   return per_cu->dwarf_version;
25137 }
25138
25139 /* Locate the .debug_info compilation unit from CU's objfile which contains
25140    the DIE at OFFSET.  Raises an error on failure.  */
25141
25142 static struct dwarf2_per_cu_data *
25143 dwarf2_find_containing_comp_unit (sect_offset sect_off,
25144                                   unsigned int offset_in_dwz,
25145                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
25146 {
25147   struct dwarf2_per_cu_data *this_cu;
25148   int low, high;
25149   const sect_offset *cu_off;
25150
25151   low = 0;
25152   high = dwarf2_per_objfile->n_comp_units - 1;
25153   while (high > low)
25154     {
25155       struct dwarf2_per_cu_data *mid_cu;
25156       int mid = low + (high - low) / 2;
25157
25158       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
25159       cu_off = &mid_cu->sect_off;
25160       if (mid_cu->is_dwz > offset_in_dwz
25161           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
25162         high = mid;
25163       else
25164         low = mid + 1;
25165     }
25166   gdb_assert (low == high);
25167   this_cu = dwarf2_per_objfile->all_comp_units[low];
25168   cu_off = &this_cu->sect_off;
25169   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
25170     {
25171       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
25172         error (_("Dwarf Error: could not find partial DIE containing "
25173                "offset 0x%x [in module %s]"),
25174                to_underlying (sect_off),
25175                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
25176
25177       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
25178                   <= sect_off);
25179       return dwarf2_per_objfile->all_comp_units[low-1];
25180     }
25181   else
25182     {
25183       this_cu = dwarf2_per_objfile->all_comp_units[low];
25184       if (low == dwarf2_per_objfile->n_comp_units - 1
25185           && sect_off >= this_cu->sect_off + this_cu->length)
25186         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
25187       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25188       return this_cu;
25189     }
25190 }
25191
25192 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25193
25194 static void
25195 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
25196 {
25197   memset (cu, 0, sizeof (*cu));
25198   per_cu->cu = cu;
25199   cu->per_cu = per_cu;
25200   obstack_init (&cu->comp_unit_obstack);
25201 }
25202
25203 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25204
25205 static void
25206 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25207                        enum language pretend_language)
25208 {
25209   struct attribute *attr;
25210
25211   /* Set the language we're debugging.  */
25212   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25213   if (attr)
25214     set_cu_language (DW_UNSND (attr), cu);
25215   else
25216     {
25217       cu->language = pretend_language;
25218       cu->language_defn = language_def (cu->language);
25219     }
25220
25221   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25222 }
25223
25224 /* Release one cached compilation unit, CU.  We unlink it from the tree
25225    of compilation units, but we don't remove it from the read_in_chain;
25226    the caller is responsible for that.
25227    NOTE: DATA is a void * because this function is also used as a
25228    cleanup routine.  */
25229
25230 static void
25231 free_heap_comp_unit (void *data)
25232 {
25233   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
25234
25235   gdb_assert (cu->per_cu != NULL);
25236   cu->per_cu->cu = NULL;
25237   cu->per_cu = NULL;
25238
25239   obstack_free (&cu->comp_unit_obstack, NULL);
25240
25241   xfree (cu);
25242 }
25243
25244 /* This cleanup function is passed the address of a dwarf2_cu on the stack
25245    when we're finished with it.  We can't free the pointer itself, but be
25246    sure to unlink it from the cache.  Also release any associated storage.  */
25247
25248 static void
25249 free_stack_comp_unit (void *data)
25250 {
25251   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
25252
25253   gdb_assert (cu->per_cu != NULL);
25254   cu->per_cu->cu = NULL;
25255   cu->per_cu = NULL;
25256
25257   obstack_free (&cu->comp_unit_obstack, NULL);
25258   cu->partial_dies = NULL;
25259 }
25260
25261 /* Free all cached compilation units.  */
25262
25263 static void
25264 free_cached_comp_units (void *data)
25265 {
25266   struct dwarf2_per_objfile *dwarf2_per_objfile
25267     = (struct dwarf2_per_objfile *) data;
25268
25269   dwarf2_per_objfile->free_cached_comp_units ();
25270 }
25271
25272 /* Increase the age counter on each cached compilation unit, and free
25273    any that are too old.  */
25274
25275 static void
25276 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25277 {
25278   struct dwarf2_per_cu_data *per_cu, **last_chain;
25279
25280   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25281   per_cu = dwarf2_per_objfile->read_in_chain;
25282   while (per_cu != NULL)
25283     {
25284       per_cu->cu->last_used ++;
25285       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25286         dwarf2_mark (per_cu->cu);
25287       per_cu = per_cu->cu->read_in_chain;
25288     }
25289
25290   per_cu = dwarf2_per_objfile->read_in_chain;
25291   last_chain = &dwarf2_per_objfile->read_in_chain;
25292   while (per_cu != NULL)
25293     {
25294       struct dwarf2_per_cu_data *next_cu;
25295
25296       next_cu = per_cu->cu->read_in_chain;
25297
25298       if (!per_cu->cu->mark)
25299         {
25300           free_heap_comp_unit (per_cu->cu);
25301           *last_chain = next_cu;
25302         }
25303       else
25304         last_chain = &per_cu->cu->read_in_chain;
25305
25306       per_cu = next_cu;
25307     }
25308 }
25309
25310 /* Remove a single compilation unit from the cache.  */
25311
25312 static void
25313 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25314 {
25315   struct dwarf2_per_cu_data *per_cu, **last_chain;
25316   struct dwarf2_per_objfile *dwarf2_per_objfile
25317     = target_per_cu->dwarf2_per_objfile;
25318
25319   per_cu = dwarf2_per_objfile->read_in_chain;
25320   last_chain = &dwarf2_per_objfile->read_in_chain;
25321   while (per_cu != NULL)
25322     {
25323       struct dwarf2_per_cu_data *next_cu;
25324
25325       next_cu = per_cu->cu->read_in_chain;
25326
25327       if (per_cu == target_per_cu)
25328         {
25329           free_heap_comp_unit (per_cu->cu);
25330           per_cu->cu = NULL;
25331           *last_chain = next_cu;
25332           break;
25333         }
25334       else
25335         last_chain = &per_cu->cu->read_in_chain;
25336
25337       per_cu = next_cu;
25338     }
25339 }
25340
25341 /* Release all extra memory associated with OBJFILE.  */
25342
25343 void
25344 dwarf2_free_objfile (struct objfile *objfile)
25345 {
25346   struct dwarf2_per_objfile *dwarf2_per_objfile
25347     = get_dwarf2_per_objfile (objfile);
25348
25349   if (dwarf2_per_objfile == NULL)
25350     return;
25351
25352   dwarf2_per_objfile->~dwarf2_per_objfile ();
25353 }
25354
25355 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25356    We store these in a hash table separate from the DIEs, and preserve them
25357    when the DIEs are flushed out of cache.
25358
25359    The CU "per_cu" pointer is needed because offset alone is not enough to
25360    uniquely identify the type.  A file may have multiple .debug_types sections,
25361    or the type may come from a DWO file.  Furthermore, while it's more logical
25362    to use per_cu->section+offset, with Fission the section with the data is in
25363    the DWO file but we don't know that section at the point we need it.
25364    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25365    because we can enter the lookup routine, get_die_type_at_offset, from
25366    outside this file, and thus won't necessarily have PER_CU->cu.
25367    Fortunately, PER_CU is stable for the life of the objfile.  */
25368
25369 struct dwarf2_per_cu_offset_and_type
25370 {
25371   const struct dwarf2_per_cu_data *per_cu;
25372   sect_offset sect_off;
25373   struct type *type;
25374 };
25375
25376 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25377
25378 static hashval_t
25379 per_cu_offset_and_type_hash (const void *item)
25380 {
25381   const struct dwarf2_per_cu_offset_and_type *ofs
25382     = (const struct dwarf2_per_cu_offset_and_type *) item;
25383
25384   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25385 }
25386
25387 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25388
25389 static int
25390 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25391 {
25392   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25393     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25394   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25395     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25396
25397   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25398           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25399 }
25400
25401 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25402    table if necessary.  For convenience, return TYPE.
25403
25404    The DIEs reading must have careful ordering to:
25405     * Not cause infite loops trying to read in DIEs as a prerequisite for
25406       reading current DIE.
25407     * Not trying to dereference contents of still incompletely read in types
25408       while reading in other DIEs.
25409     * Enable referencing still incompletely read in types just by a pointer to
25410       the type without accessing its fields.
25411
25412    Therefore caller should follow these rules:
25413      * Try to fetch any prerequisite types we may need to build this DIE type
25414        before building the type and calling set_die_type.
25415      * After building type call set_die_type for current DIE as soon as
25416        possible before fetching more types to complete the current type.
25417      * Make the type as complete as possible before fetching more types.  */
25418
25419 static struct type *
25420 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25421 {
25422   struct dwarf2_per_objfile *dwarf2_per_objfile
25423     = cu->per_cu->dwarf2_per_objfile;
25424   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25425   struct objfile *objfile = dwarf2_per_objfile->objfile;
25426   struct attribute *attr;
25427   struct dynamic_prop prop;
25428
25429   /* For Ada types, make sure that the gnat-specific data is always
25430      initialized (if not already set).  There are a few types where
25431      we should not be doing so, because the type-specific area is
25432      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25433      where the type-specific area is used to store the floatformat).
25434      But this is not a problem, because the gnat-specific information
25435      is actually not needed for these types.  */
25436   if (need_gnat_info (cu)
25437       && TYPE_CODE (type) != TYPE_CODE_FUNC
25438       && TYPE_CODE (type) != TYPE_CODE_FLT
25439       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25440       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25441       && TYPE_CODE (type) != TYPE_CODE_METHOD
25442       && !HAVE_GNAT_AUX_INFO (type))
25443     INIT_GNAT_SPECIFIC (type);
25444
25445   /* Read DW_AT_allocated and set in type.  */
25446   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25447   if (attr_form_is_block (attr))
25448     {
25449       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25450         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
25451     }
25452   else if (attr != NULL)
25453     {
25454       complaint (&symfile_complaints,
25455                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
25456                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25457                  to_underlying (die->sect_off));
25458     }
25459
25460   /* Read DW_AT_associated and set in type.  */
25461   attr = dwarf2_attr (die, DW_AT_associated, cu);
25462   if (attr_form_is_block (attr))
25463     {
25464       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25465         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
25466     }
25467   else if (attr != NULL)
25468     {
25469       complaint (&symfile_complaints,
25470                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
25471                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25472                  to_underlying (die->sect_off));
25473     }
25474
25475   /* Read DW_AT_data_location and set in type.  */
25476   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25477   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25478     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
25479
25480   if (dwarf2_per_objfile->die_type_hash == NULL)
25481     {
25482       dwarf2_per_objfile->die_type_hash =
25483         htab_create_alloc_ex (127,
25484                               per_cu_offset_and_type_hash,
25485                               per_cu_offset_and_type_eq,
25486                               NULL,
25487                               &objfile->objfile_obstack,
25488                               hashtab_obstack_allocate,
25489                               dummy_obstack_deallocate);
25490     }
25491
25492   ofs.per_cu = cu->per_cu;
25493   ofs.sect_off = die->sect_off;
25494   ofs.type = type;
25495   slot = (struct dwarf2_per_cu_offset_and_type **)
25496     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25497   if (*slot)
25498     complaint (&symfile_complaints,
25499                _("A problem internal to GDB: DIE 0x%x has type already set"),
25500                to_underlying (die->sect_off));
25501   *slot = XOBNEW (&objfile->objfile_obstack,
25502                   struct dwarf2_per_cu_offset_and_type);
25503   **slot = ofs;
25504   return type;
25505 }
25506
25507 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25508    or return NULL if the die does not have a saved type.  */
25509
25510 static struct type *
25511 get_die_type_at_offset (sect_offset sect_off,
25512                         struct dwarf2_per_cu_data *per_cu)
25513 {
25514   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25515   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25516
25517   if (dwarf2_per_objfile->die_type_hash == NULL)
25518     return NULL;
25519
25520   ofs.per_cu = per_cu;
25521   ofs.sect_off = sect_off;
25522   slot = ((struct dwarf2_per_cu_offset_and_type *)
25523           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25524   if (slot)
25525     return slot->type;
25526   else
25527     return NULL;
25528 }
25529
25530 /* Look up the type for DIE in CU in die_type_hash,
25531    or return NULL if DIE does not have a saved type.  */
25532
25533 static struct type *
25534 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25535 {
25536   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25537 }
25538
25539 /* Add a dependence relationship from CU to REF_PER_CU.  */
25540
25541 static void
25542 dwarf2_add_dependence (struct dwarf2_cu *cu,
25543                        struct dwarf2_per_cu_data *ref_per_cu)
25544 {
25545   void **slot;
25546
25547   if (cu->dependencies == NULL)
25548     cu->dependencies
25549       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25550                               NULL, &cu->comp_unit_obstack,
25551                               hashtab_obstack_allocate,
25552                               dummy_obstack_deallocate);
25553
25554   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25555   if (*slot == NULL)
25556     *slot = ref_per_cu;
25557 }
25558
25559 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25560    Set the mark field in every compilation unit in the
25561    cache that we must keep because we are keeping CU.  */
25562
25563 static int
25564 dwarf2_mark_helper (void **slot, void *data)
25565 {
25566   struct dwarf2_per_cu_data *per_cu;
25567
25568   per_cu = (struct dwarf2_per_cu_data *) *slot;
25569
25570   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25571      reading of the chain.  As such dependencies remain valid it is not much
25572      useful to track and undo them during QUIT cleanups.  */
25573   if (per_cu->cu == NULL)
25574     return 1;
25575
25576   if (per_cu->cu->mark)
25577     return 1;
25578   per_cu->cu->mark = 1;
25579
25580   if (per_cu->cu->dependencies != NULL)
25581     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25582
25583   return 1;
25584 }
25585
25586 /* Set the mark field in CU and in every other compilation unit in the
25587    cache that we must keep because we are keeping CU.  */
25588
25589 static void
25590 dwarf2_mark (struct dwarf2_cu *cu)
25591 {
25592   if (cu->mark)
25593     return;
25594   cu->mark = 1;
25595   if (cu->dependencies != NULL)
25596     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25597 }
25598
25599 static void
25600 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25601 {
25602   while (per_cu)
25603     {
25604       per_cu->cu->mark = 0;
25605       per_cu = per_cu->cu->read_in_chain;
25606     }
25607 }
25608
25609 /* Trivial hash function for partial_die_info: the hash value of a DIE
25610    is its offset in .debug_info for this objfile.  */
25611
25612 static hashval_t
25613 partial_die_hash (const void *item)
25614 {
25615   const struct partial_die_info *part_die
25616     = (const struct partial_die_info *) item;
25617
25618   return to_underlying (part_die->sect_off);
25619 }
25620
25621 /* Trivial comparison function for partial_die_info structures: two DIEs
25622    are equal if they have the same offset.  */
25623
25624 static int
25625 partial_die_eq (const void *item_lhs, const void *item_rhs)
25626 {
25627   const struct partial_die_info *part_die_lhs
25628     = (const struct partial_die_info *) item_lhs;
25629   const struct partial_die_info *part_die_rhs
25630     = (const struct partial_die_info *) item_rhs;
25631
25632   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25633 }
25634
25635 static struct cmd_list_element *set_dwarf_cmdlist;
25636 static struct cmd_list_element *show_dwarf_cmdlist;
25637
25638 static void
25639 set_dwarf_cmd (const char *args, int from_tty)
25640 {
25641   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25642              gdb_stdout);
25643 }
25644
25645 static void
25646 show_dwarf_cmd (const char *args, int from_tty)
25647 {
25648   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25649 }
25650
25651 /* Free data associated with OBJFILE, if necessary.  */
25652
25653 static void
25654 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
25655 {
25656   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
25657   int ix;
25658
25659   for (ix = 0; ix < data->n_comp_units; ++ix)
25660    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
25661
25662   for (ix = 0; ix < data->n_type_units; ++ix)
25663     VEC_free (dwarf2_per_cu_ptr,
25664               data->all_type_units[ix]->per_cu.imported_symtabs);
25665   xfree (data->all_type_units);
25666
25667   VEC_free (dwarf2_section_info_def, data->types);
25668
25669   if (data->dwo_files)
25670     free_dwo_files (data->dwo_files, objfile);
25671   if (data->dwp_file)
25672     gdb_bfd_unref (data->dwp_file->dbfd);
25673
25674   if (data->dwz_file && data->dwz_file->dwz_bfd)
25675     gdb_bfd_unref (data->dwz_file->dwz_bfd);
25676
25677   if (data->index_table != NULL)
25678     data->index_table->~mapped_index ();
25679 }
25680
25681 \f
25682 /* The "save gdb-index" command.  */
25683
25684 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
25685    error checking.  */
25686
25687 static void
25688 file_write (FILE *file, const void *data, size_t size)
25689 {
25690   if (fwrite (data, 1, size, file) != size)
25691     error (_("couldn't data write to file"));
25692 }
25693
25694 /* Write the contents of VEC to FILE, with error checking.  */
25695
25696 template<typename Elem, typename Alloc>
25697 static void
25698 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
25699 {
25700   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
25701 }
25702
25703 /* In-memory buffer to prepare data to be written later to a file.  */
25704 class data_buf
25705 {
25706 public:
25707   /* Copy DATA to the end of the buffer.  */
25708   template<typename T>
25709   void append_data (const T &data)
25710   {
25711     std::copy (reinterpret_cast<const gdb_byte *> (&data),
25712                reinterpret_cast<const gdb_byte *> (&data + 1),
25713                grow (sizeof (data)));
25714   }
25715
25716   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
25717      terminating zero is appended too.  */
25718   void append_cstr0 (const char *cstr)
25719   {
25720     const size_t size = strlen (cstr) + 1;
25721     std::copy (cstr, cstr + size, grow (size));
25722   }
25723
25724   /* Store INPUT as ULEB128 to the end of buffer.  */
25725   void append_unsigned_leb128 (ULONGEST input)
25726   {
25727     for (;;)
25728       {
25729         gdb_byte output = input & 0x7f;
25730         input >>= 7;
25731         if (input)
25732           output |= 0x80;
25733         append_data (output);
25734         if (input == 0)
25735           break;
25736       }
25737   }
25738
25739   /* Accept a host-format integer in VAL and append it to the buffer
25740      as a target-format integer which is LEN bytes long.  */
25741   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
25742   {
25743     ::store_unsigned_integer (grow (len), len, byte_order, val);
25744   }
25745
25746   /* Return the size of the buffer.  */
25747   size_t size () const
25748   {
25749     return m_vec.size ();
25750   }
25751
25752   /* Return true iff the buffer is empty.  */
25753   bool empty () const
25754   {
25755     return m_vec.empty ();
25756   }
25757
25758   /* Write the buffer to FILE.  */
25759   void file_write (FILE *file) const
25760   {
25761     ::file_write (file, m_vec);
25762   }
25763
25764 private:
25765   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
25766      the start of the new block.  */
25767   gdb_byte *grow (size_t size)
25768   {
25769     m_vec.resize (m_vec.size () + size);
25770     return &*m_vec.end () - size;
25771   }
25772
25773   gdb::byte_vector m_vec;
25774 };
25775
25776 /* An entry in the symbol table.  */
25777 struct symtab_index_entry
25778 {
25779   /* The name of the symbol.  */
25780   const char *name;
25781   /* The offset of the name in the constant pool.  */
25782   offset_type index_offset;
25783   /* A sorted vector of the indices of all the CUs that hold an object
25784      of this name.  */
25785   std::vector<offset_type> cu_indices;
25786 };
25787
25788 /* The symbol table.  This is a power-of-2-sized hash table.  */
25789 struct mapped_symtab
25790 {
25791   mapped_symtab ()
25792   {
25793     data.resize (1024);
25794   }
25795
25796   offset_type n_elements = 0;
25797   std::vector<symtab_index_entry> data;
25798 };
25799
25800 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
25801    the slot.
25802    
25803    Function is used only during write_hash_table so no index format backward
25804    compatibility is needed.  */
25805
25806 static symtab_index_entry &
25807 find_slot (struct mapped_symtab *symtab, const char *name)
25808 {
25809   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
25810
25811   index = hash & (symtab->data.size () - 1);
25812   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
25813
25814   for (;;)
25815     {
25816       if (symtab->data[index].name == NULL
25817           || strcmp (name, symtab->data[index].name) == 0)
25818         return symtab->data[index];
25819       index = (index + step) & (symtab->data.size () - 1);
25820     }
25821 }
25822
25823 /* Expand SYMTAB's hash table.  */
25824
25825 static void
25826 hash_expand (struct mapped_symtab *symtab)
25827 {
25828   auto old_entries = std::move (symtab->data);
25829
25830   symtab->data.clear ();
25831   symtab->data.resize (old_entries.size () * 2);
25832
25833   for (auto &it : old_entries)
25834     if (it.name != NULL)
25835       {
25836         auto &ref = find_slot (symtab, it.name);
25837         ref = std::move (it);
25838       }
25839 }
25840
25841 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
25842    CU_INDEX is the index of the CU in which the symbol appears.
25843    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
25844
25845 static void
25846 add_index_entry (struct mapped_symtab *symtab, const char *name,
25847                  int is_static, gdb_index_symbol_kind kind,
25848                  offset_type cu_index)
25849 {
25850   offset_type cu_index_and_attrs;
25851
25852   ++symtab->n_elements;
25853   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
25854     hash_expand (symtab);
25855
25856   symtab_index_entry &slot = find_slot (symtab, name);
25857   if (slot.name == NULL)
25858     {
25859       slot.name = name;
25860       /* index_offset is set later.  */
25861     }
25862
25863   cu_index_and_attrs = 0;
25864   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
25865   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
25866   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
25867
25868   /* We don't want to record an index value twice as we want to avoid the
25869      duplication.
25870      We process all global symbols and then all static symbols
25871      (which would allow us to avoid the duplication by only having to check
25872      the last entry pushed), but a symbol could have multiple kinds in one CU.
25873      To keep things simple we don't worry about the duplication here and
25874      sort and uniqufy the list after we've processed all symbols.  */
25875   slot.cu_indices.push_back (cu_index_and_attrs);
25876 }
25877
25878 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
25879
25880 static void
25881 uniquify_cu_indices (struct mapped_symtab *symtab)
25882 {
25883   for (auto &entry : symtab->data)
25884     {
25885       if (entry.name != NULL && !entry.cu_indices.empty ())
25886         {
25887           auto &cu_indices = entry.cu_indices;
25888           std::sort (cu_indices.begin (), cu_indices.end ());
25889           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
25890           cu_indices.erase (from, cu_indices.end ());
25891         }
25892     }
25893 }
25894
25895 /* A form of 'const char *' suitable for container keys.  Only the
25896    pointer is stored.  The strings themselves are compared, not the
25897    pointers.  */
25898 class c_str_view
25899 {
25900 public:
25901   c_str_view (const char *cstr)
25902     : m_cstr (cstr)
25903   {}
25904
25905   bool operator== (const c_str_view &other) const
25906   {
25907     return strcmp (m_cstr, other.m_cstr) == 0;
25908   }
25909
25910   /* Return the underlying C string.  Note, the returned string is
25911      only a reference with lifetime of this object.  */
25912   const char *c_str () const
25913   {
25914     return m_cstr;
25915   }
25916
25917 private:
25918   friend class c_str_view_hasher;
25919   const char *const m_cstr;
25920 };
25921
25922 /* A std::unordered_map::hasher for c_str_view that uses the right
25923    hash function for strings in a mapped index.  */
25924 class c_str_view_hasher
25925 {
25926 public:
25927   size_t operator () (const c_str_view &x) const
25928   {
25929     return mapped_index_string_hash (INT_MAX, x.m_cstr);
25930   }
25931 };
25932
25933 /* A std::unordered_map::hasher for std::vector<>.  */
25934 template<typename T>
25935 class vector_hasher
25936 {
25937 public:
25938   size_t operator () (const std::vector<T> &key) const
25939   {
25940     return iterative_hash (key.data (),
25941                            sizeof (key.front ()) * key.size (), 0);
25942   }
25943 };
25944
25945 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
25946    constant pool entries going into the data buffer CPOOL.  */
25947
25948 static void
25949 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
25950 {
25951   {
25952     /* Elements are sorted vectors of the indices of all the CUs that
25953        hold an object of this name.  */
25954     std::unordered_map<std::vector<offset_type>, offset_type,
25955                        vector_hasher<offset_type>>
25956       symbol_hash_table;
25957
25958     /* We add all the index vectors to the constant pool first, to
25959        ensure alignment is ok.  */
25960     for (symtab_index_entry &entry : symtab->data)
25961       {
25962         if (entry.name == NULL)
25963           continue;
25964         gdb_assert (entry.index_offset == 0);
25965
25966         /* Finding before inserting is faster than always trying to
25967            insert, because inserting always allocates a node, does the
25968            lookup, and then destroys the new node if another node
25969            already had the same key.  C++17 try_emplace will avoid
25970            this.  */
25971         const auto found
25972           = symbol_hash_table.find (entry.cu_indices);
25973         if (found != symbol_hash_table.end ())
25974           {
25975             entry.index_offset = found->second;
25976             continue;
25977           }
25978
25979         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
25980         entry.index_offset = cpool.size ();
25981         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
25982         for (const auto index : entry.cu_indices)
25983           cpool.append_data (MAYBE_SWAP (index));
25984       }
25985   }
25986
25987   /* Now write out the hash table.  */
25988   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
25989   for (const auto &entry : symtab->data)
25990     {
25991       offset_type str_off, vec_off;
25992
25993       if (entry.name != NULL)
25994         {
25995           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
25996           if (insertpair.second)
25997             cpool.append_cstr0 (entry.name);
25998           str_off = insertpair.first->second;
25999           vec_off = entry.index_offset;
26000         }
26001       else
26002         {
26003           /* While 0 is a valid constant pool index, it is not valid
26004              to have 0 for both offsets.  */
26005           str_off = 0;
26006           vec_off = 0;
26007         }
26008
26009       output.append_data (MAYBE_SWAP (str_off));
26010       output.append_data (MAYBE_SWAP (vec_off));
26011     }
26012 }
26013
26014 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
26015
26016 /* Helper struct for building the address table.  */
26017 struct addrmap_index_data
26018 {
26019   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
26020     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
26021   {}
26022
26023   struct objfile *objfile;
26024   data_buf &addr_vec;
26025   psym_index_map &cu_index_htab;
26026
26027   /* Non-zero if the previous_* fields are valid.
26028      We can't write an entry until we see the next entry (since it is only then
26029      that we know the end of the entry).  */
26030   int previous_valid;
26031   /* Index of the CU in the table of all CUs in the index file.  */
26032   unsigned int previous_cu_index;
26033   /* Start address of the CU.  */
26034   CORE_ADDR previous_cu_start;
26035 };
26036
26037 /* Write an address entry to ADDR_VEC.  */
26038
26039 static void
26040 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
26041                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
26042 {
26043   CORE_ADDR baseaddr;
26044
26045   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
26046
26047   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
26048   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
26049   addr_vec.append_data (MAYBE_SWAP (cu_index));
26050 }
26051
26052 /* Worker function for traversing an addrmap to build the address table.  */
26053
26054 static int
26055 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
26056 {
26057   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
26058   struct partial_symtab *pst = (struct partial_symtab *) obj;
26059
26060   if (data->previous_valid)
26061     add_address_entry (data->objfile, data->addr_vec,
26062                        data->previous_cu_start, start_addr,
26063                        data->previous_cu_index);
26064
26065   data->previous_cu_start = start_addr;
26066   if (pst != NULL)
26067     {
26068       const auto it = data->cu_index_htab.find (pst);
26069       gdb_assert (it != data->cu_index_htab.cend ());
26070       data->previous_cu_index = it->second;
26071       data->previous_valid = 1;
26072     }
26073   else
26074     data->previous_valid = 0;
26075
26076   return 0;
26077 }
26078
26079 /* Write OBJFILE's address map to ADDR_VEC.
26080    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
26081    in the index file.  */
26082
26083 static void
26084 write_address_map (struct objfile *objfile, data_buf &addr_vec,
26085                    psym_index_map &cu_index_htab)
26086 {
26087   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
26088
26089   /* When writing the address table, we have to cope with the fact that
26090      the addrmap iterator only provides the start of a region; we have to
26091      wait until the next invocation to get the start of the next region.  */
26092
26093   addrmap_index_data.objfile = objfile;
26094   addrmap_index_data.previous_valid = 0;
26095
26096   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
26097                    &addrmap_index_data);
26098
26099   /* It's highly unlikely the last entry (end address = 0xff...ff)
26100      is valid, but we should still handle it.
26101      The end address is recorded as the start of the next region, but that
26102      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
26103      anyway.  */
26104   if (addrmap_index_data.previous_valid)
26105     add_address_entry (objfile, addr_vec,
26106                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
26107                        addrmap_index_data.previous_cu_index);
26108 }
26109
26110 /* Return the symbol kind of PSYM.  */
26111
26112 static gdb_index_symbol_kind
26113 symbol_kind (struct partial_symbol *psym)
26114 {
26115   domain_enum domain = PSYMBOL_DOMAIN (psym);
26116   enum address_class aclass = PSYMBOL_CLASS (psym);
26117
26118   switch (domain)
26119     {
26120     case VAR_DOMAIN:
26121       switch (aclass)
26122         {
26123         case LOC_BLOCK:
26124           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
26125         case LOC_TYPEDEF:
26126           return GDB_INDEX_SYMBOL_KIND_TYPE;
26127         case LOC_COMPUTED:
26128         case LOC_CONST_BYTES:
26129         case LOC_OPTIMIZED_OUT:
26130         case LOC_STATIC:
26131           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
26132         case LOC_CONST:
26133           /* Note: It's currently impossible to recognize psyms as enum values
26134              short of reading the type info.  For now punt.  */
26135           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
26136         default:
26137           /* There are other LOC_FOO values that one might want to classify
26138              as variables, but dwarf2read.c doesn't currently use them.  */
26139           return GDB_INDEX_SYMBOL_KIND_OTHER;
26140         }
26141     case STRUCT_DOMAIN:
26142       return GDB_INDEX_SYMBOL_KIND_TYPE;
26143     default:
26144       return GDB_INDEX_SYMBOL_KIND_OTHER;
26145     }
26146 }
26147
26148 /* Add a list of partial symbols to SYMTAB.  */
26149
26150 static void
26151 write_psymbols (struct mapped_symtab *symtab,
26152                 std::unordered_set<partial_symbol *> &psyms_seen,
26153                 struct partial_symbol **psymp,
26154                 int count,
26155                 offset_type cu_index,
26156                 int is_static)
26157 {
26158   for (; count-- > 0; ++psymp)
26159     {
26160       struct partial_symbol *psym = *psymp;
26161
26162       if (SYMBOL_LANGUAGE (psym) == language_ada)
26163         error (_("Ada is not currently supported by the index"));
26164
26165       /* Only add a given psymbol once.  */
26166       if (psyms_seen.insert (psym).second)
26167         {
26168           gdb_index_symbol_kind kind = symbol_kind (psym);
26169
26170           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
26171                            is_static, kind, cu_index);
26172         }
26173     }
26174 }
26175
26176 /* A helper struct used when iterating over debug_types.  */
26177 struct signatured_type_index_data
26178 {
26179   signatured_type_index_data (data_buf &types_list_,
26180                               std::unordered_set<partial_symbol *> &psyms_seen_)
26181     : types_list (types_list_), psyms_seen (psyms_seen_)
26182   {}
26183
26184   struct objfile *objfile;
26185   struct mapped_symtab *symtab;
26186   data_buf &types_list;
26187   std::unordered_set<partial_symbol *> &psyms_seen;
26188   int cu_index;
26189 };
26190
26191 /* A helper function that writes a single signatured_type to an
26192    obstack.  */
26193
26194 static int
26195 write_one_signatured_type (void **slot, void *d)
26196 {
26197   struct signatured_type_index_data *info
26198     = (struct signatured_type_index_data *) d;
26199   struct signatured_type *entry = (struct signatured_type *) *slot;
26200   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26201
26202   write_psymbols (info->symtab,
26203                   info->psyms_seen,
26204                   &info->objfile->global_psymbols[psymtab->globals_offset],
26205                   psymtab->n_global_syms, info->cu_index,
26206                   0);
26207   write_psymbols (info->symtab,
26208                   info->psyms_seen,
26209                   &info->objfile->static_psymbols[psymtab->statics_offset],
26210                   psymtab->n_static_syms, info->cu_index,
26211                   1);
26212
26213   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26214                                 to_underlying (entry->per_cu.sect_off));
26215   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
26216                                 to_underlying (entry->type_offset_in_tu));
26217   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
26218
26219   ++info->cu_index;
26220
26221   return 1;
26222 }
26223
26224 /* Recurse into all "included" dependencies and count their symbols as
26225    if they appeared in this psymtab.  */
26226
26227 static void
26228 recursively_count_psymbols (struct partial_symtab *psymtab,
26229                             size_t &psyms_seen)
26230 {
26231   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26232     if (psymtab->dependencies[i]->user != NULL)
26233       recursively_count_psymbols (psymtab->dependencies[i],
26234                                   psyms_seen);
26235
26236   psyms_seen += psymtab->n_global_syms;
26237   psyms_seen += psymtab->n_static_syms;
26238 }
26239
26240 /* Recurse into all "included" dependencies and write their symbols as
26241    if they appeared in this psymtab.  */
26242
26243 static void
26244 recursively_write_psymbols (struct objfile *objfile,
26245                             struct partial_symtab *psymtab,
26246                             struct mapped_symtab *symtab,
26247                             std::unordered_set<partial_symbol *> &psyms_seen,
26248                             offset_type cu_index)
26249 {
26250   int i;
26251
26252   for (i = 0; i < psymtab->number_of_dependencies; ++i)
26253     if (psymtab->dependencies[i]->user != NULL)
26254       recursively_write_psymbols (objfile, psymtab->dependencies[i],
26255                                   symtab, psyms_seen, cu_index);
26256
26257   write_psymbols (symtab,
26258                   psyms_seen,
26259                   &objfile->global_psymbols[psymtab->globals_offset],
26260                   psymtab->n_global_syms, cu_index,
26261                   0);
26262   write_psymbols (symtab,
26263                   psyms_seen,
26264                   &objfile->static_psymbols[psymtab->statics_offset],
26265                   psymtab->n_static_syms, cu_index,
26266                   1);
26267 }
26268
26269 /* DWARF-5 .debug_names builder.  */
26270 class debug_names
26271 {
26272 public:
26273   debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile, bool is_dwarf64,
26274                bfd_endian dwarf5_byte_order)
26275     : m_dwarf5_byte_order (dwarf5_byte_order),
26276       m_dwarf32 (dwarf5_byte_order),
26277       m_dwarf64 (dwarf5_byte_order),
26278       m_dwarf (is_dwarf64
26279                ? static_cast<dwarf &> (m_dwarf64)
26280                : static_cast<dwarf &> (m_dwarf32)),
26281       m_name_table_string_offs (m_dwarf.name_table_string_offs),
26282       m_name_table_entry_offs (m_dwarf.name_table_entry_offs),
26283       m_debugstrlookup (dwarf2_per_objfile)
26284   {}
26285
26286   int dwarf5_offset_size () const
26287   {
26288     const bool dwarf5_is_dwarf64 = &m_dwarf == &m_dwarf64;
26289     return dwarf5_is_dwarf64 ? 8 : 4;
26290   }
26291
26292   /* Is this symbol from DW_TAG_compile_unit or DW_TAG_type_unit?  */
26293   enum class unit_kind { cu, tu };
26294
26295   /* Insert one symbol.  */
26296   void insert (const partial_symbol *psym, int cu_index, bool is_static,
26297                unit_kind kind)
26298   {
26299     const int dwarf_tag = psymbol_tag (psym);
26300     if (dwarf_tag == 0)
26301       return;
26302     const char *const name = SYMBOL_SEARCH_NAME (psym);
26303     const auto insertpair
26304       = m_name_to_value_set.emplace (c_str_view (name),
26305                                      std::set<symbol_value> ());
26306     std::set<symbol_value> &value_set = insertpair.first->second;
26307     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static, kind));
26308   }
26309
26310   /* Build all the tables.  All symbols must be already inserted.
26311      This function does not call file_write, caller has to do it
26312      afterwards.  */
26313   void build ()
26314   {
26315     /* Verify the build method has not be called twice.  */
26316     gdb_assert (m_abbrev_table.empty ());
26317     const size_t name_count = m_name_to_value_set.size ();
26318     m_bucket_table.resize
26319       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
26320     m_hash_table.reserve (name_count);
26321     m_name_table_string_offs.reserve (name_count);
26322     m_name_table_entry_offs.reserve (name_count);
26323
26324     /* Map each hash of symbol to its name and value.  */
26325     struct hash_it_pair
26326     {
26327       uint32_t hash;
26328       decltype (m_name_to_value_set)::const_iterator it;
26329     };
26330     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
26331     bucket_hash.resize (m_bucket_table.size ());
26332     for (decltype (m_name_to_value_set)::const_iterator it
26333            = m_name_to_value_set.cbegin ();
26334          it != m_name_to_value_set.cend ();
26335          ++it)
26336       {
26337         const char *const name = it->first.c_str ();
26338         const uint32_t hash = dwarf5_djb_hash (name);
26339         hash_it_pair hashitpair;
26340         hashitpair.hash = hash;
26341         hashitpair.it = it;
26342         auto &slot = bucket_hash[hash % bucket_hash.size()];
26343         slot.push_front (std::move (hashitpair));
26344       }
26345     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
26346       {
26347         const std::forward_list<hash_it_pair> &hashitlist
26348           = bucket_hash[bucket_ix];
26349         if (hashitlist.empty ())
26350           continue;
26351         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
26352         /* The hashes array is indexed starting at 1.  */
26353         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
26354                                 sizeof (bucket_slot), m_dwarf5_byte_order,
26355                                 m_hash_table.size () + 1);
26356         for (const hash_it_pair &hashitpair : hashitlist)
26357           {
26358             m_hash_table.push_back (0);
26359             store_unsigned_integer (reinterpret_cast<gdb_byte *>
26360                                                         (&m_hash_table.back ()),
26361                                     sizeof (m_hash_table.back ()),
26362                                     m_dwarf5_byte_order, hashitpair.hash);
26363             const c_str_view &name = hashitpair.it->first;
26364             const std::set<symbol_value> &value_set = hashitpair.it->second;
26365             m_name_table_string_offs.push_back_reorder
26366               (m_debugstrlookup.lookup (name.c_str ()));
26367             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
26368             gdb_assert (!value_set.empty ());
26369             for (const symbol_value &value : value_set)
26370               {
26371                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
26372                                                         value.is_static,
26373                                                         value.kind)];
26374                 if (idx == 0)
26375                   {
26376                     idx = m_idx_next++;
26377                     m_abbrev_table.append_unsigned_leb128 (idx);
26378                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
26379                     m_abbrev_table.append_unsigned_leb128
26380                               (value.kind == unit_kind::cu ? DW_IDX_compile_unit
26381                                                            : DW_IDX_type_unit);
26382                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
26383                     m_abbrev_table.append_unsigned_leb128 (value.is_static
26384                                                            ? DW_IDX_GNU_internal
26385                                                            : DW_IDX_GNU_external);
26386                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
26387
26388                     /* Terminate attributes list.  */
26389                     m_abbrev_table.append_unsigned_leb128 (0);
26390                     m_abbrev_table.append_unsigned_leb128 (0);
26391                   }
26392
26393                 m_entry_pool.append_unsigned_leb128 (idx);
26394                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
26395               }
26396
26397             /* Terminate the list of CUs.  */
26398             m_entry_pool.append_unsigned_leb128 (0);
26399           }
26400       }
26401     gdb_assert (m_hash_table.size () == name_count);
26402
26403     /* Terminate tags list.  */
26404     m_abbrev_table.append_unsigned_leb128 (0);
26405   }
26406
26407   /* Return .debug_names bucket count.  This must be called only after
26408      calling the build method.  */
26409   uint32_t bucket_count () const
26410   {
26411     /* Verify the build method has been already called.  */
26412     gdb_assert (!m_abbrev_table.empty ());
26413     const uint32_t retval = m_bucket_table.size ();
26414
26415     /* Check for overflow.  */
26416     gdb_assert (retval == m_bucket_table.size ());
26417     return retval;
26418   }
26419
26420   /* Return .debug_names names count.  This must be called only after
26421      calling the build method.  */
26422   uint32_t name_count () const
26423   {
26424     /* Verify the build method has been already called.  */
26425     gdb_assert (!m_abbrev_table.empty ());
26426     const uint32_t retval = m_hash_table.size ();
26427
26428     /* Check for overflow.  */
26429     gdb_assert (retval == m_hash_table.size ());
26430     return retval;
26431   }
26432
26433   /* Return number of bytes of .debug_names abbreviation table.  This
26434      must be called only after calling the build method.  */
26435   uint32_t abbrev_table_bytes () const
26436   {
26437     gdb_assert (!m_abbrev_table.empty ());
26438     return m_abbrev_table.size ();
26439   }
26440
26441   /* Recurse into all "included" dependencies and store their symbols
26442      as if they appeared in this psymtab.  */
26443   void recursively_write_psymbols
26444     (struct objfile *objfile,
26445      struct partial_symtab *psymtab,
26446      std::unordered_set<partial_symbol *> &psyms_seen,
26447      int cu_index)
26448   {
26449     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
26450       if (psymtab->dependencies[i]->user != NULL)
26451         recursively_write_psymbols (objfile, psymtab->dependencies[i],
26452                                     psyms_seen, cu_index);
26453
26454     write_psymbols (psyms_seen,
26455                     &objfile->global_psymbols[psymtab->globals_offset],
26456                     psymtab->n_global_syms, cu_index, false, unit_kind::cu);
26457     write_psymbols (psyms_seen,
26458                     &objfile->static_psymbols[psymtab->statics_offset],
26459                     psymtab->n_static_syms, cu_index, true, unit_kind::cu);
26460   }
26461
26462   /* Return number of bytes the .debug_names section will have.  This
26463      must be called only after calling the build method.  */
26464   size_t bytes () const
26465   {
26466     /* Verify the build method has been already called.  */
26467     gdb_assert (!m_abbrev_table.empty ());
26468     size_t expected_bytes = 0;
26469     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
26470     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
26471     expected_bytes += m_name_table_string_offs.bytes ();
26472     expected_bytes += m_name_table_entry_offs.bytes ();
26473     expected_bytes += m_abbrev_table.size ();
26474     expected_bytes += m_entry_pool.size ();
26475     return expected_bytes;
26476   }
26477
26478   /* Write .debug_names to FILE_NAMES and .debug_str addition to
26479      FILE_STR.  This must be called only after calling the build
26480      method.  */
26481   void file_write (FILE *file_names, FILE *file_str) const
26482   {
26483     /* Verify the build method has been already called.  */
26484     gdb_assert (!m_abbrev_table.empty ());
26485     ::file_write (file_names, m_bucket_table);
26486     ::file_write (file_names, m_hash_table);
26487     m_name_table_string_offs.file_write (file_names);
26488     m_name_table_entry_offs.file_write (file_names);
26489     m_abbrev_table.file_write (file_names);
26490     m_entry_pool.file_write (file_names);
26491     m_debugstrlookup.file_write (file_str);
26492   }
26493
26494   /* A helper user data for write_one_signatured_type.  */
26495   class write_one_signatured_type_data
26496   {
26497   public:
26498     write_one_signatured_type_data (debug_names &nametable_,
26499                                     signatured_type_index_data &&info_)
26500     : nametable (nametable_), info (std::move (info_))
26501     {}
26502     debug_names &nametable;
26503     struct signatured_type_index_data info;
26504   };
26505
26506   /* A helper function to pass write_one_signatured_type to
26507      htab_traverse_noresize.  */
26508   static int
26509   write_one_signatured_type (void **slot, void *d)
26510   {
26511     write_one_signatured_type_data *data = (write_one_signatured_type_data *) d;
26512     struct signatured_type_index_data *info = &data->info;
26513     struct signatured_type *entry = (struct signatured_type *) *slot;
26514
26515     data->nametable.write_one_signatured_type (entry, info);
26516
26517     return 1;
26518   }
26519
26520 private:
26521
26522   /* Storage for symbol names mapping them to their .debug_str section
26523      offsets.  */
26524   class debug_str_lookup
26525   {
26526   public:
26527
26528     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
26529        All .debug_str section strings are automatically stored.  */
26530     debug_str_lookup (struct dwarf2_per_objfile *dwarf2_per_objfile)
26531       : m_abfd (dwarf2_per_objfile->objfile->obfd),
26532         m_dwarf2_per_objfile (dwarf2_per_objfile)
26533     {
26534       dwarf2_read_section (dwarf2_per_objfile->objfile,
26535                            &dwarf2_per_objfile->str);
26536       if (dwarf2_per_objfile->str.buffer == NULL)
26537         return;
26538       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
26539            data < (dwarf2_per_objfile->str.buffer
26540                    + dwarf2_per_objfile->str.size);)
26541         {
26542           const char *const s = reinterpret_cast<const char *> (data);
26543           const auto insertpair
26544             = m_str_table.emplace (c_str_view (s),
26545                                    data - dwarf2_per_objfile->str.buffer);
26546           if (!insertpair.second)
26547             complaint (&symfile_complaints,
26548                        _("Duplicate string \"%s\" in "
26549                          ".debug_str section [in module %s]"),
26550                        s, bfd_get_filename (m_abfd));
26551           data += strlen (s) + 1;
26552         }
26553     }
26554
26555     /* Return offset of symbol name S in the .debug_str section.  Add
26556        such symbol to the section's end if it does not exist there
26557        yet.  */
26558     size_t lookup (const char *s)
26559     {
26560       const auto it = m_str_table.find (c_str_view (s));
26561       if (it != m_str_table.end ())
26562         return it->second;
26563       const size_t offset = (m_dwarf2_per_objfile->str.size
26564                              + m_str_add_buf.size ());
26565       m_str_table.emplace (c_str_view (s), offset);
26566       m_str_add_buf.append_cstr0 (s);
26567       return offset;
26568     }
26569
26570     /* Append the end of the .debug_str section to FILE.  */
26571     void file_write (FILE *file) const
26572     {
26573       m_str_add_buf.file_write (file);
26574     }
26575
26576   private:
26577     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
26578     bfd *const m_abfd;
26579     struct dwarf2_per_objfile *m_dwarf2_per_objfile;
26580
26581     /* Data to add at the end of .debug_str for new needed symbol names.  */
26582     data_buf m_str_add_buf;
26583   };
26584
26585   /* Container to map used DWARF tags to their .debug_names abbreviation
26586      tags.  */
26587   class index_key
26588   {
26589   public:
26590     index_key (int dwarf_tag_, bool is_static_, unit_kind kind_)
26591       : dwarf_tag (dwarf_tag_), is_static (is_static_), kind (kind_)
26592     {
26593     }
26594
26595     bool
26596     operator== (const index_key &other) const
26597     {
26598       return (dwarf_tag == other.dwarf_tag && is_static == other.is_static
26599               && kind == other.kind);
26600     }
26601
26602     const int dwarf_tag;
26603     const bool is_static;
26604     const unit_kind kind;
26605   };
26606
26607   /* Provide std::unordered_map::hasher for index_key.  */
26608   class index_key_hasher
26609   {
26610   public:
26611     size_t
26612     operator () (const index_key &key) const
26613     {
26614       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
26615     }
26616   };
26617
26618   /* Parameters of one symbol entry.  */
26619   class symbol_value
26620   {
26621   public:
26622     const int dwarf_tag, cu_index;
26623     const bool is_static;
26624     const unit_kind kind;
26625
26626     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_,
26627                   unit_kind kind_)
26628       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_),
26629         kind (kind_)
26630     {}
26631
26632     bool
26633     operator< (const symbol_value &other) const
26634     {
26635 #define X(n) \
26636   do \
26637     { \
26638       if (n < other.n) \
26639         return true; \
26640       if (n > other.n) \
26641         return false; \
26642     } \
26643   while (0)
26644       X (dwarf_tag);
26645       X (is_static);
26646       X (kind);
26647       X (cu_index);
26648 #undef X
26649       return false;
26650     }
26651   };
26652
26653   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
26654      output.  */
26655   class offset_vec
26656   {
26657   protected:
26658     const bfd_endian dwarf5_byte_order;
26659   public:
26660     explicit offset_vec (bfd_endian dwarf5_byte_order_)
26661       : dwarf5_byte_order (dwarf5_byte_order_)
26662     {}
26663
26664     /* Call std::vector::reserve for NELEM elements.  */
26665     virtual void reserve (size_t nelem) = 0;
26666
26667     /* Call std::vector::push_back with store_unsigned_integer byte
26668        reordering for ELEM.  */
26669     virtual void push_back_reorder (size_t elem) = 0;
26670
26671     /* Return expected output size in bytes.  */
26672     virtual size_t bytes () const = 0;
26673
26674     /* Write name table to FILE.  */
26675     virtual void file_write (FILE *file) const = 0;
26676   };
26677
26678   /* Template to unify DWARF-32 and DWARF-64 output.  */
26679   template<typename OffsetSize>
26680   class offset_vec_tmpl : public offset_vec
26681   {
26682   public:
26683     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
26684       : offset_vec (dwarf5_byte_order_)
26685     {}
26686
26687     /* Implement offset_vec::reserve.  */
26688     void reserve (size_t nelem) override
26689     {
26690       m_vec.reserve (nelem);
26691     }
26692
26693     /* Implement offset_vec::push_back_reorder.  */
26694     void push_back_reorder (size_t elem) override
26695     {
26696       m_vec.push_back (elem);
26697       /* Check for overflow.  */
26698       gdb_assert (m_vec.back () == elem);
26699       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
26700                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
26701     }
26702
26703     /* Implement offset_vec::bytes.  */
26704     size_t bytes () const override
26705     {
26706       return m_vec.size () * sizeof (m_vec[0]);
26707     }
26708
26709     /* Implement offset_vec::file_write.  */
26710     void file_write (FILE *file) const override
26711     {
26712       ::file_write (file, m_vec);
26713     }
26714
26715   private:
26716     std::vector<OffsetSize> m_vec;
26717   };
26718
26719   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
26720      respecting name table width.  */
26721   class dwarf
26722   {
26723   public:
26724     offset_vec &name_table_string_offs, &name_table_entry_offs;
26725
26726     dwarf (offset_vec &name_table_string_offs_,
26727            offset_vec &name_table_entry_offs_)
26728       : name_table_string_offs (name_table_string_offs_),
26729         name_table_entry_offs (name_table_entry_offs_)
26730     {
26731     }
26732   };
26733
26734   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
26735      respecting name table width.  */
26736   template<typename OffsetSize>
26737   class dwarf_tmpl : public dwarf
26738   {
26739   public:
26740     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
26741       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
26742         m_name_table_string_offs (dwarf5_byte_order_),
26743         m_name_table_entry_offs (dwarf5_byte_order_)
26744     {}
26745
26746   private:
26747     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
26748     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
26749   };
26750
26751   /* Try to reconstruct original DWARF tag for given partial_symbol.
26752      This function is not DWARF-5 compliant but it is sufficient for
26753      GDB as a DWARF-5 index consumer.  */
26754   static int psymbol_tag (const struct partial_symbol *psym)
26755   {
26756     domain_enum domain = PSYMBOL_DOMAIN (psym);
26757     enum address_class aclass = PSYMBOL_CLASS (psym);
26758
26759     switch (domain)
26760       {
26761       case VAR_DOMAIN:
26762         switch (aclass)
26763           {
26764           case LOC_BLOCK:
26765             return DW_TAG_subprogram;
26766           case LOC_TYPEDEF:
26767             return DW_TAG_typedef;
26768           case LOC_COMPUTED:
26769           case LOC_CONST_BYTES:
26770           case LOC_OPTIMIZED_OUT:
26771           case LOC_STATIC:
26772             return DW_TAG_variable;
26773           case LOC_CONST:
26774             /* Note: It's currently impossible to recognize psyms as enum values
26775                short of reading the type info.  For now punt.  */
26776             return DW_TAG_variable;
26777           default:
26778             /* There are other LOC_FOO values that one might want to classify
26779                as variables, but dwarf2read.c doesn't currently use them.  */
26780             return DW_TAG_variable;
26781           }
26782       case STRUCT_DOMAIN:
26783         return DW_TAG_structure_type;
26784       default:
26785         return 0;
26786       }
26787   }
26788
26789   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
26790   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
26791                        struct partial_symbol **psymp, int count, int cu_index,
26792                        bool is_static, unit_kind kind)
26793   {
26794     for (; count-- > 0; ++psymp)
26795       {
26796         struct partial_symbol *psym = *psymp;
26797
26798         if (SYMBOL_LANGUAGE (psym) == language_ada)
26799           error (_("Ada is not currently supported by the index"));
26800
26801         /* Only add a given psymbol once.  */
26802         if (psyms_seen.insert (psym).second)
26803           insert (psym, cu_index, is_static, kind);
26804       }
26805   }
26806
26807   /* A helper function that writes a single signatured_type
26808      to a debug_names.  */
26809   void
26810   write_one_signatured_type (struct signatured_type *entry,
26811                              struct signatured_type_index_data *info)
26812   {
26813     struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
26814
26815     write_psymbols (info->psyms_seen,
26816                     &info->objfile->global_psymbols[psymtab->globals_offset],
26817                     psymtab->n_global_syms, info->cu_index, false,
26818                     unit_kind::tu);
26819     write_psymbols (info->psyms_seen,
26820                     &info->objfile->static_psymbols[psymtab->statics_offset],
26821                     psymtab->n_static_syms, info->cu_index, true,
26822                     unit_kind::tu);
26823
26824     info->types_list.append_uint (dwarf5_offset_size (), m_dwarf5_byte_order,
26825                                   to_underlying (entry->per_cu.sect_off));
26826
26827     ++info->cu_index;
26828   }
26829
26830   /* Store value of each symbol.  */
26831   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
26832     m_name_to_value_set;
26833
26834   /* Tables of DWARF-5 .debug_names.  They are in object file byte
26835      order.  */
26836   std::vector<uint32_t> m_bucket_table;
26837   std::vector<uint32_t> m_hash_table;
26838
26839   const bfd_endian m_dwarf5_byte_order;
26840   dwarf_tmpl<uint32_t> m_dwarf32;
26841   dwarf_tmpl<uint64_t> m_dwarf64;
26842   dwarf &m_dwarf;
26843   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
26844   debug_str_lookup m_debugstrlookup;
26845
26846   /* Map each used .debug_names abbreviation tag parameter to its
26847      index value.  */
26848   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
26849
26850   /* Next unused .debug_names abbreviation tag for
26851      m_indexkey_to_idx.  */
26852   int m_idx_next = 1;
26853
26854   /* .debug_names abbreviation table.  */
26855   data_buf m_abbrev_table;
26856
26857   /* .debug_names entry pool.  */
26858   data_buf m_entry_pool;
26859 };
26860
26861 /* Return iff any of the needed offsets does not fit into 32-bit
26862    .debug_names section.  */
26863
26864 static bool
26865 check_dwarf64_offsets (struct dwarf2_per_objfile *dwarf2_per_objfile)
26866 {
26867   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26868     {
26869       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
26870
26871       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26872         return true;
26873     }
26874   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
26875     {
26876       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
26877       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
26878
26879       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
26880         return true;
26881     }
26882   return false;
26883 }
26884
26885 /* The psyms_seen set is potentially going to be largish (~40k
26886    elements when indexing a -g3 build of GDB itself).  Estimate the
26887    number of elements in order to avoid too many rehashes, which
26888    require rebuilding buckets and thus many trips to
26889    malloc/free.  */
26890
26891 static size_t
26892 psyms_seen_size (struct dwarf2_per_objfile *dwarf2_per_objfile)
26893 {
26894   size_t psyms_count = 0;
26895   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26896     {
26897       struct dwarf2_per_cu_data *per_cu
26898         = dwarf2_per_objfile->all_comp_units[i];
26899       struct partial_symtab *psymtab = per_cu->v.psymtab;
26900
26901       if (psymtab != NULL && psymtab->user == NULL)
26902         recursively_count_psymbols (psymtab, psyms_count);
26903     }
26904   /* Generating an index for gdb itself shows a ratio of
26905      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
26906   return psyms_count / 4;
26907 }
26908
26909 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
26910    Return how many bytes were expected to be written into OUT_FILE.  */
26911
26912 static size_t
26913 write_gdbindex (struct dwarf2_per_objfile *dwarf2_per_objfile, FILE *out_file)
26914 {
26915   struct objfile *objfile = dwarf2_per_objfile->objfile;
26916   mapped_symtab symtab;
26917   data_buf cu_list;
26918
26919   /* While we're scanning CU's create a table that maps a psymtab pointer
26920      (which is what addrmap records) to its index (which is what is recorded
26921      in the index file).  This will later be needed to write the address
26922      table.  */
26923   psym_index_map cu_index_htab;
26924   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
26925
26926   /* The CU list is already sorted, so we don't need to do additional
26927      work here.  Also, the debug_types entries do not appear in
26928      all_comp_units, but only in their own hash table.  */
26929
26930   std::unordered_set<partial_symbol *> psyms_seen
26931     (psyms_seen_size (dwarf2_per_objfile));
26932   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
26933     {
26934       struct dwarf2_per_cu_data *per_cu
26935         = dwarf2_per_objfile->all_comp_units[i];
26936       struct partial_symtab *psymtab = per_cu->v.psymtab;
26937
26938       /* CU of a shared file from 'dwz -m' may be unused by this main file.
26939          It may be referenced from a local scope but in such case it does not
26940          need to be present in .gdb_index.  */
26941       if (psymtab == NULL)
26942         continue;
26943
26944       if (psymtab->user == NULL)
26945         recursively_write_psymbols (objfile, psymtab, &symtab,
26946                                     psyms_seen, i);
26947
26948       const auto insertpair = cu_index_htab.emplace (psymtab, i);
26949       gdb_assert (insertpair.second);
26950
26951       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
26952                            to_underlying (per_cu->sect_off));
26953       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
26954     }
26955
26956   /* Dump the address map.  */
26957   data_buf addr_vec;
26958   write_address_map (objfile, addr_vec, cu_index_htab);
26959
26960   /* Write out the .debug_type entries, if any.  */
26961   data_buf types_cu_list;
26962   if (dwarf2_per_objfile->signatured_types)
26963     {
26964       signatured_type_index_data sig_data (types_cu_list,
26965                                            psyms_seen);
26966
26967       sig_data.objfile = objfile;
26968       sig_data.symtab = &symtab;
26969       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
26970       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
26971                               write_one_signatured_type, &sig_data);
26972     }
26973
26974   /* Now that we've processed all symbols we can shrink their cu_indices
26975      lists.  */
26976   uniquify_cu_indices (&symtab);
26977
26978   data_buf symtab_vec, constant_pool;
26979   write_hash_table (&symtab, symtab_vec, constant_pool);
26980
26981   data_buf contents;
26982   const offset_type size_of_contents = 6 * sizeof (offset_type);
26983   offset_type total_len = size_of_contents;
26984
26985   /* The version number.  */
26986   contents.append_data (MAYBE_SWAP (8));
26987
26988   /* The offset of the CU list from the start of the file.  */
26989   contents.append_data (MAYBE_SWAP (total_len));
26990   total_len += cu_list.size ();
26991
26992   /* The offset of the types CU list from the start of the file.  */
26993   contents.append_data (MAYBE_SWAP (total_len));
26994   total_len += types_cu_list.size ();
26995
26996   /* The offset of the address table from the start of the file.  */
26997   contents.append_data (MAYBE_SWAP (total_len));
26998   total_len += addr_vec.size ();
26999
27000   /* The offset of the symbol table from the start of the file.  */
27001   contents.append_data (MAYBE_SWAP (total_len));
27002   total_len += symtab_vec.size ();
27003
27004   /* The offset of the constant pool from the start of the file.  */
27005   contents.append_data (MAYBE_SWAP (total_len));
27006   total_len += constant_pool.size ();
27007
27008   gdb_assert (contents.size () == size_of_contents);
27009
27010   contents.file_write (out_file);
27011   cu_list.file_write (out_file);
27012   types_cu_list.file_write (out_file);
27013   addr_vec.file_write (out_file);
27014   symtab_vec.file_write (out_file);
27015   constant_pool.file_write (out_file);
27016
27017   return total_len;
27018 }
27019
27020 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
27021 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
27022
27023 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
27024    needed addition to .debug_str section to OUT_FILE_STR.  Return how
27025    many bytes were expected to be written into OUT_FILE.  */
27026
27027 static size_t
27028 write_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
27029                    FILE *out_file, FILE *out_file_str)
27030 {
27031   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets (dwarf2_per_objfile);
27032   struct objfile *objfile = dwarf2_per_objfile->objfile;
27033   const enum bfd_endian dwarf5_byte_order
27034     = gdbarch_byte_order (get_objfile_arch (objfile));
27035
27036   /* The CU list is already sorted, so we don't need to do additional
27037      work here.  Also, the debug_types entries do not appear in
27038      all_comp_units, but only in their own hash table.  */
27039   data_buf cu_list;
27040   debug_names nametable (dwarf2_per_objfile, dwarf5_is_dwarf64,
27041                          dwarf5_byte_order);
27042   std::unordered_set<partial_symbol *>
27043     psyms_seen (psyms_seen_size (dwarf2_per_objfile));
27044   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
27045     {
27046       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
27047       partial_symtab *psymtab = per_cu->v.psymtab;
27048
27049       /* CU of a shared file from 'dwz -m' may be unused by this main
27050          file.  It may be referenced from a local scope but in such
27051          case it does not need to be present in .debug_names.  */
27052       if (psymtab == NULL)
27053         continue;
27054
27055       if (psymtab->user == NULL)
27056         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
27057
27058       cu_list.append_uint (nametable.dwarf5_offset_size (), dwarf5_byte_order,
27059                            to_underlying (per_cu->sect_off));
27060     }
27061
27062   /* Write out the .debug_type entries, if any.  */
27063   data_buf types_cu_list;
27064   if (dwarf2_per_objfile->signatured_types)
27065     {
27066       debug_names::write_one_signatured_type_data sig_data (nametable,
27067                         signatured_type_index_data (types_cu_list, psyms_seen));
27068
27069       sig_data.info.objfile = objfile;
27070       /* It is used only for gdb_index.  */
27071       sig_data.info.symtab = nullptr;
27072       sig_data.info.cu_index = 0;
27073       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
27074                               debug_names::write_one_signatured_type,
27075                               &sig_data);
27076     }
27077
27078   nametable.build ();
27079
27080   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
27081
27082   const offset_type bytes_of_header
27083     = ((dwarf5_is_dwarf64 ? 12 : 4)
27084        + 2 + 2 + 7 * 4
27085        + sizeof (dwarf5_gdb_augmentation));
27086   size_t expected_bytes = 0;
27087   expected_bytes += bytes_of_header;
27088   expected_bytes += cu_list.size ();
27089   expected_bytes += types_cu_list.size ();
27090   expected_bytes += nametable.bytes ();
27091   data_buf header;
27092
27093   if (!dwarf5_is_dwarf64)
27094     {
27095       const uint64_t size64 = expected_bytes - 4;
27096       gdb_assert (size64 < 0xfffffff0);
27097       header.append_uint (4, dwarf5_byte_order, size64);
27098     }
27099   else
27100     {
27101       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
27102       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
27103     }
27104
27105   /* The version number.  */
27106   header.append_uint (2, dwarf5_byte_order, 5);
27107
27108   /* Padding.  */
27109   header.append_uint (2, dwarf5_byte_order, 0);
27110
27111   /* comp_unit_count - The number of CUs in the CU list.  */
27112   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
27113
27114   /* local_type_unit_count - The number of TUs in the local TU
27115      list.  */
27116   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
27117
27118   /* foreign_type_unit_count - The number of TUs in the foreign TU
27119      list.  */
27120   header.append_uint (4, dwarf5_byte_order, 0);
27121
27122   /* bucket_count - The number of hash buckets in the hash lookup
27123      table.  */
27124   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
27125
27126   /* name_count - The number of unique names in the index.  */
27127   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
27128
27129   /* abbrev_table_size - The size in bytes of the abbreviations
27130      table.  */
27131   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
27132
27133   /* augmentation_string_size - The size in bytes of the augmentation
27134      string.  This value is rounded up to a multiple of 4.  */
27135   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
27136   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
27137   header.append_data (dwarf5_gdb_augmentation);
27138
27139   gdb_assert (header.size () == bytes_of_header);
27140
27141   header.file_write (out_file);
27142   cu_list.file_write (out_file);
27143   types_cu_list.file_write (out_file);
27144   nametable.file_write (out_file, out_file_str);
27145
27146   return expected_bytes;
27147 }
27148
27149 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
27150    position is at the end of the file.  */
27151
27152 static void
27153 assert_file_size (FILE *file, const char *filename, size_t expected_size)
27154 {
27155   const auto file_size = ftell (file);
27156   if (file_size == -1)
27157     error (_("Can't get `%s' size"), filename);
27158   gdb_assert (file_size == expected_size);
27159 }
27160
27161 /* Create an index file for OBJFILE in the directory DIR.  */
27162
27163 static void
27164 write_psymtabs_to_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
27165                          const char *dir,
27166                          dw_index_kind index_kind)
27167 {
27168   struct objfile *objfile = dwarf2_per_objfile->objfile;
27169
27170   if (dwarf2_per_objfile->using_index)
27171     error (_("Cannot use an index to create the index"));
27172
27173   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
27174     error (_("Cannot make an index when the file has multiple .debug_types sections"));
27175
27176   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
27177     return;
27178
27179   struct stat st;
27180   if (stat (objfile_name (objfile), &st) < 0)
27181     perror_with_name (objfile_name (objfile));
27182
27183   std::string filename (std::string (dir) + SLASH_STRING
27184                         + lbasename (objfile_name (objfile))
27185                         + (index_kind == dw_index_kind::DEBUG_NAMES
27186                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
27187
27188   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
27189   if (!out_file)
27190     error (_("Can't open `%s' for writing"), filename.c_str ());
27191
27192   /* Order matters here; we want FILE to be closed before FILENAME is
27193      unlinked, because on MS-Windows one cannot delete a file that is
27194      still open.  (Don't call anything here that might throw until
27195      file_closer is created.)  */
27196   gdb::unlinker unlink_file (filename.c_str ());
27197   gdb_file_up close_out_file (out_file);
27198
27199   if (index_kind == dw_index_kind::DEBUG_NAMES)
27200     {
27201       std::string filename_str (std::string (dir) + SLASH_STRING
27202                                 + lbasename (objfile_name (objfile))
27203                                 + DEBUG_STR_SUFFIX);
27204       FILE *out_file_str
27205         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
27206       if (!out_file_str)
27207         error (_("Can't open `%s' for writing"), filename_str.c_str ());
27208       gdb::unlinker unlink_file_str (filename_str.c_str ());
27209       gdb_file_up close_out_file_str (out_file_str);
27210
27211       const size_t total_len
27212         = write_debug_names (dwarf2_per_objfile, out_file, out_file_str);
27213       assert_file_size (out_file, filename.c_str (), total_len);
27214
27215       /* We want to keep the file .debug_str file too.  */
27216       unlink_file_str.keep ();
27217     }
27218   else
27219     {
27220       const size_t total_len
27221         = write_gdbindex (dwarf2_per_objfile, out_file);
27222       assert_file_size (out_file, filename.c_str (), total_len);
27223     }
27224
27225   /* We want to keep the file.  */
27226   unlink_file.keep ();
27227 }
27228
27229 /* Implementation of the `save gdb-index' command.
27230    
27231    Note that the .gdb_index file format used by this command is
27232    documented in the GDB manual.  Any changes here must be documented
27233    there.  */
27234
27235 static void
27236 save_gdb_index_command (const char *arg, int from_tty)
27237 {
27238   struct objfile *objfile;
27239   const char dwarf5space[] = "-dwarf-5 ";
27240   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
27241
27242   if (!arg)
27243     arg = "";
27244
27245   arg = skip_spaces (arg);
27246   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
27247     {
27248       index_kind = dw_index_kind::DEBUG_NAMES;
27249       arg += strlen (dwarf5space);
27250       arg = skip_spaces (arg);
27251     }
27252
27253   if (!*arg)
27254     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
27255
27256   ALL_OBJFILES (objfile)
27257   {
27258     struct stat st;
27259
27260     /* If the objfile does not correspond to an actual file, skip it.  */
27261     if (stat (objfile_name (objfile), &st) < 0)
27262       continue;
27263
27264     struct dwarf2_per_objfile *dwarf2_per_objfile
27265       = get_dwarf2_per_objfile (objfile);
27266
27267     if (dwarf2_per_objfile != NULL)
27268       {
27269         TRY
27270           {
27271             write_psymtabs_to_index (dwarf2_per_objfile, arg, index_kind);
27272           }
27273         CATCH (except, RETURN_MASK_ERROR)
27274           {
27275             exception_fprintf (gdb_stderr, except,
27276                                _("Error while writing index for `%s': "),
27277                                objfile_name (objfile));
27278           }
27279         END_CATCH
27280       }
27281
27282   }
27283 }
27284
27285 \f
27286
27287 int dwarf_always_disassemble;
27288
27289 static void
27290 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
27291                                struct cmd_list_element *c, const char *value)
27292 {
27293   fprintf_filtered (file,
27294                     _("Whether to always disassemble "
27295                       "DWARF expressions is %s.\n"),
27296                     value);
27297 }
27298
27299 static void
27300 show_check_physname (struct ui_file *file, int from_tty,
27301                      struct cmd_list_element *c, const char *value)
27302 {
27303   fprintf_filtered (file,
27304                     _("Whether to check \"physname\" is %s.\n"),
27305                     value);
27306 }
27307
27308 void
27309 _initialize_dwarf2_read (void)
27310 {
27311   struct cmd_list_element *c;
27312
27313   dwarf2_objfile_data_key
27314     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
27315
27316   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
27317 Set DWARF specific variables.\n\
27318 Configure DWARF variables such as the cache size"),
27319                   &set_dwarf_cmdlist, "maintenance set dwarf ",
27320                   0/*allow-unknown*/, &maintenance_set_cmdlist);
27321
27322   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
27323 Show DWARF specific variables\n\
27324 Show DWARF variables such as the cache size"),
27325                   &show_dwarf_cmdlist, "maintenance show dwarf ",
27326                   0/*allow-unknown*/, &maintenance_show_cmdlist);
27327
27328   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
27329                             &dwarf_max_cache_age, _("\
27330 Set the upper bound on the age of cached DWARF compilation units."), _("\
27331 Show the upper bound on the age of cached DWARF compilation units."), _("\
27332 A higher limit means that cached compilation units will be stored\n\
27333 in memory longer, and more total memory will be used.  Zero disables\n\
27334 caching, which can slow down startup."),
27335                             NULL,
27336                             show_dwarf_max_cache_age,
27337                             &set_dwarf_cmdlist,
27338                             &show_dwarf_cmdlist);
27339
27340   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
27341                            &dwarf_always_disassemble, _("\
27342 Set whether `info address' always disassembles DWARF expressions."), _("\
27343 Show whether `info address' always disassembles DWARF expressions."), _("\
27344 When enabled, DWARF expressions are always printed in an assembly-like\n\
27345 syntax.  When disabled, expressions will be printed in a more\n\
27346 conversational style, when possible."),
27347                            NULL,
27348                            show_dwarf_always_disassemble,
27349                            &set_dwarf_cmdlist,
27350                            &show_dwarf_cmdlist);
27351
27352   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
27353 Set debugging of the DWARF reader."), _("\
27354 Show debugging of the DWARF reader."), _("\
27355 When enabled (non-zero), debugging messages are printed during DWARF\n\
27356 reading and symtab expansion.  A value of 1 (one) provides basic\n\
27357 information.  A value greater than 1 provides more verbose information."),
27358                             NULL,
27359                             NULL,
27360                             &setdebuglist, &showdebuglist);
27361
27362   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
27363 Set debugging of the DWARF DIE reader."), _("\
27364 Show debugging of the DWARF DIE reader."), _("\
27365 When enabled (non-zero), DIEs are dumped after they are read in.\n\
27366 The value is the maximum depth to print."),
27367                              NULL,
27368                              NULL,
27369                              &setdebuglist, &showdebuglist);
27370
27371   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
27372 Set debugging of the dwarf line reader."), _("\
27373 Show debugging of the dwarf line reader."), _("\
27374 When enabled (non-zero), line number entries are dumped as they are read in.\n\
27375 A value of 1 (one) provides basic information.\n\
27376 A value greater than 1 provides more verbose information."),
27377                              NULL,
27378                              NULL,
27379                              &setdebuglist, &showdebuglist);
27380
27381   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
27382 Set cross-checking of \"physname\" code against demangler."), _("\
27383 Show cross-checking of \"physname\" code against demangler."), _("\
27384 When enabled, GDB's internal \"physname\" code is checked against\n\
27385 the demangler."),
27386                            NULL, show_check_physname,
27387                            &setdebuglist, &showdebuglist);
27388
27389   add_setshow_boolean_cmd ("use-deprecated-index-sections",
27390                            no_class, &use_deprecated_index_sections, _("\
27391 Set whether to use deprecated gdb_index sections."), _("\
27392 Show whether to use deprecated gdb_index sections."), _("\
27393 When enabled, deprecated .gdb_index sections are used anyway.\n\
27394 Normally they are ignored either because of a missing feature or\n\
27395 performance issue.\n\
27396 Warning: This option must be enabled before gdb reads the file."),
27397                            NULL,
27398                            NULL,
27399                            &setlist, &showlist);
27400
27401   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
27402                _("\
27403 Save a gdb-index file.\n\
27404 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
27405 \n\
27406 No options create one file with .gdb-index extension for pre-DWARF-5\n\
27407 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
27408 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
27409                &save_cmdlist);
27410   set_cmd_completer (c, filename_completer);
27411
27412   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
27413                                                         &dwarf2_locexpr_funcs);
27414   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
27415                                                         &dwarf2_loclist_funcs);
27416
27417   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
27418                                         &dwarf2_block_frame_base_locexpr_funcs);
27419   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
27420                                         &dwarf2_block_frame_base_loclist_funcs);
27421
27422 #if GDB_SELF_TEST
27423   selftests::register_test ("dw2_expand_symtabs_matching",
27424                             selftests::dw2_expand_symtabs_matching::run_test);
27425 #endif
27426 }