Set CU language before processing any DIEs (symtab/23010 et al)
[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 "dwarf2read.h"
33 #include "dwarf-index-common.h"
34 #include "bfd.h"
35 #include "elf-bfd.h"
36 #include "symtab.h"
37 #include "gdbtypes.h"
38 #include "objfiles.h"
39 #include "dwarf2.h"
40 #include "buildsym.h"
41 #include "demangle.h"
42 #include "gdb-demangle.h"
43 #include "expression.h"
44 #include "filenames.h"  /* for DOSish file names */
45 #include "macrotab.h"
46 #include "language.h"
47 #include "complaints.h"
48 #include "bcache.h"
49 #include "dwarf2expr.h"
50 #include "dwarf2loc.h"
51 #include "cp-support.h"
52 #include "hashtab.h"
53 #include "command.h"
54 #include "gdbcmd.h"
55 #include "block.h"
56 #include "addrmap.h"
57 #include "typeprint.h"
58 #include "psympriv.h"
59 #include <sys/stat.h>
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "filestuff.h"
72 #include "build-id.h"
73 #include "namespace.h"
74 #include "common/gdb_unlinker.h"
75 #include "common/function-view.h"
76 #include "common/gdb_optional.h"
77 #include "common/underlying.h"
78 #include "common/byte-vector.h"
79 #include "common/hash_enum.h"
80 #include "filename-seen-cache.h"
81 #include "producer.h"
82 #include <fcntl.h>
83 #include <sys/types.h>
84 #include <algorithm>
85 #include <unordered_set>
86 #include <unordered_map>
87 #include "selftest.h"
88 #include <cmath>
89 #include <set>
90 #include <forward_list>
91 #include "rust-lang.h"
92 #include "common/pathstuff.h"
93
94 /* When == 1, print basic high level tracing messages.
95    When > 1, be more verbose.
96    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
97 static unsigned int dwarf_read_debug = 0;
98
99 /* When non-zero, dump DIEs after they are read in.  */
100 static unsigned int dwarf_die_debug = 0;
101
102 /* When non-zero, dump line number entries as they are read in.  */
103 static unsigned int dwarf_line_debug = 0;
104
105 /* When non-zero, cross-check physname against demangler.  */
106 static int check_physname = 0;
107
108 /* When non-zero, do not reject deprecated .gdb_index sections.  */
109 static int use_deprecated_index_sections = 0;
110
111 static const struct objfile_data *dwarf2_objfile_data_key;
112
113 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
114
115 static int dwarf2_locexpr_index;
116 static int dwarf2_loclist_index;
117 static int dwarf2_locexpr_block_index;
118 static int dwarf2_loclist_block_index;
119
120 /* An index into a (C++) symbol name component in a symbol name as
121    recorded in the mapped_index's symbol table.  For each C++ symbol
122    in the symbol table, we record one entry for the start of each
123    component in the symbol in a table of name components, and then
124    sort the table, in order to be able to binary search symbol names,
125    ignoring leading namespaces, both completion and regular look up.
126    For example, for symbol "A::B::C", we'll have an entry that points
127    to "A::B::C", another that points to "B::C", and another for "C".
128    Note that function symbols in GDB index have no parameter
129    information, just the function/method names.  You can convert a
130    name_component to a "const char *" using the
131    'mapped_index::symbol_name_at(offset_type)' method.  */
132
133 struct name_component
134 {
135   /* Offset in the symbol name where the component starts.  Stored as
136      a (32-bit) offset instead of a pointer to save memory and improve
137      locality on 64-bit architectures.  */
138   offset_type name_offset;
139
140   /* The symbol's index in the symbol and constant pool tables of a
141      mapped_index.  */
142   offset_type idx;
143 };
144
145 /* Base class containing bits shared by both .gdb_index and
146    .debug_name indexes.  */
147
148 struct mapped_index_base
149 {
150   mapped_index_base () = default;
151   DISABLE_COPY_AND_ASSIGN (mapped_index_base);
152
153   /* The name_component table (a sorted vector).  See name_component's
154      description above.  */
155   std::vector<name_component> name_components;
156
157   /* How NAME_COMPONENTS is sorted.  */
158   enum case_sensitivity name_components_casing;
159
160   /* Return the number of names in the symbol table.  */
161   virtual size_t symbol_name_count () const = 0;
162
163   /* Get the name of the symbol at IDX in the symbol table.  */
164   virtual const char *symbol_name_at (offset_type idx) const = 0;
165
166   /* Return whether the name at IDX in the symbol table should be
167      ignored.  */
168   virtual bool symbol_name_slot_invalid (offset_type idx) const
169   {
170     return false;
171   }
172
173   /* Build the symbol name component sorted vector, if we haven't
174      yet.  */
175   void build_name_components ();
176
177   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
178      possible matches for LN_NO_PARAMS in the name component
179      vector.  */
180   std::pair<std::vector<name_component>::const_iterator,
181             std::vector<name_component>::const_iterator>
182     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
183
184   /* Prevent deleting/destroying via a base class pointer.  */
185 protected:
186   ~mapped_index_base() = default;
187 };
188
189 /* A description of the mapped index.  The file format is described in
190    a comment by the code that writes the index.  */
191 struct mapped_index final : public mapped_index_base
192 {
193   /* A slot/bucket in the symbol table hash.  */
194   struct symbol_table_slot
195   {
196     const offset_type name;
197     const offset_type vec;
198   };
199
200   /* Index data format version.  */
201   int version = 0;
202
203   /* The address table data.  */
204   gdb::array_view<const gdb_byte> address_table;
205
206   /* The symbol table, implemented as a hash table.  */
207   gdb::array_view<symbol_table_slot> symbol_table;
208
209   /* A pointer to the constant pool.  */
210   const char *constant_pool = nullptr;
211
212   bool symbol_name_slot_invalid (offset_type idx) const override
213   {
214     const auto &bucket = this->symbol_table[idx];
215     return bucket.name == 0 && bucket.vec;
216   }
217
218   /* Convenience method to get at the name of the symbol at IDX in the
219      symbol table.  */
220   const char *symbol_name_at (offset_type idx) const override
221   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
222
223   size_t symbol_name_count () const override
224   { return this->symbol_table.size (); }
225 };
226
227 /* A description of the mapped .debug_names.
228    Uninitialized map has CU_COUNT 0.  */
229 struct mapped_debug_names final : public mapped_index_base
230 {
231   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
232   : dwarf2_per_objfile (dwarf2_per_objfile_)
233   {}
234
235   struct dwarf2_per_objfile *dwarf2_per_objfile;
236   bfd_endian dwarf5_byte_order;
237   bool dwarf5_is_dwarf64;
238   bool augmentation_is_gdb;
239   uint8_t offset_size;
240   uint32_t cu_count = 0;
241   uint32_t tu_count, bucket_count, name_count;
242   const gdb_byte *cu_table_reordered, *tu_table_reordered;
243   const uint32_t *bucket_table_reordered, *hash_table_reordered;
244   const gdb_byte *name_table_string_offs_reordered;
245   const gdb_byte *name_table_entry_offs_reordered;
246   const gdb_byte *entry_pool;
247
248   struct index_val
249   {
250     ULONGEST dwarf_tag;
251     struct attr
252     {
253       /* Attribute name DW_IDX_*.  */
254       ULONGEST dw_idx;
255
256       /* Attribute form DW_FORM_*.  */
257       ULONGEST form;
258
259       /* Value if FORM is DW_FORM_implicit_const.  */
260       LONGEST implicit_const;
261     };
262     std::vector<attr> attr_vec;
263   };
264
265   std::unordered_map<ULONGEST, index_val> abbrev_map;
266
267   const char *namei_to_name (uint32_t namei) const;
268
269   /* Implementation of the mapped_index_base virtual interface, for
270      the name_components cache.  */
271
272   const char *symbol_name_at (offset_type idx) const override
273   { return namei_to_name (idx); }
274
275   size_t symbol_name_count () const override
276   { return this->name_count; }
277 };
278
279 /* See dwarf2read.h.  */
280
281 dwarf2_per_objfile *
282 get_dwarf2_per_objfile (struct objfile *objfile)
283 {
284   return ((struct dwarf2_per_objfile *)
285           objfile_data (objfile, dwarf2_objfile_data_key));
286 }
287
288 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
289
290 void
291 set_dwarf2_per_objfile (struct objfile *objfile,
292                         struct dwarf2_per_objfile *dwarf2_per_objfile)
293 {
294   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
295   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
296 }
297
298 /* Default names of the debugging sections.  */
299
300 /* Note that if the debugging section has been compressed, it might
301    have a name like .zdebug_info.  */
302
303 static const struct dwarf2_debug_sections dwarf2_elf_names =
304 {
305   { ".debug_info", ".zdebug_info" },
306   { ".debug_abbrev", ".zdebug_abbrev" },
307   { ".debug_line", ".zdebug_line" },
308   { ".debug_loc", ".zdebug_loc" },
309   { ".debug_loclists", ".zdebug_loclists" },
310   { ".debug_macinfo", ".zdebug_macinfo" },
311   { ".debug_macro", ".zdebug_macro" },
312   { ".debug_str", ".zdebug_str" },
313   { ".debug_line_str", ".zdebug_line_str" },
314   { ".debug_ranges", ".zdebug_ranges" },
315   { ".debug_rnglists", ".zdebug_rnglists" },
316   { ".debug_types", ".zdebug_types" },
317   { ".debug_addr", ".zdebug_addr" },
318   { ".debug_frame", ".zdebug_frame" },
319   { ".eh_frame", NULL },
320   { ".gdb_index", ".zgdb_index" },
321   { ".debug_names", ".zdebug_names" },
322   { ".debug_aranges", ".zdebug_aranges" },
323   23
324 };
325
326 /* List of DWO/DWP sections.  */
327
328 static const struct dwop_section_names
329 {
330   struct dwarf2_section_names abbrev_dwo;
331   struct dwarf2_section_names info_dwo;
332   struct dwarf2_section_names line_dwo;
333   struct dwarf2_section_names loc_dwo;
334   struct dwarf2_section_names loclists_dwo;
335   struct dwarf2_section_names macinfo_dwo;
336   struct dwarf2_section_names macro_dwo;
337   struct dwarf2_section_names str_dwo;
338   struct dwarf2_section_names str_offsets_dwo;
339   struct dwarf2_section_names types_dwo;
340   struct dwarf2_section_names cu_index;
341   struct dwarf2_section_names tu_index;
342 }
343 dwop_section_names =
344 {
345   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
346   { ".debug_info.dwo", ".zdebug_info.dwo" },
347   { ".debug_line.dwo", ".zdebug_line.dwo" },
348   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
349   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
350   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
351   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
352   { ".debug_str.dwo", ".zdebug_str.dwo" },
353   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
354   { ".debug_types.dwo", ".zdebug_types.dwo" },
355   { ".debug_cu_index", ".zdebug_cu_index" },
356   { ".debug_tu_index", ".zdebug_tu_index" },
357 };
358
359 /* local data types */
360
361 /* The data in a compilation unit header, after target2host
362    translation, looks like this.  */
363 struct comp_unit_head
364 {
365   unsigned int length;
366   short version;
367   unsigned char addr_size;
368   unsigned char signed_addr_p;
369   sect_offset abbrev_sect_off;
370
371   /* Size of file offsets; either 4 or 8.  */
372   unsigned int offset_size;
373
374   /* Size of the length field; either 4 or 12.  */
375   unsigned int initial_length_size;
376
377   enum dwarf_unit_type unit_type;
378
379   /* Offset to the first byte of this compilation unit header in the
380      .debug_info section, for resolving relative reference dies.  */
381   sect_offset sect_off;
382
383   /* Offset to first die in this cu from the start of the cu.
384      This will be the first byte following the compilation unit header.  */
385   cu_offset first_die_cu_offset;
386
387   /* 64-bit signature of this type unit - it is valid only for
388      UNIT_TYPE DW_UT_type.  */
389   ULONGEST signature;
390
391   /* For types, offset in the type's DIE of the type defined by this TU.  */
392   cu_offset type_cu_offset_in_tu;
393 };
394
395 /* Type used for delaying computation of method physnames.
396    See comments for compute_delayed_physnames.  */
397 struct delayed_method_info
398 {
399   /* The type to which the method is attached, i.e., its parent class.  */
400   struct type *type;
401
402   /* The index of the method in the type's function fieldlists.  */
403   int fnfield_index;
404
405   /* The index of the method in the fieldlist.  */
406   int index;
407
408   /* The name of the DIE.  */
409   const char *name;
410
411   /*  The DIE associated with this method.  */
412   struct die_info *die;
413 };
414
415 /* Internal state when decoding a particular compilation unit.  */
416 struct dwarf2_cu
417 {
418   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
419   ~dwarf2_cu ();
420
421   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
422
423   /* The header of the compilation unit.  */
424   struct comp_unit_head header {};
425
426   /* Base address of this compilation unit.  */
427   CORE_ADDR base_address = 0;
428
429   /* Non-zero if base_address has been set.  */
430   int base_known = 0;
431
432   /* The language we are debugging.  */
433   enum language language = language_unknown;
434   const struct language_defn *language_defn = nullptr;
435
436   const char *producer = nullptr;
437
438   /* The symtab builder for this CU.  This is only non-NULL when full
439      symbols are being read.  */
440   std::unique_ptr<buildsym_compunit> builder;
441
442   /* The generic symbol table building routines have separate lists for
443      file scope symbols and all all other scopes (local scopes).  So
444      we need to select the right one to pass to add_symbol_to_list().
445      We do it by keeping a pointer to the correct list in list_in_scope.
446
447      FIXME: The original dwarf code just treated the file scope as the
448      first local scope, and all other local scopes as nested local
449      scopes, and worked fine.  Check to see if we really need to
450      distinguish these in buildsym.c.  */
451   struct pending **list_in_scope = nullptr;
452
453   /* Hash table holding all the loaded partial DIEs
454      with partial_die->offset.SECT_OFF as hash.  */
455   htab_t partial_dies = nullptr;
456
457   /* Storage for things with the same lifetime as this read-in compilation
458      unit, including partial DIEs.  */
459   auto_obstack comp_unit_obstack;
460
461   /* When multiple dwarf2_cu structures are living in memory, this field
462      chains them all together, so that they can be released efficiently.
463      We will probably also want a generation counter so that most-recently-used
464      compilation units are cached...  */
465   struct dwarf2_per_cu_data *read_in_chain = nullptr;
466
467   /* Backlink to our per_cu entry.  */
468   struct dwarf2_per_cu_data *per_cu;
469
470   /* How many compilation units ago was this CU last referenced?  */
471   int last_used = 0;
472
473   /* A hash table of DIE cu_offset for following references with
474      die_info->offset.sect_off as hash.  */
475   htab_t die_hash = nullptr;
476
477   /* Full DIEs if read in.  */
478   struct die_info *dies = nullptr;
479
480   /* A set of pointers to dwarf2_per_cu_data objects for compilation
481      units referenced by this one.  Only set during full symbol processing;
482      partial symbol tables do not have dependencies.  */
483   htab_t dependencies = nullptr;
484
485   /* Header data from the line table, during full symbol processing.  */
486   struct line_header *line_header = nullptr;
487   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
488      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
489      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
490      to the line header as long as this DIE is being processed.  See
491      process_die_scope.  */
492   die_info *line_header_die_owner = nullptr;
493
494   /* A list of methods which need to have physnames computed
495      after all type information has been read.  */
496   std::vector<delayed_method_info> method_list;
497
498   /* To be copied to symtab->call_site_htab.  */
499   htab_t call_site_htab = nullptr;
500
501   /* Non-NULL if this CU came from a DWO file.
502      There is an invariant here that is important to remember:
503      Except for attributes copied from the top level DIE in the "main"
504      (or "stub") file in preparation for reading the DWO file
505      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
506      Either there isn't a DWO file (in which case this is NULL and the point
507      is moot), or there is and either we're not going to read it (in which
508      case this is NULL) or there is and we are reading it (in which case this
509      is non-NULL).  */
510   struct dwo_unit *dwo_unit = nullptr;
511
512   /* The DW_AT_addr_base attribute if present, zero otherwise
513      (zero is a valid value though).
514      Note this value comes from the Fission stub CU/TU's DIE.  */
515   ULONGEST addr_base = 0;
516
517   /* The DW_AT_ranges_base attribute if present, zero otherwise
518      (zero is a valid value though).
519      Note this value comes from the Fission stub CU/TU's DIE.
520      Also note that the value is zero in the non-DWO case so this value can
521      be used without needing to know whether DWO files are in use or not.
522      N.B. This does not apply to DW_AT_ranges appearing in
523      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
524      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
525      DW_AT_ranges_base *would* have to be applied, and we'd have to care
526      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
527   ULONGEST ranges_base = 0;
528
529   /* When reading debug info generated by older versions of rustc, we
530      have to rewrite some union types to be struct types with a
531      variant part.  This rewriting must be done after the CU is fully
532      read in, because otherwise at the point of rewriting some struct
533      type might not have been fully processed.  So, we keep a list of
534      all such types here and process them after expansion.  */
535   std::vector<struct type *> rust_unions;
536
537   /* Mark used when releasing cached dies.  */
538   unsigned int mark : 1;
539
540   /* This CU references .debug_loc.  See the symtab->locations_valid field.
541      This test is imperfect as there may exist optimized debug code not using
542      any location list and still facing inlining issues if handled as
543      unoptimized code.  For a future better test see GCC PR other/32998.  */
544   unsigned int has_loclist : 1;
545
546   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
547      if all the producer_is_* fields are valid.  This information is cached
548      because profiling CU expansion showed excessive time spent in
549      producer_is_gxx_lt_4_6.  */
550   unsigned int checked_producer : 1;
551   unsigned int producer_is_gxx_lt_4_6 : 1;
552   unsigned int producer_is_gcc_lt_4_3 : 1;
553   unsigned int producer_is_icc_lt_14 : 1;
554
555   /* When set, the file that we're processing is known to have
556      debugging info for C++ namespaces.  GCC 3.3.x did not produce
557      this information, but later versions do.  */
558
559   unsigned int processing_has_namespace_info : 1;
560
561   struct partial_die_info *find_partial_die (sect_offset sect_off);
562 };
563
564 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
565    This includes type_unit_group and quick_file_names.  */
566
567 struct stmt_list_hash
568 {
569   /* The DWO unit this table is from or NULL if there is none.  */
570   struct dwo_unit *dwo_unit;
571
572   /* Offset in .debug_line or .debug_line.dwo.  */
573   sect_offset line_sect_off;
574 };
575
576 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
577    an object of this type.  */
578
579 struct type_unit_group
580 {
581   /* dwarf2read.c's main "handle" on a TU symtab.
582      To simplify things we create an artificial CU that "includes" all the
583      type units using this stmt_list so that the rest of the code still has
584      a "per_cu" handle on the symtab.
585      This PER_CU is recognized by having no section.  */
586 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
587   struct dwarf2_per_cu_data per_cu;
588
589   /* The TUs that share this DW_AT_stmt_list entry.
590      This is added to while parsing type units to build partial symtabs,
591      and is deleted afterwards and not used again.  */
592   VEC (sig_type_ptr) *tus;
593
594   /* The compunit symtab.
595      Type units in a group needn't all be defined in the same source file,
596      so we create an essentially anonymous symtab as the compunit symtab.  */
597   struct compunit_symtab *compunit_symtab;
598
599   /* The data used to construct the hash key.  */
600   struct stmt_list_hash hash;
601
602   /* The number of symtabs from the line header.
603      The value here must match line_header.num_file_names.  */
604   unsigned int num_symtabs;
605
606   /* The symbol tables for this TU (obtained from the files listed in
607      DW_AT_stmt_list).
608      WARNING: The order of entries here must match the order of entries
609      in the line header.  After the first TU using this type_unit_group, the
610      line header for the subsequent TUs is recreated from this.  This is done
611      because we need to use the same symtabs for each TU using the same
612      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
613      there's no guarantee the line header doesn't have duplicate entries.  */
614   struct symtab **symtabs;
615 };
616
617 /* These sections are what may appear in a (real or virtual) DWO file.  */
618
619 struct dwo_sections
620 {
621   struct dwarf2_section_info abbrev;
622   struct dwarf2_section_info line;
623   struct dwarf2_section_info loc;
624   struct dwarf2_section_info loclists;
625   struct dwarf2_section_info macinfo;
626   struct dwarf2_section_info macro;
627   struct dwarf2_section_info str;
628   struct dwarf2_section_info str_offsets;
629   /* In the case of a virtual DWO file, these two are unused.  */
630   struct dwarf2_section_info info;
631   VEC (dwarf2_section_info_def) *types;
632 };
633
634 /* CUs/TUs in DWP/DWO files.  */
635
636 struct dwo_unit
637 {
638   /* Backlink to the containing struct dwo_file.  */
639   struct dwo_file *dwo_file;
640
641   /* The "id" that distinguishes this CU/TU.
642      .debug_info calls this "dwo_id", .debug_types calls this "signature".
643      Since signatures came first, we stick with it for consistency.  */
644   ULONGEST signature;
645
646   /* The section this CU/TU lives in, in the DWO file.  */
647   struct dwarf2_section_info *section;
648
649   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
650   sect_offset sect_off;
651   unsigned int length;
652
653   /* For types, offset in the type's DIE of the type defined by this TU.  */
654   cu_offset type_offset_in_tu;
655 };
656
657 /* include/dwarf2.h defines the DWP section codes.
658    It defines a max value but it doesn't define a min value, which we
659    use for error checking, so provide one.  */
660
661 enum dwp_v2_section_ids
662 {
663   DW_SECT_MIN = 1
664 };
665
666 /* Data for one DWO file.
667
668    This includes virtual DWO files (a virtual DWO file is a DWO file as it
669    appears in a DWP file).  DWP files don't really have DWO files per se -
670    comdat folding of types "loses" the DWO file they came from, and from
671    a high level view DWP files appear to contain a mass of random types.
672    However, to maintain consistency with the non-DWP case we pretend DWP
673    files contain virtual DWO files, and we assign each TU with one virtual
674    DWO file (generally based on the line and abbrev section offsets -
675    a heuristic that seems to work in practice).  */
676
677 struct dwo_file
678 {
679   /* The DW_AT_GNU_dwo_name attribute.
680      For virtual DWO files the name is constructed from the section offsets
681      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
682      from related CU+TUs.  */
683   const char *dwo_name;
684
685   /* The DW_AT_comp_dir attribute.  */
686   const char *comp_dir;
687
688   /* The bfd, when the file is open.  Otherwise this is NULL.
689      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
690   bfd *dbfd;
691
692   /* The sections that make up this DWO file.
693      Remember that for virtual DWO files in DWP V2, these are virtual
694      sections (for lack of a better name).  */
695   struct dwo_sections sections;
696
697   /* The CUs in the file.
698      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
699      an extension to handle LLVM's Link Time Optimization output (where
700      multiple source files may be compiled into a single object/dwo pair). */
701   htab_t cus;
702
703   /* Table of TUs in the file.
704      Each element is a struct dwo_unit.  */
705   htab_t tus;
706 };
707
708 /* These sections are what may appear in a DWP file.  */
709
710 struct dwp_sections
711 {
712   /* These are used by both DWP version 1 and 2.  */
713   struct dwarf2_section_info str;
714   struct dwarf2_section_info cu_index;
715   struct dwarf2_section_info tu_index;
716
717   /* These are only used by DWP version 2 files.
718      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
719      sections are referenced by section number, and are not recorded here.
720      In DWP version 2 there is at most one copy of all these sections, each
721      section being (effectively) comprised of the concatenation of all of the
722      individual sections that exist in the version 1 format.
723      To keep the code simple we treat each of these concatenated pieces as a
724      section itself (a virtual section?).  */
725   struct dwarf2_section_info abbrev;
726   struct dwarf2_section_info info;
727   struct dwarf2_section_info line;
728   struct dwarf2_section_info loc;
729   struct dwarf2_section_info macinfo;
730   struct dwarf2_section_info macro;
731   struct dwarf2_section_info str_offsets;
732   struct dwarf2_section_info types;
733 };
734
735 /* These sections are what may appear in a virtual DWO file in DWP version 1.
736    A virtual DWO file is a DWO file as it appears in a DWP file.  */
737
738 struct virtual_v1_dwo_sections
739 {
740   struct dwarf2_section_info abbrev;
741   struct dwarf2_section_info line;
742   struct dwarf2_section_info loc;
743   struct dwarf2_section_info macinfo;
744   struct dwarf2_section_info macro;
745   struct dwarf2_section_info str_offsets;
746   /* Each DWP hash table entry records one CU or one TU.
747      That is recorded here, and copied to dwo_unit.section.  */
748   struct dwarf2_section_info info_or_types;
749 };
750
751 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
752    In version 2, the sections of the DWO files are concatenated together
753    and stored in one section of that name.  Thus each ELF section contains
754    several "virtual" sections.  */
755
756 struct virtual_v2_dwo_sections
757 {
758   bfd_size_type abbrev_offset;
759   bfd_size_type abbrev_size;
760
761   bfd_size_type line_offset;
762   bfd_size_type line_size;
763
764   bfd_size_type loc_offset;
765   bfd_size_type loc_size;
766
767   bfd_size_type macinfo_offset;
768   bfd_size_type macinfo_size;
769
770   bfd_size_type macro_offset;
771   bfd_size_type macro_size;
772
773   bfd_size_type str_offsets_offset;
774   bfd_size_type str_offsets_size;
775
776   /* Each DWP hash table entry records one CU or one TU.
777      That is recorded here, and copied to dwo_unit.section.  */
778   bfd_size_type info_or_types_offset;
779   bfd_size_type info_or_types_size;
780 };
781
782 /* Contents of DWP hash tables.  */
783
784 struct dwp_hash_table
785 {
786   uint32_t version, nr_columns;
787   uint32_t nr_units, nr_slots;
788   const gdb_byte *hash_table, *unit_table;
789   union
790   {
791     struct
792     {
793       const gdb_byte *indices;
794     } v1;
795     struct
796     {
797       /* This is indexed by column number and gives the id of the section
798          in that column.  */
799 #define MAX_NR_V2_DWO_SECTIONS \
800   (1 /* .debug_info or .debug_types */ \
801    + 1 /* .debug_abbrev */ \
802    + 1 /* .debug_line */ \
803    + 1 /* .debug_loc */ \
804    + 1 /* .debug_str_offsets */ \
805    + 1 /* .debug_macro or .debug_macinfo */)
806       int section_ids[MAX_NR_V2_DWO_SECTIONS];
807       const gdb_byte *offsets;
808       const gdb_byte *sizes;
809     } v2;
810   } section_pool;
811 };
812
813 /* Data for one DWP file.  */
814
815 struct dwp_file
816 {
817   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
818     : name (name_),
819       dbfd (std::move (abfd))
820   {
821   }
822
823   /* Name of the file.  */
824   const char *name;
825
826   /* File format version.  */
827   int version = 0;
828
829   /* The bfd.  */
830   gdb_bfd_ref_ptr dbfd;
831
832   /* Section info for this file.  */
833   struct dwp_sections sections {};
834
835   /* Table of CUs in the file.  */
836   const struct dwp_hash_table *cus = nullptr;
837
838   /* Table of TUs in the file.  */
839   const struct dwp_hash_table *tus = nullptr;
840
841   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
842   htab_t loaded_cus {};
843   htab_t loaded_tus {};
844
845   /* Table to map ELF section numbers to their sections.
846      This is only needed for the DWP V1 file format.  */
847   unsigned int num_sections = 0;
848   asection **elf_sections = nullptr;
849 };
850
851 /* This represents a '.dwz' file.  */
852
853 struct dwz_file
854 {
855   dwz_file (gdb_bfd_ref_ptr &&bfd)
856     : dwz_bfd (std::move (bfd))
857   {
858   }
859
860   /* A dwz file can only contain a few sections.  */
861   struct dwarf2_section_info abbrev {};
862   struct dwarf2_section_info info {};
863   struct dwarf2_section_info str {};
864   struct dwarf2_section_info line {};
865   struct dwarf2_section_info macro {};
866   struct dwarf2_section_info gdb_index {};
867   struct dwarf2_section_info debug_names {};
868
869   /* The dwz's BFD.  */
870   gdb_bfd_ref_ptr dwz_bfd;
871 };
872
873 /* Struct used to pass misc. parameters to read_die_and_children, et
874    al.  which are used for both .debug_info and .debug_types dies.
875    All parameters here are unchanging for the life of the call.  This
876    struct exists to abstract away the constant parameters of die reading.  */
877
878 struct die_reader_specs
879 {
880   /* The bfd of die_section.  */
881   bfd* abfd;
882
883   /* The CU of the DIE we are parsing.  */
884   struct dwarf2_cu *cu;
885
886   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
887   struct dwo_file *dwo_file;
888
889   /* The section the die comes from.
890      This is either .debug_info or .debug_types, or the .dwo variants.  */
891   struct dwarf2_section_info *die_section;
892
893   /* die_section->buffer.  */
894   const gdb_byte *buffer;
895
896   /* The end of the buffer.  */
897   const gdb_byte *buffer_end;
898
899   /* The value of the DW_AT_comp_dir attribute.  */
900   const char *comp_dir;
901
902   /* The abbreviation table to use when reading the DIEs.  */
903   struct abbrev_table *abbrev_table;
904 };
905
906 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
907 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
908                                       const gdb_byte *info_ptr,
909                                       struct die_info *comp_unit_die,
910                                       int has_children,
911                                       void *data);
912
913 /* A 1-based directory index.  This is a strong typedef to prevent
914    accidentally using a directory index as a 0-based index into an
915    array/vector.  */
916 enum class dir_index : unsigned int {};
917
918 /* Likewise, a 1-based file name index.  */
919 enum class file_name_index : unsigned int {};
920
921 struct file_entry
922 {
923   file_entry () = default;
924
925   file_entry (const char *name_, dir_index d_index_,
926               unsigned int mod_time_, unsigned int length_)
927     : name (name_),
928       d_index (d_index_),
929       mod_time (mod_time_),
930       length (length_)
931   {}
932
933   /* Return the include directory at D_INDEX stored in LH.  Returns
934      NULL if D_INDEX is out of bounds.  */
935   const char *include_dir (const line_header *lh) const;
936
937   /* The file name.  Note this is an observing pointer.  The memory is
938      owned by debug_line_buffer.  */
939   const char *name {};
940
941   /* The directory index (1-based).  */
942   dir_index d_index {};
943
944   unsigned int mod_time {};
945
946   unsigned int length {};
947
948   /* True if referenced by the Line Number Program.  */
949   bool included_p {};
950
951   /* The associated symbol table, if any.  */
952   struct symtab *symtab {};
953 };
954
955 /* The line number information for a compilation unit (found in the
956    .debug_line section) begins with a "statement program header",
957    which contains the following information.  */
958 struct line_header
959 {
960   line_header ()
961     : offset_in_dwz {}
962   {}
963
964   /* Add an entry to the include directory table.  */
965   void add_include_dir (const char *include_dir);
966
967   /* Add an entry to the file name table.  */
968   void add_file_name (const char *name, dir_index d_index,
969                       unsigned int mod_time, unsigned int length);
970
971   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
972      is out of bounds.  */
973   const char *include_dir_at (dir_index index) const
974   {
975     /* Convert directory index number (1-based) to vector index
976        (0-based).  */
977     size_t vec_index = to_underlying (index) - 1;
978
979     if (vec_index >= include_dirs.size ())
980       return NULL;
981     return include_dirs[vec_index];
982   }
983
984   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
985      is out of bounds.  */
986   file_entry *file_name_at (file_name_index index)
987   {
988     /* Convert file name index number (1-based) to vector index
989        (0-based).  */
990     size_t vec_index = to_underlying (index) - 1;
991
992     if (vec_index >= file_names.size ())
993       return NULL;
994     return &file_names[vec_index];
995   }
996
997   /* Const version of the above.  */
998   const file_entry *file_name_at (unsigned int index) const
999   {
1000     if (index >= file_names.size ())
1001       return NULL;
1002     return &file_names[index];
1003   }
1004
1005   /* Offset of line number information in .debug_line section.  */
1006   sect_offset sect_off {};
1007
1008   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1009   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1010
1011   unsigned int total_length {};
1012   unsigned short version {};
1013   unsigned int header_length {};
1014   unsigned char minimum_instruction_length {};
1015   unsigned char maximum_ops_per_instruction {};
1016   unsigned char default_is_stmt {};
1017   int line_base {};
1018   unsigned char line_range {};
1019   unsigned char opcode_base {};
1020
1021   /* standard_opcode_lengths[i] is the number of operands for the
1022      standard opcode whose value is i.  This means that
1023      standard_opcode_lengths[0] is unused, and the last meaningful
1024      element is standard_opcode_lengths[opcode_base - 1].  */
1025   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1026
1027   /* The include_directories table.  Note these are observing
1028      pointers.  The memory is owned by debug_line_buffer.  */
1029   std::vector<const char *> include_dirs;
1030
1031   /* The file_names table.  */
1032   std::vector<file_entry> file_names;
1033
1034   /* The start and end of the statement program following this
1035      header.  These point into dwarf2_per_objfile->line_buffer.  */
1036   const gdb_byte *statement_program_start {}, *statement_program_end {};
1037 };
1038
1039 typedef std::unique_ptr<line_header> line_header_up;
1040
1041 const char *
1042 file_entry::include_dir (const line_header *lh) const
1043 {
1044   return lh->include_dir_at (d_index);
1045 }
1046
1047 /* When we construct a partial symbol table entry we only
1048    need this much information.  */
1049 struct partial_die_info : public allocate_on_obstack
1050   {
1051     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1052
1053     /* Disable assign but still keep copy ctor, which is needed
1054        load_partial_dies.   */
1055     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1056
1057     /* Adjust the partial die before generating a symbol for it.  This
1058        function may set the is_external flag or change the DIE's
1059        name.  */
1060     void fixup (struct dwarf2_cu *cu);
1061
1062     /* Read a minimal amount of information into the minimal die
1063        structure.  */
1064     const gdb_byte *read (const struct die_reader_specs *reader,
1065                           const struct abbrev_info &abbrev,
1066                           const gdb_byte *info_ptr);
1067
1068     /* Offset of this DIE.  */
1069     const sect_offset sect_off;
1070
1071     /* DWARF-2 tag for this DIE.  */
1072     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1073
1074     /* Assorted flags describing the data found in this DIE.  */
1075     const unsigned int has_children : 1;
1076
1077     unsigned int is_external : 1;
1078     unsigned int is_declaration : 1;
1079     unsigned int has_type : 1;
1080     unsigned int has_specification : 1;
1081     unsigned int has_pc_info : 1;
1082     unsigned int may_be_inlined : 1;
1083
1084     /* This DIE has been marked DW_AT_main_subprogram.  */
1085     unsigned int main_subprogram : 1;
1086
1087     /* Flag set if the SCOPE field of this structure has been
1088        computed.  */
1089     unsigned int scope_set : 1;
1090
1091     /* Flag set if the DIE has a byte_size attribute.  */
1092     unsigned int has_byte_size : 1;
1093
1094     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1095     unsigned int has_const_value : 1;
1096
1097     /* Flag set if any of the DIE's children are template arguments.  */
1098     unsigned int has_template_arguments : 1;
1099
1100     /* Flag set if fixup has been called on this die.  */
1101     unsigned int fixup_called : 1;
1102
1103     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1104     unsigned int is_dwz : 1;
1105
1106     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1107     unsigned int spec_is_dwz : 1;
1108
1109     /* The name of this DIE.  Normally the value of DW_AT_name, but
1110        sometimes a default name for unnamed DIEs.  */
1111     const char *name = nullptr;
1112
1113     /* The linkage name, if present.  */
1114     const char *linkage_name = nullptr;
1115
1116     /* The scope to prepend to our children.  This is generally
1117        allocated on the comp_unit_obstack, so will disappear
1118        when this compilation unit leaves the cache.  */
1119     const char *scope = nullptr;
1120
1121     /* Some data associated with the partial DIE.  The tag determines
1122        which field is live.  */
1123     union
1124     {
1125       /* The location description associated with this DIE, if any.  */
1126       struct dwarf_block *locdesc;
1127       /* The offset of an import, for DW_TAG_imported_unit.  */
1128       sect_offset sect_off;
1129     } d {};
1130
1131     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1132     CORE_ADDR lowpc = 0;
1133     CORE_ADDR highpc = 0;
1134
1135     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1136        DW_AT_sibling, if any.  */
1137     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1138        could return DW_AT_sibling values to its caller load_partial_dies.  */
1139     const gdb_byte *sibling = nullptr;
1140
1141     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1142        DW_AT_specification (or DW_AT_abstract_origin or
1143        DW_AT_extension).  */
1144     sect_offset spec_offset {};
1145
1146     /* Pointers to this DIE's parent, first child, and next sibling,
1147        if any.  */
1148     struct partial_die_info *die_parent = nullptr;
1149     struct partial_die_info *die_child = nullptr;
1150     struct partial_die_info *die_sibling = nullptr;
1151
1152     friend struct partial_die_info *
1153     dwarf2_cu::find_partial_die (sect_offset sect_off);
1154
1155   private:
1156     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1157     partial_die_info (sect_offset sect_off)
1158       : partial_die_info (sect_off, DW_TAG_padding, 0)
1159     {
1160     }
1161
1162     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1163                       int has_children_)
1164       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1165     {
1166       is_external = 0;
1167       is_declaration = 0;
1168       has_type = 0;
1169       has_specification = 0;
1170       has_pc_info = 0;
1171       may_be_inlined = 0;
1172       main_subprogram = 0;
1173       scope_set = 0;
1174       has_byte_size = 0;
1175       has_const_value = 0;
1176       has_template_arguments = 0;
1177       fixup_called = 0;
1178       is_dwz = 0;
1179       spec_is_dwz = 0;
1180     }
1181   };
1182
1183 /* This data structure holds the information of an abbrev.  */
1184 struct abbrev_info
1185   {
1186     unsigned int number;        /* number identifying abbrev */
1187     enum dwarf_tag tag;         /* dwarf tag */
1188     unsigned short has_children;                /* boolean */
1189     unsigned short num_attrs;   /* number of attributes */
1190     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1191     struct abbrev_info *next;   /* next in chain */
1192   };
1193
1194 struct attr_abbrev
1195   {
1196     ENUM_BITFIELD(dwarf_attribute) name : 16;
1197     ENUM_BITFIELD(dwarf_form) form : 16;
1198
1199     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1200     LONGEST implicit_const;
1201   };
1202
1203 /* Size of abbrev_table.abbrev_hash_table.  */
1204 #define ABBREV_HASH_SIZE 121
1205
1206 /* Top level data structure to contain an abbreviation table.  */
1207
1208 struct abbrev_table
1209 {
1210   explicit abbrev_table (sect_offset off)
1211     : sect_off (off)
1212   {
1213     m_abbrevs =
1214       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1215     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1216   }
1217
1218   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1219
1220   /* Allocate space for a struct abbrev_info object in
1221      ABBREV_TABLE.  */
1222   struct abbrev_info *alloc_abbrev ();
1223
1224   /* Add an abbreviation to the table.  */
1225   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1226
1227   /* Look up an abbrev in the table.
1228      Returns NULL if the abbrev is not found.  */
1229
1230   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1231
1232
1233   /* Where the abbrev table came from.
1234      This is used as a sanity check when the table is used.  */
1235   const sect_offset sect_off;
1236
1237   /* Storage for the abbrev table.  */
1238   auto_obstack abbrev_obstack;
1239
1240 private:
1241
1242   /* Hash table of abbrevs.
1243      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1244      It could be statically allocated, but the previous code didn't so we
1245      don't either.  */
1246   struct abbrev_info **m_abbrevs;
1247 };
1248
1249 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1250
1251 /* Attributes have a name and a value.  */
1252 struct attribute
1253   {
1254     ENUM_BITFIELD(dwarf_attribute) name : 16;
1255     ENUM_BITFIELD(dwarf_form) form : 15;
1256
1257     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1258        field should be in u.str (existing only for DW_STRING) but it is kept
1259        here for better struct attribute alignment.  */
1260     unsigned int string_is_canonical : 1;
1261
1262     union
1263       {
1264         const char *str;
1265         struct dwarf_block *blk;
1266         ULONGEST unsnd;
1267         LONGEST snd;
1268         CORE_ADDR addr;
1269         ULONGEST signature;
1270       }
1271     u;
1272   };
1273
1274 /* This data structure holds a complete die structure.  */
1275 struct die_info
1276   {
1277     /* DWARF-2 tag for this DIE.  */
1278     ENUM_BITFIELD(dwarf_tag) tag : 16;
1279
1280     /* Number of attributes */
1281     unsigned char num_attrs;
1282
1283     /* True if we're presently building the full type name for the
1284        type derived from this DIE.  */
1285     unsigned char building_fullname : 1;
1286
1287     /* True if this die is in process.  PR 16581.  */
1288     unsigned char in_process : 1;
1289
1290     /* Abbrev number */
1291     unsigned int abbrev;
1292
1293     /* Offset in .debug_info or .debug_types section.  */
1294     sect_offset sect_off;
1295
1296     /* The dies in a compilation unit form an n-ary tree.  PARENT
1297        points to this die's parent; CHILD points to the first child of
1298        this node; and all the children of a given node are chained
1299        together via their SIBLING fields.  */
1300     struct die_info *child;     /* Its first child, if any.  */
1301     struct die_info *sibling;   /* Its next sibling, if any.  */
1302     struct die_info *parent;    /* Its parent, if any.  */
1303
1304     /* An array of attributes, with NUM_ATTRS elements.  There may be
1305        zero, but it's not common and zero-sized arrays are not
1306        sufficiently portable C.  */
1307     struct attribute attrs[1];
1308   };
1309
1310 /* Get at parts of an attribute structure.  */
1311
1312 #define DW_STRING(attr)    ((attr)->u.str)
1313 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1314 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1315 #define DW_BLOCK(attr)     ((attr)->u.blk)
1316 #define DW_SND(attr)       ((attr)->u.snd)
1317 #define DW_ADDR(attr)      ((attr)->u.addr)
1318 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1319
1320 /* Blocks are a bunch of untyped bytes.  */
1321 struct dwarf_block
1322   {
1323     size_t size;
1324
1325     /* Valid only if SIZE is not zero.  */
1326     const gdb_byte *data;
1327   };
1328
1329 #ifndef ATTR_ALLOC_CHUNK
1330 #define ATTR_ALLOC_CHUNK 4
1331 #endif
1332
1333 /* Allocate fields for structs, unions and enums in this size.  */
1334 #ifndef DW_FIELD_ALLOC_CHUNK
1335 #define DW_FIELD_ALLOC_CHUNK 4
1336 #endif
1337
1338 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1339    but this would require a corresponding change in unpack_field_as_long
1340    and friends.  */
1341 static int bits_per_byte = 8;
1342
1343 /* When reading a variant or variant part, we track a bit more
1344    information about the field, and store it in an object of this
1345    type.  */
1346
1347 struct variant_field
1348 {
1349   /* If we see a DW_TAG_variant, then this will be the discriminant
1350      value.  */
1351   ULONGEST discriminant_value;
1352   /* If we see a DW_TAG_variant, then this will be set if this is the
1353      default branch.  */
1354   bool default_branch;
1355   /* While reading a DW_TAG_variant_part, this will be set if this
1356      field is the discriminant.  */
1357   bool is_discriminant;
1358 };
1359
1360 struct nextfield
1361 {
1362   int accessibility = 0;
1363   int virtuality = 0;
1364   /* Extra information to describe a variant or variant part.  */
1365   struct variant_field variant {};
1366   struct field field {};
1367 };
1368
1369 struct fnfieldlist
1370 {
1371   const char *name = nullptr;
1372   std::vector<struct fn_field> fnfields;
1373 };
1374
1375 /* The routines that read and process dies for a C struct or C++ class
1376    pass lists of data member fields and lists of member function fields
1377    in an instance of a field_info structure, as defined below.  */
1378 struct field_info
1379   {
1380     /* List of data member and baseclasses fields.  */
1381     std::vector<struct nextfield> fields;
1382     std::vector<struct nextfield> baseclasses;
1383
1384     /* Number of fields (including baseclasses).  */
1385     int nfields = 0;
1386
1387     /* Set if the accesibility of one of the fields is not public.  */
1388     int non_public_fields = 0;
1389
1390     /* Member function fieldlist array, contains name of possibly overloaded
1391        member function, number of overloaded member functions and a pointer
1392        to the head of the member function field chain.  */
1393     std::vector<struct fnfieldlist> fnfieldlists;
1394
1395     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1396        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1397     std::vector<struct decl_field> typedef_field_list;
1398
1399     /* Nested types defined by this class and the number of elements in this
1400        list.  */
1401     std::vector<struct decl_field> nested_types_list;
1402   };
1403
1404 /* One item on the queue of compilation units to read in full symbols
1405    for.  */
1406 struct dwarf2_queue_item
1407 {
1408   struct dwarf2_per_cu_data *per_cu;
1409   enum language pretend_language;
1410   struct dwarf2_queue_item *next;
1411 };
1412
1413 /* The current queue.  */
1414 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1415
1416 /* Loaded secondary compilation units are kept in memory until they
1417    have not been referenced for the processing of this many
1418    compilation units.  Set this to zero to disable caching.  Cache
1419    sizes of up to at least twenty will improve startup time for
1420    typical inter-CU-reference binaries, at an obvious memory cost.  */
1421 static int dwarf_max_cache_age = 5;
1422 static void
1423 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1424                           struct cmd_list_element *c, const char *value)
1425 {
1426   fprintf_filtered (file, _("The upper bound on the age of cached "
1427                             "DWARF compilation units is %s.\n"),
1428                     value);
1429 }
1430 \f
1431 /* local function prototypes */
1432
1433 static const char *get_section_name (const struct dwarf2_section_info *);
1434
1435 static const char *get_section_file_name (const struct dwarf2_section_info *);
1436
1437 static void dwarf2_find_base_address (struct die_info *die,
1438                                       struct dwarf2_cu *cu);
1439
1440 static struct partial_symtab *create_partial_symtab
1441   (struct dwarf2_per_cu_data *per_cu, const char *name);
1442
1443 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1444                                         const gdb_byte *info_ptr,
1445                                         struct die_info *type_unit_die,
1446                                         int has_children, void *data);
1447
1448 static void dwarf2_build_psymtabs_hard
1449   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1450
1451 static void scan_partial_symbols (struct partial_die_info *,
1452                                   CORE_ADDR *, CORE_ADDR *,
1453                                   int, struct dwarf2_cu *);
1454
1455 static void add_partial_symbol (struct partial_die_info *,
1456                                 struct dwarf2_cu *);
1457
1458 static void add_partial_namespace (struct partial_die_info *pdi,
1459                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1460                                    int set_addrmap, struct dwarf2_cu *cu);
1461
1462 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1463                                 CORE_ADDR *highpc, int set_addrmap,
1464                                 struct dwarf2_cu *cu);
1465
1466 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1467                                      struct dwarf2_cu *cu);
1468
1469 static void add_partial_subprogram (struct partial_die_info *pdi,
1470                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1471                                     int need_pc, struct dwarf2_cu *cu);
1472
1473 static void dwarf2_read_symtab (struct partial_symtab *,
1474                                 struct objfile *);
1475
1476 static void psymtab_to_symtab_1 (struct partial_symtab *);
1477
1478 static abbrev_table_up abbrev_table_read_table
1479   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1480    sect_offset);
1481
1482 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1483
1484 static struct partial_die_info *load_partial_dies
1485   (const struct die_reader_specs *, const gdb_byte *, int);
1486
1487 static struct partial_die_info *find_partial_die (sect_offset, int,
1488                                                   struct dwarf2_cu *);
1489
1490 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1491                                        struct attribute *, struct attr_abbrev *,
1492                                        const gdb_byte *);
1493
1494 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1495
1496 static int read_1_signed_byte (bfd *, const gdb_byte *);
1497
1498 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1499
1500 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1501
1502 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1503
1504 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1505                                unsigned int *);
1506
1507 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1508
1509 static LONGEST read_checked_initial_length_and_offset
1510   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1511    unsigned int *, unsigned int *);
1512
1513 static LONGEST read_offset (bfd *, const gdb_byte *,
1514                             const struct comp_unit_head *,
1515                             unsigned int *);
1516
1517 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1518
1519 static sect_offset read_abbrev_offset
1520   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1521    struct dwarf2_section_info *, sect_offset);
1522
1523 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1524
1525 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1526
1527 static const char *read_indirect_string
1528   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1529    const struct comp_unit_head *, unsigned int *);
1530
1531 static const char *read_indirect_line_string
1532   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1533    const struct comp_unit_head *, unsigned int *);
1534
1535 static const char *read_indirect_string_at_offset
1536   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1537    LONGEST str_offset);
1538
1539 static const char *read_indirect_string_from_dwz
1540   (struct objfile *objfile, struct dwz_file *, LONGEST);
1541
1542 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1543
1544 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1545                                               const gdb_byte *,
1546                                               unsigned int *);
1547
1548 static const char *read_str_index (const struct die_reader_specs *reader,
1549                                    ULONGEST str_index);
1550
1551 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1552
1553 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1554                                       struct dwarf2_cu *);
1555
1556 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1557                                                 unsigned int);
1558
1559 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1560                                        struct dwarf2_cu *cu);
1561
1562 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1563                                struct dwarf2_cu *cu);
1564
1565 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1566
1567 static struct die_info *die_specification (struct die_info *die,
1568                                            struct dwarf2_cu **);
1569
1570 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1571                                                 struct dwarf2_cu *cu);
1572
1573 static void dwarf_decode_lines (struct line_header *, const char *,
1574                                 struct dwarf2_cu *, struct partial_symtab *,
1575                                 CORE_ADDR, int decode_mapping);
1576
1577 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1578                                   const char *);
1579
1580 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1581                                                     const char *, const char *,
1582                                                     CORE_ADDR);
1583
1584 static struct symbol *new_symbol (struct die_info *, struct type *,
1585                                   struct dwarf2_cu *, struct symbol * = NULL);
1586
1587 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1588                                 struct dwarf2_cu *);
1589
1590 static void dwarf2_const_value_attr (const struct attribute *attr,
1591                                      struct type *type,
1592                                      const char *name,
1593                                      struct obstack *obstack,
1594                                      struct dwarf2_cu *cu, LONGEST *value,
1595                                      const gdb_byte **bytes,
1596                                      struct dwarf2_locexpr_baton **baton);
1597
1598 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1599
1600 static int need_gnat_info (struct dwarf2_cu *);
1601
1602 static struct type *die_descriptive_type (struct die_info *,
1603                                           struct dwarf2_cu *);
1604
1605 static void set_descriptive_type (struct type *, struct die_info *,
1606                                   struct dwarf2_cu *);
1607
1608 static struct type *die_containing_type (struct die_info *,
1609                                          struct dwarf2_cu *);
1610
1611 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1612                                      struct dwarf2_cu *);
1613
1614 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1615
1616 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1617
1618 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1619
1620 static char *typename_concat (struct obstack *obs, const char *prefix,
1621                               const char *suffix, int physname,
1622                               struct dwarf2_cu *cu);
1623
1624 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1625
1626 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1627
1628 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1629
1630 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1631
1632 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1633
1634 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1635
1636 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1637                                struct dwarf2_cu *, struct partial_symtab *);
1638
1639 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1640    values.  Keep the items ordered with increasing constraints compliance.  */
1641 enum pc_bounds_kind
1642 {
1643   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1644   PC_BOUNDS_NOT_PRESENT,
1645
1646   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1647      were present but they do not form a valid range of PC addresses.  */
1648   PC_BOUNDS_INVALID,
1649
1650   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1651   PC_BOUNDS_RANGES,
1652
1653   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1654   PC_BOUNDS_HIGH_LOW,
1655 };
1656
1657 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1658                                                  CORE_ADDR *, CORE_ADDR *,
1659                                                  struct dwarf2_cu *,
1660                                                  struct partial_symtab *);
1661
1662 static void get_scope_pc_bounds (struct die_info *,
1663                                  CORE_ADDR *, CORE_ADDR *,
1664                                  struct dwarf2_cu *);
1665
1666 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1667                                         CORE_ADDR, struct dwarf2_cu *);
1668
1669 static void dwarf2_add_field (struct field_info *, struct die_info *,
1670                               struct dwarf2_cu *);
1671
1672 static void dwarf2_attach_fields_to_type (struct field_info *,
1673                                           struct type *, struct dwarf2_cu *);
1674
1675 static void dwarf2_add_member_fn (struct field_info *,
1676                                   struct die_info *, struct type *,
1677                                   struct dwarf2_cu *);
1678
1679 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1680                                              struct type *,
1681                                              struct dwarf2_cu *);
1682
1683 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1684
1685 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1686
1687 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1688
1689 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1690
1691 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1692
1693 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1694
1695 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1696
1697 static struct type *read_module_type (struct die_info *die,
1698                                       struct dwarf2_cu *cu);
1699
1700 static const char *namespace_name (struct die_info *die,
1701                                    int *is_anonymous, struct dwarf2_cu *);
1702
1703 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1704
1705 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1706
1707 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1708                                                        struct dwarf2_cu *);
1709
1710 static struct die_info *read_die_and_siblings_1
1711   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1712    struct die_info *);
1713
1714 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1715                                                const gdb_byte *info_ptr,
1716                                                const gdb_byte **new_info_ptr,
1717                                                struct die_info *parent);
1718
1719 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1720                                         struct die_info **, const gdb_byte *,
1721                                         int *, int);
1722
1723 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1724                                       struct die_info **, const gdb_byte *,
1725                                       int *);
1726
1727 static void process_die (struct die_info *, struct dwarf2_cu *);
1728
1729 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1730                                              struct obstack *);
1731
1732 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1733
1734 static const char *dwarf2_full_name (const char *name,
1735                                      struct die_info *die,
1736                                      struct dwarf2_cu *cu);
1737
1738 static const char *dwarf2_physname (const char *name, struct die_info *die,
1739                                     struct dwarf2_cu *cu);
1740
1741 static struct die_info *dwarf2_extension (struct die_info *die,
1742                                           struct dwarf2_cu **);
1743
1744 static const char *dwarf_tag_name (unsigned int);
1745
1746 static const char *dwarf_attr_name (unsigned int);
1747
1748 static const char *dwarf_form_name (unsigned int);
1749
1750 static const char *dwarf_bool_name (unsigned int);
1751
1752 static const char *dwarf_type_encoding_name (unsigned int);
1753
1754 static struct die_info *sibling_die (struct die_info *);
1755
1756 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1757
1758 static void dump_die_for_error (struct die_info *);
1759
1760 static void dump_die_1 (struct ui_file *, int level, int max_level,
1761                         struct die_info *);
1762
1763 /*static*/ void dump_die (struct die_info *, int max_level);
1764
1765 static void store_in_ref_table (struct die_info *,
1766                                 struct dwarf2_cu *);
1767
1768 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1769
1770 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1771
1772 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1773                                                const struct attribute *,
1774                                                struct dwarf2_cu **);
1775
1776 static struct die_info *follow_die_ref (struct die_info *,
1777                                         const struct attribute *,
1778                                         struct dwarf2_cu **);
1779
1780 static struct die_info *follow_die_sig (struct die_info *,
1781                                         const struct attribute *,
1782                                         struct dwarf2_cu **);
1783
1784 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1785                                          struct dwarf2_cu *);
1786
1787 static struct type *get_DW_AT_signature_type (struct die_info *,
1788                                               const struct attribute *,
1789                                               struct dwarf2_cu *);
1790
1791 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1792
1793 static void read_signatured_type (struct signatured_type *);
1794
1795 static int attr_to_dynamic_prop (const struct attribute *attr,
1796                                  struct die_info *die, struct dwarf2_cu *cu,
1797                                  struct dynamic_prop *prop);
1798
1799 /* memory allocation interface */
1800
1801 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1802
1803 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1804
1805 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1806
1807 static int attr_form_is_block (const struct attribute *);
1808
1809 static int attr_form_is_section_offset (const struct attribute *);
1810
1811 static int attr_form_is_constant (const struct attribute *);
1812
1813 static int attr_form_is_ref (const struct attribute *);
1814
1815 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1816                                    struct dwarf2_loclist_baton *baton,
1817                                    const struct attribute *attr);
1818
1819 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1820                                          struct symbol *sym,
1821                                          struct dwarf2_cu *cu,
1822                                          int is_block);
1823
1824 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1825                                      const gdb_byte *info_ptr,
1826                                      struct abbrev_info *abbrev);
1827
1828 static hashval_t partial_die_hash (const void *item);
1829
1830 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1831
1832 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1833   (sect_offset sect_off, unsigned int offset_in_dwz,
1834    struct dwarf2_per_objfile *dwarf2_per_objfile);
1835
1836 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1837                                    struct die_info *comp_unit_die,
1838                                    enum language pretend_language);
1839
1840 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1841
1842 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1843
1844 static struct type *set_die_type (struct die_info *, struct type *,
1845                                   struct dwarf2_cu *);
1846
1847 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1848
1849 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1850
1851 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1852                                  enum language);
1853
1854 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1855                                     enum language);
1856
1857 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1858                                     enum language);
1859
1860 static void dwarf2_add_dependence (struct dwarf2_cu *,
1861                                    struct dwarf2_per_cu_data *);
1862
1863 static void dwarf2_mark (struct dwarf2_cu *);
1864
1865 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1866
1867 static struct type *get_die_type_at_offset (sect_offset,
1868                                             struct dwarf2_per_cu_data *);
1869
1870 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1871
1872 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1873                              enum language pretend_language);
1874
1875 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1876
1877 /* Class, the destructor of which frees all allocated queue entries.  This
1878    will only have work to do if an error was thrown while processing the
1879    dwarf.  If no error was thrown then the queue entries should have all
1880    been processed, and freed, as we went along.  */
1881
1882 class dwarf2_queue_guard
1883 {
1884 public:
1885   dwarf2_queue_guard () = default;
1886
1887   /* Free any entries remaining on the queue.  There should only be
1888      entries left if we hit an error while processing the dwarf.  */
1889   ~dwarf2_queue_guard ()
1890   {
1891     struct dwarf2_queue_item *item, *last;
1892
1893     item = dwarf2_queue;
1894     while (item)
1895       {
1896         /* Anything still marked queued is likely to be in an
1897            inconsistent state, so discard it.  */
1898         if (item->per_cu->queued)
1899           {
1900             if (item->per_cu->cu != NULL)
1901               free_one_cached_comp_unit (item->per_cu);
1902             item->per_cu->queued = 0;
1903           }
1904
1905         last = item;
1906         item = item->next;
1907         xfree (last);
1908       }
1909
1910     dwarf2_queue = dwarf2_queue_tail = NULL;
1911   }
1912 };
1913
1914 /* The return type of find_file_and_directory.  Note, the enclosed
1915    string pointers are only valid while this object is valid.  */
1916
1917 struct file_and_directory
1918 {
1919   /* The filename.  This is never NULL.  */
1920   const char *name;
1921
1922   /* The compilation directory.  NULL if not known.  If we needed to
1923      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1924      points directly to the DW_AT_comp_dir string attribute owned by
1925      the obstack that owns the DIE.  */
1926   const char *comp_dir;
1927
1928   /* If we needed to build a new string for comp_dir, this is what
1929      owns the storage.  */
1930   std::string comp_dir_storage;
1931 };
1932
1933 static file_and_directory find_file_and_directory (struct die_info *die,
1934                                                    struct dwarf2_cu *cu);
1935
1936 static char *file_full_name (int file, struct line_header *lh,
1937                              const char *comp_dir);
1938
1939 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1940 enum class rcuh_kind { COMPILE, TYPE };
1941
1942 static const gdb_byte *read_and_check_comp_unit_head
1943   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1944    struct comp_unit_head *header,
1945    struct dwarf2_section_info *section,
1946    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1947    rcuh_kind section_kind);
1948
1949 static void init_cutu_and_read_dies
1950   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1951    int use_existing_cu, int keep, bool skip_partial,
1952    die_reader_func_ftype *die_reader_func, void *data);
1953
1954 static void init_cutu_and_read_dies_simple
1955   (struct dwarf2_per_cu_data *this_cu,
1956    die_reader_func_ftype *die_reader_func, void *data);
1957
1958 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1959
1960 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1961
1962 static struct dwo_unit *lookup_dwo_unit_in_dwp
1963   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1964    struct dwp_file *dwp_file, const char *comp_dir,
1965    ULONGEST signature, int is_debug_types);
1966
1967 static struct dwp_file *get_dwp_file
1968   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1969
1970 static struct dwo_unit *lookup_dwo_comp_unit
1971   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1972
1973 static struct dwo_unit *lookup_dwo_type_unit
1974   (struct signatured_type *, const char *, const char *);
1975
1976 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1977
1978 static void free_dwo_file (struct dwo_file *);
1979
1980 /* A unique_ptr helper to free a dwo_file.  */
1981
1982 struct dwo_file_deleter
1983 {
1984   void operator() (struct dwo_file *df) const
1985   {
1986     free_dwo_file (df);
1987   }
1988 };
1989
1990 /* A unique pointer to a dwo_file.  */
1991
1992 typedef std::unique_ptr<struct dwo_file, dwo_file_deleter> dwo_file_up;
1993
1994 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
1995
1996 static void check_producer (struct dwarf2_cu *cu);
1997
1998 static void free_line_header_voidp (void *arg);
1999 \f
2000 /* Various complaints about symbol reading that don't abort the process.  */
2001
2002 static void
2003 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2004 {
2005   complaint (_("statement list doesn't fit in .debug_line section"));
2006 }
2007
2008 static void
2009 dwarf2_debug_line_missing_file_complaint (void)
2010 {
2011   complaint (_(".debug_line section has line data without a file"));
2012 }
2013
2014 static void
2015 dwarf2_debug_line_missing_end_sequence_complaint (void)
2016 {
2017   complaint (_(".debug_line section has line "
2018                "program sequence without an end"));
2019 }
2020
2021 static void
2022 dwarf2_complex_location_expr_complaint (void)
2023 {
2024   complaint (_("location expression too complex"));
2025 }
2026
2027 static void
2028 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2029                                               int arg3)
2030 {
2031   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
2032              arg1, arg2, arg3);
2033 }
2034
2035 static void
2036 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2037 {
2038   complaint (_("debug info runs off end of %s section"
2039                " [in module %s]"),
2040              get_section_name (section),
2041              get_section_file_name (section));
2042 }
2043
2044 static void
2045 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2046 {
2047   complaint (_("macro debug info contains a "
2048                "malformed macro definition:\n`%s'"),
2049              arg1);
2050 }
2051
2052 static void
2053 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2054 {
2055   complaint (_("invalid attribute class or form for '%s' in '%s'"),
2056              arg1, arg2);
2057 }
2058
2059 /* Hash function for line_header_hash.  */
2060
2061 static hashval_t
2062 line_header_hash (const struct line_header *ofs)
2063 {
2064   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2065 }
2066
2067 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2068
2069 static hashval_t
2070 line_header_hash_voidp (const void *item)
2071 {
2072   const struct line_header *ofs = (const struct line_header *) item;
2073
2074   return line_header_hash (ofs);
2075 }
2076
2077 /* Equality function for line_header_hash.  */
2078
2079 static int
2080 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2081 {
2082   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2083   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2084
2085   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2086           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2087 }
2088
2089 \f
2090
2091 /* Read the given attribute value as an address, taking the attribute's
2092    form into account.  */
2093
2094 static CORE_ADDR
2095 attr_value_as_address (struct attribute *attr)
2096 {
2097   CORE_ADDR addr;
2098
2099   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2100     {
2101       /* Aside from a few clearly defined exceptions, attributes that
2102          contain an address must always be in DW_FORM_addr form.
2103          Unfortunately, some compilers happen to be violating this
2104          requirement by encoding addresses using other forms, such
2105          as DW_FORM_data4 for example.  For those broken compilers,
2106          we try to do our best, without any guarantee of success,
2107          to interpret the address correctly.  It would also be nice
2108          to generate a complaint, but that would require us to maintain
2109          a list of legitimate cases where a non-address form is allowed,
2110          as well as update callers to pass in at least the CU's DWARF
2111          version.  This is more overhead than what we're willing to
2112          expand for a pretty rare case.  */
2113       addr = DW_UNSND (attr);
2114     }
2115   else
2116     addr = DW_ADDR (attr);
2117
2118   return addr;
2119 }
2120
2121 /* See declaration.  */
2122
2123 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2124                                         const dwarf2_debug_sections *names)
2125   : objfile (objfile_)
2126 {
2127   if (names == NULL)
2128     names = &dwarf2_elf_names;
2129
2130   bfd *obfd = objfile->obfd;
2131
2132   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2133     locate_sections (obfd, sec, *names);
2134 }
2135
2136 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2137
2138 dwarf2_per_objfile::~dwarf2_per_objfile ()
2139 {
2140   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2141   free_cached_comp_units ();
2142
2143   if (quick_file_names_table)
2144     htab_delete (quick_file_names_table);
2145
2146   if (line_header_hash)
2147     htab_delete (line_header_hash);
2148
2149   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2150     VEC_free (dwarf2_per_cu_ptr, per_cu->imported_symtabs);
2151
2152   for (signatured_type *sig_type : all_type_units)
2153     VEC_free (dwarf2_per_cu_ptr, sig_type->per_cu.imported_symtabs);
2154
2155   VEC_free (dwarf2_section_info_def, types);
2156
2157   if (dwo_files != NULL)
2158     free_dwo_files (dwo_files, objfile);
2159
2160   /* Everything else should be on the objfile obstack.  */
2161 }
2162
2163 /* See declaration.  */
2164
2165 void
2166 dwarf2_per_objfile::free_cached_comp_units ()
2167 {
2168   dwarf2_per_cu_data *per_cu = read_in_chain;
2169   dwarf2_per_cu_data **last_chain = &read_in_chain;
2170   while (per_cu != NULL)
2171     {
2172       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2173
2174       delete per_cu->cu;
2175       *last_chain = next_cu;
2176       per_cu = next_cu;
2177     }
2178 }
2179
2180 /* A helper class that calls free_cached_comp_units on
2181    destruction.  */
2182
2183 class free_cached_comp_units
2184 {
2185 public:
2186
2187   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2188     : m_per_objfile (per_objfile)
2189   {
2190   }
2191
2192   ~free_cached_comp_units ()
2193   {
2194     m_per_objfile->free_cached_comp_units ();
2195   }
2196
2197   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2198
2199 private:
2200
2201   dwarf2_per_objfile *m_per_objfile;
2202 };
2203
2204 /* Try to locate the sections we need for DWARF 2 debugging
2205    information and return true if we have enough to do something.
2206    NAMES points to the dwarf2 section names, or is NULL if the standard
2207    ELF names are used.  */
2208
2209 int
2210 dwarf2_has_info (struct objfile *objfile,
2211                  const struct dwarf2_debug_sections *names)
2212 {
2213   if (objfile->flags & OBJF_READNEVER)
2214     return 0;
2215
2216   struct dwarf2_per_objfile *dwarf2_per_objfile
2217     = get_dwarf2_per_objfile (objfile);
2218
2219   if (dwarf2_per_objfile == NULL)
2220     {
2221       /* Initialize per-objfile state.  */
2222       dwarf2_per_objfile
2223         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2224                                                                      names);
2225       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2226     }
2227   return (!dwarf2_per_objfile->info.is_virtual
2228           && dwarf2_per_objfile->info.s.section != NULL
2229           && !dwarf2_per_objfile->abbrev.is_virtual
2230           && dwarf2_per_objfile->abbrev.s.section != NULL);
2231 }
2232
2233 /* Return the containing section of virtual section SECTION.  */
2234
2235 static struct dwarf2_section_info *
2236 get_containing_section (const struct dwarf2_section_info *section)
2237 {
2238   gdb_assert (section->is_virtual);
2239   return section->s.containing_section;
2240 }
2241
2242 /* Return the bfd owner of SECTION.  */
2243
2244 static struct bfd *
2245 get_section_bfd_owner (const struct dwarf2_section_info *section)
2246 {
2247   if (section->is_virtual)
2248     {
2249       section = get_containing_section (section);
2250       gdb_assert (!section->is_virtual);
2251     }
2252   return section->s.section->owner;
2253 }
2254
2255 /* Return the bfd section of SECTION.
2256    Returns NULL if the section is not present.  */
2257
2258 static asection *
2259 get_section_bfd_section (const struct dwarf2_section_info *section)
2260 {
2261   if (section->is_virtual)
2262     {
2263       section = get_containing_section (section);
2264       gdb_assert (!section->is_virtual);
2265     }
2266   return section->s.section;
2267 }
2268
2269 /* Return the name of SECTION.  */
2270
2271 static const char *
2272 get_section_name (const struct dwarf2_section_info *section)
2273 {
2274   asection *sectp = get_section_bfd_section (section);
2275
2276   gdb_assert (sectp != NULL);
2277   return bfd_section_name (get_section_bfd_owner (section), sectp);
2278 }
2279
2280 /* Return the name of the file SECTION is in.  */
2281
2282 static const char *
2283 get_section_file_name (const struct dwarf2_section_info *section)
2284 {
2285   bfd *abfd = get_section_bfd_owner (section);
2286
2287   return bfd_get_filename (abfd);
2288 }
2289
2290 /* Return the id of SECTION.
2291    Returns 0 if SECTION doesn't exist.  */
2292
2293 static int
2294 get_section_id (const struct dwarf2_section_info *section)
2295 {
2296   asection *sectp = get_section_bfd_section (section);
2297
2298   if (sectp == NULL)
2299     return 0;
2300   return sectp->id;
2301 }
2302
2303 /* Return the flags of SECTION.
2304    SECTION (or containing section if this is a virtual section) must exist.  */
2305
2306 static int
2307 get_section_flags (const struct dwarf2_section_info *section)
2308 {
2309   asection *sectp = get_section_bfd_section (section);
2310
2311   gdb_assert (sectp != NULL);
2312   return bfd_get_section_flags (sectp->owner, sectp);
2313 }
2314
2315 /* When loading sections, we look either for uncompressed section or for
2316    compressed section names.  */
2317
2318 static int
2319 section_is_p (const char *section_name,
2320               const struct dwarf2_section_names *names)
2321 {
2322   if (names->normal != NULL
2323       && strcmp (section_name, names->normal) == 0)
2324     return 1;
2325   if (names->compressed != NULL
2326       && strcmp (section_name, names->compressed) == 0)
2327     return 1;
2328   return 0;
2329 }
2330
2331 /* See declaration.  */
2332
2333 void
2334 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2335                                      const dwarf2_debug_sections &names)
2336 {
2337   flagword aflag = bfd_get_section_flags (abfd, sectp);
2338
2339   if ((aflag & SEC_HAS_CONTENTS) == 0)
2340     {
2341     }
2342   else if (section_is_p (sectp->name, &names.info))
2343     {
2344       this->info.s.section = sectp;
2345       this->info.size = bfd_get_section_size (sectp);
2346     }
2347   else if (section_is_p (sectp->name, &names.abbrev))
2348     {
2349       this->abbrev.s.section = sectp;
2350       this->abbrev.size = bfd_get_section_size (sectp);
2351     }
2352   else if (section_is_p (sectp->name, &names.line))
2353     {
2354       this->line.s.section = sectp;
2355       this->line.size = bfd_get_section_size (sectp);
2356     }
2357   else if (section_is_p (sectp->name, &names.loc))
2358     {
2359       this->loc.s.section = sectp;
2360       this->loc.size = bfd_get_section_size (sectp);
2361     }
2362   else if (section_is_p (sectp->name, &names.loclists))
2363     {
2364       this->loclists.s.section = sectp;
2365       this->loclists.size = bfd_get_section_size (sectp);
2366     }
2367   else if (section_is_p (sectp->name, &names.macinfo))
2368     {
2369       this->macinfo.s.section = sectp;
2370       this->macinfo.size = bfd_get_section_size (sectp);
2371     }
2372   else if (section_is_p (sectp->name, &names.macro))
2373     {
2374       this->macro.s.section = sectp;
2375       this->macro.size = bfd_get_section_size (sectp);
2376     }
2377   else if (section_is_p (sectp->name, &names.str))
2378     {
2379       this->str.s.section = sectp;
2380       this->str.size = bfd_get_section_size (sectp);
2381     }
2382   else if (section_is_p (sectp->name, &names.line_str))
2383     {
2384       this->line_str.s.section = sectp;
2385       this->line_str.size = bfd_get_section_size (sectp);
2386     }
2387   else if (section_is_p (sectp->name, &names.addr))
2388     {
2389       this->addr.s.section = sectp;
2390       this->addr.size = bfd_get_section_size (sectp);
2391     }
2392   else if (section_is_p (sectp->name, &names.frame))
2393     {
2394       this->frame.s.section = sectp;
2395       this->frame.size = bfd_get_section_size (sectp);
2396     }
2397   else if (section_is_p (sectp->name, &names.eh_frame))
2398     {
2399       this->eh_frame.s.section = sectp;
2400       this->eh_frame.size = bfd_get_section_size (sectp);
2401     }
2402   else if (section_is_p (sectp->name, &names.ranges))
2403     {
2404       this->ranges.s.section = sectp;
2405       this->ranges.size = bfd_get_section_size (sectp);
2406     }
2407   else if (section_is_p (sectp->name, &names.rnglists))
2408     {
2409       this->rnglists.s.section = sectp;
2410       this->rnglists.size = bfd_get_section_size (sectp);
2411     }
2412   else if (section_is_p (sectp->name, &names.types))
2413     {
2414       struct dwarf2_section_info type_section;
2415
2416       memset (&type_section, 0, sizeof (type_section));
2417       type_section.s.section = sectp;
2418       type_section.size = bfd_get_section_size (sectp);
2419
2420       VEC_safe_push (dwarf2_section_info_def, this->types,
2421                      &type_section);
2422     }
2423   else if (section_is_p (sectp->name, &names.gdb_index))
2424     {
2425       this->gdb_index.s.section = sectp;
2426       this->gdb_index.size = bfd_get_section_size (sectp);
2427     }
2428   else if (section_is_p (sectp->name, &names.debug_names))
2429     {
2430       this->debug_names.s.section = sectp;
2431       this->debug_names.size = bfd_get_section_size (sectp);
2432     }
2433   else if (section_is_p (sectp->name, &names.debug_aranges))
2434     {
2435       this->debug_aranges.s.section = sectp;
2436       this->debug_aranges.size = bfd_get_section_size (sectp);
2437     }
2438
2439   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2440       && bfd_section_vma (abfd, sectp) == 0)
2441     this->has_section_at_zero = true;
2442 }
2443
2444 /* A helper function that decides whether a section is empty,
2445    or not present.  */
2446
2447 static int
2448 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2449 {
2450   if (section->is_virtual)
2451     return section->size == 0;
2452   return section->s.section == NULL || section->size == 0;
2453 }
2454
2455 /* See dwarf2read.h.  */
2456
2457 void
2458 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2459 {
2460   asection *sectp;
2461   bfd *abfd;
2462   gdb_byte *buf, *retbuf;
2463
2464   if (info->readin)
2465     return;
2466   info->buffer = NULL;
2467   info->readin = 1;
2468
2469   if (dwarf2_section_empty_p (info))
2470     return;
2471
2472   sectp = get_section_bfd_section (info);
2473
2474   /* If this is a virtual section we need to read in the real one first.  */
2475   if (info->is_virtual)
2476     {
2477       struct dwarf2_section_info *containing_section =
2478         get_containing_section (info);
2479
2480       gdb_assert (sectp != NULL);
2481       if ((sectp->flags & SEC_RELOC) != 0)
2482         {
2483           error (_("Dwarf Error: DWP format V2 with relocations is not"
2484                    " supported in section %s [in module %s]"),
2485                  get_section_name (info), get_section_file_name (info));
2486         }
2487       dwarf2_read_section (objfile, containing_section);
2488       /* Other code should have already caught virtual sections that don't
2489          fit.  */
2490       gdb_assert (info->virtual_offset + info->size
2491                   <= containing_section->size);
2492       /* If the real section is empty or there was a problem reading the
2493          section we shouldn't get here.  */
2494       gdb_assert (containing_section->buffer != NULL);
2495       info->buffer = containing_section->buffer + info->virtual_offset;
2496       return;
2497     }
2498
2499   /* If the section has relocations, we must read it ourselves.
2500      Otherwise we attach it to the BFD.  */
2501   if ((sectp->flags & SEC_RELOC) == 0)
2502     {
2503       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2504       return;
2505     }
2506
2507   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2508   info->buffer = buf;
2509
2510   /* When debugging .o files, we may need to apply relocations; see
2511      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2512      We never compress sections in .o files, so we only need to
2513      try this when the section is not compressed.  */
2514   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2515   if (retbuf != NULL)
2516     {
2517       info->buffer = retbuf;
2518       return;
2519     }
2520
2521   abfd = get_section_bfd_owner (info);
2522   gdb_assert (abfd != NULL);
2523
2524   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2525       || bfd_bread (buf, info->size, abfd) != info->size)
2526     {
2527       error (_("Dwarf Error: Can't read DWARF data"
2528                " in section %s [in module %s]"),
2529              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2530     }
2531 }
2532
2533 /* A helper function that returns the size of a section in a safe way.
2534    If you are positive that the section has been read before using the
2535    size, then it is safe to refer to the dwarf2_section_info object's
2536    "size" field directly.  In other cases, you must call this
2537    function, because for compressed sections the size field is not set
2538    correctly until the section has been read.  */
2539
2540 static bfd_size_type
2541 dwarf2_section_size (struct objfile *objfile,
2542                      struct dwarf2_section_info *info)
2543 {
2544   if (!info->readin)
2545     dwarf2_read_section (objfile, info);
2546   return info->size;
2547 }
2548
2549 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2550    SECTION_NAME.  */
2551
2552 void
2553 dwarf2_get_section_info (struct objfile *objfile,
2554                          enum dwarf2_section_enum sect,
2555                          asection **sectp, const gdb_byte **bufp,
2556                          bfd_size_type *sizep)
2557 {
2558   struct dwarf2_per_objfile *data
2559     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2560                                                   dwarf2_objfile_data_key);
2561   struct dwarf2_section_info *info;
2562
2563   /* We may see an objfile without any DWARF, in which case we just
2564      return nothing.  */
2565   if (data == NULL)
2566     {
2567       *sectp = NULL;
2568       *bufp = NULL;
2569       *sizep = 0;
2570       return;
2571     }
2572   switch (sect)
2573     {
2574     case DWARF2_DEBUG_FRAME:
2575       info = &data->frame;
2576       break;
2577     case DWARF2_EH_FRAME:
2578       info = &data->eh_frame;
2579       break;
2580     default:
2581       gdb_assert_not_reached ("unexpected section");
2582     }
2583
2584   dwarf2_read_section (objfile, info);
2585
2586   *sectp = get_section_bfd_section (info);
2587   *bufp = info->buffer;
2588   *sizep = info->size;
2589 }
2590
2591 /* A helper function to find the sections for a .dwz file.  */
2592
2593 static void
2594 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2595 {
2596   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2597
2598   /* Note that we only support the standard ELF names, because .dwz
2599      is ELF-only (at the time of writing).  */
2600   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2601     {
2602       dwz_file->abbrev.s.section = sectp;
2603       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2604     }
2605   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2606     {
2607       dwz_file->info.s.section = sectp;
2608       dwz_file->info.size = bfd_get_section_size (sectp);
2609     }
2610   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2611     {
2612       dwz_file->str.s.section = sectp;
2613       dwz_file->str.size = bfd_get_section_size (sectp);
2614     }
2615   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2616     {
2617       dwz_file->line.s.section = sectp;
2618       dwz_file->line.size = bfd_get_section_size (sectp);
2619     }
2620   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2621     {
2622       dwz_file->macro.s.section = sectp;
2623       dwz_file->macro.size = bfd_get_section_size (sectp);
2624     }
2625   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2626     {
2627       dwz_file->gdb_index.s.section = sectp;
2628       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2629     }
2630   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2631     {
2632       dwz_file->debug_names.s.section = sectp;
2633       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2634     }
2635 }
2636
2637 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2638    there is no .gnu_debugaltlink section in the file.  Error if there
2639    is such a section but the file cannot be found.  */
2640
2641 static struct dwz_file *
2642 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2643 {
2644   const char *filename;
2645   bfd_size_type buildid_len_arg;
2646   size_t buildid_len;
2647   bfd_byte *buildid;
2648
2649   if (dwarf2_per_objfile->dwz_file != NULL)
2650     return dwarf2_per_objfile->dwz_file.get ();
2651
2652   bfd_set_error (bfd_error_no_error);
2653   gdb::unique_xmalloc_ptr<char> data
2654     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2655                                   &buildid_len_arg, &buildid));
2656   if (data == NULL)
2657     {
2658       if (bfd_get_error () == bfd_error_no_error)
2659         return NULL;
2660       error (_("could not read '.gnu_debugaltlink' section: %s"),
2661              bfd_errmsg (bfd_get_error ()));
2662     }
2663
2664   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2665
2666   buildid_len = (size_t) buildid_len_arg;
2667
2668   filename = data.get ();
2669
2670   std::string abs_storage;
2671   if (!IS_ABSOLUTE_PATH (filename))
2672     {
2673       gdb::unique_xmalloc_ptr<char> abs
2674         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2675
2676       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2677       filename = abs_storage.c_str ();
2678     }
2679
2680   /* First try the file name given in the section.  If that doesn't
2681      work, try to use the build-id instead.  */
2682   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2683   if (dwz_bfd != NULL)
2684     {
2685       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2686         dwz_bfd.release ();
2687     }
2688
2689   if (dwz_bfd == NULL)
2690     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2691
2692   if (dwz_bfd == NULL)
2693     error (_("could not find '.gnu_debugaltlink' file for %s"),
2694            objfile_name (dwarf2_per_objfile->objfile));
2695
2696   std::unique_ptr<struct dwz_file> result
2697     (new struct dwz_file (std::move (dwz_bfd)));
2698
2699   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2700                          result.get ());
2701
2702   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2703                             result->dwz_bfd.get ());
2704   dwarf2_per_objfile->dwz_file = std::move (result);
2705   return dwarf2_per_objfile->dwz_file.get ();
2706 }
2707 \f
2708 /* DWARF quick_symbols_functions support.  */
2709
2710 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2711    unique line tables, so we maintain a separate table of all .debug_line
2712    derived entries to support the sharing.
2713    All the quick functions need is the list of file names.  We discard the
2714    line_header when we're done and don't need to record it here.  */
2715 struct quick_file_names
2716 {
2717   /* The data used to construct the hash key.  */
2718   struct stmt_list_hash hash;
2719
2720   /* The number of entries in file_names, real_names.  */
2721   unsigned int num_file_names;
2722
2723   /* The file names from the line table, after being run through
2724      file_full_name.  */
2725   const char **file_names;
2726
2727   /* The file names from the line table after being run through
2728      gdb_realpath.  These are computed lazily.  */
2729   const char **real_names;
2730 };
2731
2732 /* When using the index (and thus not using psymtabs), each CU has an
2733    object of this type.  This is used to hold information needed by
2734    the various "quick" methods.  */
2735 struct dwarf2_per_cu_quick_data
2736 {
2737   /* The file table.  This can be NULL if there was no file table
2738      or it's currently not read in.
2739      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2740   struct quick_file_names *file_names;
2741
2742   /* The corresponding symbol table.  This is NULL if symbols for this
2743      CU have not yet been read.  */
2744   struct compunit_symtab *compunit_symtab;
2745
2746   /* A temporary mark bit used when iterating over all CUs in
2747      expand_symtabs_matching.  */
2748   unsigned int mark : 1;
2749
2750   /* True if we've tried to read the file table and found there isn't one.
2751      There will be no point in trying to read it again next time.  */
2752   unsigned int no_file_data : 1;
2753 };
2754
2755 /* Utility hash function for a stmt_list_hash.  */
2756
2757 static hashval_t
2758 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2759 {
2760   hashval_t v = 0;
2761
2762   if (stmt_list_hash->dwo_unit != NULL)
2763     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2764   v += to_underlying (stmt_list_hash->line_sect_off);
2765   return v;
2766 }
2767
2768 /* Utility equality function for a stmt_list_hash.  */
2769
2770 static int
2771 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2772                     const struct stmt_list_hash *rhs)
2773 {
2774   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2775     return 0;
2776   if (lhs->dwo_unit != NULL
2777       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2778     return 0;
2779
2780   return lhs->line_sect_off == rhs->line_sect_off;
2781 }
2782
2783 /* Hash function for a quick_file_names.  */
2784
2785 static hashval_t
2786 hash_file_name_entry (const void *e)
2787 {
2788   const struct quick_file_names *file_data
2789     = (const struct quick_file_names *) e;
2790
2791   return hash_stmt_list_entry (&file_data->hash);
2792 }
2793
2794 /* Equality function for a quick_file_names.  */
2795
2796 static int
2797 eq_file_name_entry (const void *a, const void *b)
2798 {
2799   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2800   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2801
2802   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2803 }
2804
2805 /* Delete function for a quick_file_names.  */
2806
2807 static void
2808 delete_file_name_entry (void *e)
2809 {
2810   struct quick_file_names *file_data = (struct quick_file_names *) e;
2811   int i;
2812
2813   for (i = 0; i < file_data->num_file_names; ++i)
2814     {
2815       xfree ((void*) file_data->file_names[i]);
2816       if (file_data->real_names)
2817         xfree ((void*) file_data->real_names[i]);
2818     }
2819
2820   /* The space for the struct itself lives on objfile_obstack,
2821      so we don't free it here.  */
2822 }
2823
2824 /* Create a quick_file_names hash table.  */
2825
2826 static htab_t
2827 create_quick_file_names_table (unsigned int nr_initial_entries)
2828 {
2829   return htab_create_alloc (nr_initial_entries,
2830                             hash_file_name_entry, eq_file_name_entry,
2831                             delete_file_name_entry, xcalloc, xfree);
2832 }
2833
2834 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2835    have to be created afterwards.  You should call age_cached_comp_units after
2836    processing PER_CU->CU.  dw2_setup must have been already called.  */
2837
2838 static void
2839 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2840 {
2841   if (per_cu->is_debug_types)
2842     load_full_type_unit (per_cu);
2843   else
2844     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2845
2846   if (per_cu->cu == NULL)
2847     return;  /* Dummy CU.  */
2848
2849   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2850 }
2851
2852 /* Read in the symbols for PER_CU.  */
2853
2854 static void
2855 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2856 {
2857   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2858
2859   /* Skip type_unit_groups, reading the type units they contain
2860      is handled elsewhere.  */
2861   if (IS_TYPE_UNIT_GROUP (per_cu))
2862     return;
2863
2864   /* The destructor of dwarf2_queue_guard frees any entries left on
2865      the queue.  After this point we're guaranteed to leave this function
2866      with the dwarf queue empty.  */
2867   dwarf2_queue_guard q_guard;
2868
2869   if (dwarf2_per_objfile->using_index
2870       ? per_cu->v.quick->compunit_symtab == NULL
2871       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2872     {
2873       queue_comp_unit (per_cu, language_minimal);
2874       load_cu (per_cu, skip_partial);
2875
2876       /* If we just loaded a CU from a DWO, and we're working with an index
2877          that may badly handle TUs, load all the TUs in that DWO as well.
2878          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2879       if (!per_cu->is_debug_types
2880           && per_cu->cu != NULL
2881           && per_cu->cu->dwo_unit != NULL
2882           && dwarf2_per_objfile->index_table != NULL
2883           && dwarf2_per_objfile->index_table->version <= 7
2884           /* DWP files aren't supported yet.  */
2885           && get_dwp_file (dwarf2_per_objfile) == NULL)
2886         queue_and_load_all_dwo_tus (per_cu);
2887     }
2888
2889   process_queue (dwarf2_per_objfile);
2890
2891   /* Age the cache, releasing compilation units that have not
2892      been used recently.  */
2893   age_cached_comp_units (dwarf2_per_objfile);
2894 }
2895
2896 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2897    the objfile from which this CU came.  Returns the resulting symbol
2898    table.  */
2899
2900 static struct compunit_symtab *
2901 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2902 {
2903   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2904
2905   gdb_assert (dwarf2_per_objfile->using_index);
2906   if (!per_cu->v.quick->compunit_symtab)
2907     {
2908       free_cached_comp_units freer (dwarf2_per_objfile);
2909       scoped_restore decrementer = increment_reading_symtab ();
2910       dw2_do_instantiate_symtab (per_cu, skip_partial);
2911       process_cu_includes (dwarf2_per_objfile);
2912     }
2913
2914   return per_cu->v.quick->compunit_symtab;
2915 }
2916
2917 /* See declaration.  */
2918
2919 dwarf2_per_cu_data *
2920 dwarf2_per_objfile::get_cutu (int index)
2921 {
2922   if (index >= this->all_comp_units.size ())
2923     {
2924       index -= this->all_comp_units.size ();
2925       gdb_assert (index < this->all_type_units.size ());
2926       return &this->all_type_units[index]->per_cu;
2927     }
2928
2929   return this->all_comp_units[index];
2930 }
2931
2932 /* See declaration.  */
2933
2934 dwarf2_per_cu_data *
2935 dwarf2_per_objfile::get_cu (int index)
2936 {
2937   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2938
2939   return this->all_comp_units[index];
2940 }
2941
2942 /* See declaration.  */
2943
2944 signatured_type *
2945 dwarf2_per_objfile::get_tu (int index)
2946 {
2947   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2948
2949   return this->all_type_units[index];
2950 }
2951
2952 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2953    objfile_obstack, and constructed with the specified field
2954    values.  */
2955
2956 static dwarf2_per_cu_data *
2957 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2958                           struct dwarf2_section_info *section,
2959                           int is_dwz,
2960                           sect_offset sect_off, ULONGEST length)
2961 {
2962   struct objfile *objfile = dwarf2_per_objfile->objfile;
2963   dwarf2_per_cu_data *the_cu
2964     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2965                      struct dwarf2_per_cu_data);
2966   the_cu->sect_off = sect_off;
2967   the_cu->length = length;
2968   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2969   the_cu->section = section;
2970   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2971                                    struct dwarf2_per_cu_quick_data);
2972   the_cu->is_dwz = is_dwz;
2973   return the_cu;
2974 }
2975
2976 /* A helper for create_cus_from_index that handles a given list of
2977    CUs.  */
2978
2979 static void
2980 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2981                             const gdb_byte *cu_list, offset_type n_elements,
2982                             struct dwarf2_section_info *section,
2983                             int is_dwz)
2984 {
2985   for (offset_type i = 0; i < n_elements; i += 2)
2986     {
2987       gdb_static_assert (sizeof (ULONGEST) >= 8);
2988
2989       sect_offset sect_off
2990         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2991       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2992       cu_list += 2 * 8;
2993
2994       dwarf2_per_cu_data *per_cu
2995         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2996                                      sect_off, length);
2997       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
2998     }
2999 }
3000
3001 /* Read the CU list from the mapped index, and use it to create all
3002    the CU objects for this objfile.  */
3003
3004 static void
3005 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3006                        const gdb_byte *cu_list, offset_type cu_list_elements,
3007                        const gdb_byte *dwz_list, offset_type dwz_elements)
3008 {
3009   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
3010   dwarf2_per_objfile->all_comp_units.reserve
3011     ((cu_list_elements + dwz_elements) / 2);
3012
3013   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
3014                               &dwarf2_per_objfile->info, 0);
3015
3016   if (dwz_elements == 0)
3017     return;
3018
3019   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3020   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
3021                               &dwz->info, 1);
3022 }
3023
3024 /* Create the signatured type hash table from the index.  */
3025
3026 static void
3027 create_signatured_type_table_from_index
3028   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3029    struct dwarf2_section_info *section,
3030    const gdb_byte *bytes,
3031    offset_type elements)
3032 {
3033   struct objfile *objfile = dwarf2_per_objfile->objfile;
3034
3035   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3036   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
3037
3038   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3039
3040   for (offset_type i = 0; i < elements; i += 3)
3041     {
3042       struct signatured_type *sig_type;
3043       ULONGEST signature;
3044       void **slot;
3045       cu_offset type_offset_in_tu;
3046
3047       gdb_static_assert (sizeof (ULONGEST) >= 8);
3048       sect_offset sect_off
3049         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3050       type_offset_in_tu
3051         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3052                                                 BFD_ENDIAN_LITTLE);
3053       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3054       bytes += 3 * 8;
3055
3056       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3057                                  struct signatured_type);
3058       sig_type->signature = signature;
3059       sig_type->type_offset_in_tu = type_offset_in_tu;
3060       sig_type->per_cu.is_debug_types = 1;
3061       sig_type->per_cu.section = section;
3062       sig_type->per_cu.sect_off = sect_off;
3063       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3064       sig_type->per_cu.v.quick
3065         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3066                           struct dwarf2_per_cu_quick_data);
3067
3068       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3069       *slot = sig_type;
3070
3071       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3072     }
3073
3074   dwarf2_per_objfile->signatured_types = sig_types_hash;
3075 }
3076
3077 /* Create the signatured type hash table from .debug_names.  */
3078
3079 static void
3080 create_signatured_type_table_from_debug_names
3081   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3082    const mapped_debug_names &map,
3083    struct dwarf2_section_info *section,
3084    struct dwarf2_section_info *abbrev_section)
3085 {
3086   struct objfile *objfile = dwarf2_per_objfile->objfile;
3087
3088   dwarf2_read_section (objfile, section);
3089   dwarf2_read_section (objfile, abbrev_section);
3090
3091   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3092   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
3093
3094   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3095
3096   for (uint32_t i = 0; i < map.tu_count; ++i)
3097     {
3098       struct signatured_type *sig_type;
3099       void **slot;
3100
3101       sect_offset sect_off
3102         = (sect_offset) (extract_unsigned_integer
3103                          (map.tu_table_reordered + i * map.offset_size,
3104                           map.offset_size,
3105                           map.dwarf5_byte_order));
3106
3107       comp_unit_head cu_header;
3108       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3109                                      abbrev_section,
3110                                      section->buffer + to_underlying (sect_off),
3111                                      rcuh_kind::TYPE);
3112
3113       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3114                                  struct signatured_type);
3115       sig_type->signature = cu_header.signature;
3116       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3117       sig_type->per_cu.is_debug_types = 1;
3118       sig_type->per_cu.section = section;
3119       sig_type->per_cu.sect_off = sect_off;
3120       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3121       sig_type->per_cu.v.quick
3122         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3123                           struct dwarf2_per_cu_quick_data);
3124
3125       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3126       *slot = sig_type;
3127
3128       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3129     }
3130
3131   dwarf2_per_objfile->signatured_types = sig_types_hash;
3132 }
3133
3134 /* Read the address map data from the mapped index, and use it to
3135    populate the objfile's psymtabs_addrmap.  */
3136
3137 static void
3138 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3139                            struct mapped_index *index)
3140 {
3141   struct objfile *objfile = dwarf2_per_objfile->objfile;
3142   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3143   const gdb_byte *iter, *end;
3144   struct addrmap *mutable_map;
3145   CORE_ADDR baseaddr;
3146
3147   auto_obstack temp_obstack;
3148
3149   mutable_map = addrmap_create_mutable (&temp_obstack);
3150
3151   iter = index->address_table.data ();
3152   end = iter + index->address_table.size ();
3153
3154   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3155
3156   while (iter < end)
3157     {
3158       ULONGEST hi, lo, cu_index;
3159       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3160       iter += 8;
3161       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3162       iter += 8;
3163       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3164       iter += 4;
3165
3166       if (lo > hi)
3167         {
3168           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
3169                      hex_string (lo), hex_string (hi));
3170           continue;
3171         }
3172
3173       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
3174         {
3175           complaint (_(".gdb_index address table has invalid CU number %u"),
3176                      (unsigned) cu_index);
3177           continue;
3178         }
3179
3180       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3181       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3182       addrmap_set_empty (mutable_map, lo, hi - 1,
3183                          dwarf2_per_objfile->get_cu (cu_index));
3184     }
3185
3186   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3187                                                     &objfile->objfile_obstack);
3188 }
3189
3190 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3191    populate the objfile's psymtabs_addrmap.  */
3192
3193 static void
3194 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3195                              struct dwarf2_section_info *section)
3196 {
3197   struct objfile *objfile = dwarf2_per_objfile->objfile;
3198   bfd *abfd = objfile->obfd;
3199   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3200   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3201                                        SECT_OFF_TEXT (objfile));
3202
3203   auto_obstack temp_obstack;
3204   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3205
3206   std::unordered_map<sect_offset,
3207                      dwarf2_per_cu_data *,
3208                      gdb::hash_enum<sect_offset>>
3209     debug_info_offset_to_per_cu;
3210   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3211     {
3212       const auto insertpair
3213         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3214       if (!insertpair.second)
3215         {
3216           warning (_("Section .debug_aranges in %s has duplicate "
3217                      "debug_info_offset %s, ignoring .debug_aranges."),
3218                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3219           return;
3220         }
3221     }
3222
3223   dwarf2_read_section (objfile, section);
3224
3225   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3226
3227   const gdb_byte *addr = section->buffer;
3228
3229   while (addr < section->buffer + section->size)
3230     {
3231       const gdb_byte *const entry_addr = addr;
3232       unsigned int bytes_read;
3233
3234       const LONGEST entry_length = read_initial_length (abfd, addr,
3235                                                         &bytes_read);
3236       addr += bytes_read;
3237
3238       const gdb_byte *const entry_end = addr + entry_length;
3239       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3240       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3241       if (addr + entry_length > section->buffer + section->size)
3242         {
3243           warning (_("Section .debug_aranges in %s entry at offset %zu "
3244                      "length %s exceeds section length %s, "
3245                      "ignoring .debug_aranges."),
3246                    objfile_name (objfile), entry_addr - section->buffer,
3247                    plongest (bytes_read + entry_length),
3248                    pulongest (section->size));
3249           return;
3250         }
3251
3252       /* The version number.  */
3253       const uint16_t version = read_2_bytes (abfd, addr);
3254       addr += 2;
3255       if (version != 2)
3256         {
3257           warning (_("Section .debug_aranges in %s entry at offset %zu "
3258                      "has unsupported version %d, ignoring .debug_aranges."),
3259                    objfile_name (objfile), entry_addr - section->buffer,
3260                    version);
3261           return;
3262         }
3263
3264       const uint64_t debug_info_offset
3265         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3266       addr += offset_size;
3267       const auto per_cu_it
3268         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3269       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3270         {
3271           warning (_("Section .debug_aranges in %s entry at offset %zu "
3272                      "debug_info_offset %s does not exists, "
3273                      "ignoring .debug_aranges."),
3274                    objfile_name (objfile), entry_addr - section->buffer,
3275                    pulongest (debug_info_offset));
3276           return;
3277         }
3278       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3279
3280       const uint8_t address_size = *addr++;
3281       if (address_size < 1 || address_size > 8)
3282         {
3283           warning (_("Section .debug_aranges in %s entry at offset %zu "
3284                      "address_size %u is invalid, ignoring .debug_aranges."),
3285                    objfile_name (objfile), entry_addr - section->buffer,
3286                    address_size);
3287           return;
3288         }
3289
3290       const uint8_t segment_selector_size = *addr++;
3291       if (segment_selector_size != 0)
3292         {
3293           warning (_("Section .debug_aranges in %s entry at offset %zu "
3294                      "segment_selector_size %u is not supported, "
3295                      "ignoring .debug_aranges."),
3296                    objfile_name (objfile), entry_addr - section->buffer,
3297                    segment_selector_size);
3298           return;
3299         }
3300
3301       /* Must pad to an alignment boundary that is twice the address
3302          size.  It is undocumented by the DWARF standard but GCC does
3303          use it.  */
3304       for (size_t padding = ((-(addr - section->buffer))
3305                              & (2 * address_size - 1));
3306            padding > 0; padding--)
3307         if (*addr++ != 0)
3308           {
3309             warning (_("Section .debug_aranges in %s entry at offset %zu "
3310                        "padding is not zero, ignoring .debug_aranges."),
3311                      objfile_name (objfile), entry_addr - section->buffer);
3312             return;
3313           }
3314
3315       for (;;)
3316         {
3317           if (addr + 2 * address_size > entry_end)
3318             {
3319               warning (_("Section .debug_aranges in %s entry at offset %zu "
3320                          "address list is not properly terminated, "
3321                          "ignoring .debug_aranges."),
3322                        objfile_name (objfile), entry_addr - section->buffer);
3323               return;
3324             }
3325           ULONGEST start = extract_unsigned_integer (addr, address_size,
3326                                                      dwarf5_byte_order);
3327           addr += address_size;
3328           ULONGEST length = extract_unsigned_integer (addr, address_size,
3329                                                       dwarf5_byte_order);
3330           addr += address_size;
3331           if (start == 0 && length == 0)
3332             break;
3333           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3334             {
3335               /* Symbol was eliminated due to a COMDAT group.  */
3336               continue;
3337             }
3338           ULONGEST end = start + length;
3339           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3340           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3341           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3342         }
3343     }
3344
3345   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3346                                                     &objfile->objfile_obstack);
3347 }
3348
3349 /* Find a slot in the mapped index INDEX for the object named NAME.
3350    If NAME is found, set *VEC_OUT to point to the CU vector in the
3351    constant pool and return true.  If NAME cannot be found, return
3352    false.  */
3353
3354 static bool
3355 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3356                           offset_type **vec_out)
3357 {
3358   offset_type hash;
3359   offset_type slot, step;
3360   int (*cmp) (const char *, const char *);
3361
3362   gdb::unique_xmalloc_ptr<char> without_params;
3363   if (current_language->la_language == language_cplus
3364       || current_language->la_language == language_fortran
3365       || current_language->la_language == language_d)
3366     {
3367       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3368          not contain any.  */
3369
3370       if (strchr (name, '(') != NULL)
3371         {
3372           without_params = cp_remove_params (name);
3373
3374           if (without_params != NULL)
3375             name = without_params.get ();
3376         }
3377     }
3378
3379   /* Index version 4 did not support case insensitive searches.  But the
3380      indices for case insensitive languages are built in lowercase, therefore
3381      simulate our NAME being searched is also lowercased.  */
3382   hash = mapped_index_string_hash ((index->version == 4
3383                                     && case_sensitivity == case_sensitive_off
3384                                     ? 5 : index->version),
3385                                    name);
3386
3387   slot = hash & (index->symbol_table.size () - 1);
3388   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3389   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3390
3391   for (;;)
3392     {
3393       const char *str;
3394
3395       const auto &bucket = index->symbol_table[slot];
3396       if (bucket.name == 0 && bucket.vec == 0)
3397         return false;
3398
3399       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3400       if (!cmp (name, str))
3401         {
3402           *vec_out = (offset_type *) (index->constant_pool
3403                                       + MAYBE_SWAP (bucket.vec));
3404           return true;
3405         }
3406
3407       slot = (slot + step) & (index->symbol_table.size () - 1);
3408     }
3409 }
3410
3411 /* A helper function that reads the .gdb_index from SECTION and fills
3412    in MAP.  FILENAME is the name of the file containing the section;
3413    it is used for error reporting.  DEPRECATED_OK is true if it is
3414    ok to use deprecated sections.
3415
3416    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3417    out parameters that are filled in with information about the CU and
3418    TU lists in the section.
3419
3420    Returns 1 if all went well, 0 otherwise.  */
3421
3422 static bool
3423 read_gdb_index_from_section (struct objfile *objfile,
3424                              const char *filename,
3425                              bool deprecated_ok,
3426                              struct dwarf2_section_info *section,
3427                              struct mapped_index *map,
3428                              const gdb_byte **cu_list,
3429                              offset_type *cu_list_elements,
3430                              const gdb_byte **types_list,
3431                              offset_type *types_list_elements)
3432 {
3433   const gdb_byte *addr;
3434   offset_type version;
3435   offset_type *metadata;
3436   int i;
3437
3438   if (dwarf2_section_empty_p (section))
3439     return 0;
3440
3441   /* Older elfutils strip versions could keep the section in the main
3442      executable while splitting it for the separate debug info file.  */
3443   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3444     return 0;
3445
3446   dwarf2_read_section (objfile, section);
3447
3448   addr = section->buffer;
3449   /* Version check.  */
3450   version = MAYBE_SWAP (*(offset_type *) addr);
3451   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3452      causes the index to behave very poorly for certain requests.  Version 3
3453      contained incomplete addrmap.  So, it seems better to just ignore such
3454      indices.  */
3455   if (version < 4)
3456     {
3457       static int warning_printed = 0;
3458       if (!warning_printed)
3459         {
3460           warning (_("Skipping obsolete .gdb_index section in %s."),
3461                    filename);
3462           warning_printed = 1;
3463         }
3464       return 0;
3465     }
3466   /* Index version 4 uses a different hash function than index version
3467      5 and later.
3468
3469      Versions earlier than 6 did not emit psymbols for inlined
3470      functions.  Using these files will cause GDB not to be able to
3471      set breakpoints on inlined functions by name, so we ignore these
3472      indices unless the user has done
3473      "set use-deprecated-index-sections on".  */
3474   if (version < 6 && !deprecated_ok)
3475     {
3476       static int warning_printed = 0;
3477       if (!warning_printed)
3478         {
3479           warning (_("\
3480 Skipping deprecated .gdb_index section in %s.\n\
3481 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3482 to use the section anyway."),
3483                    filename);
3484           warning_printed = 1;
3485         }
3486       return 0;
3487     }
3488   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3489      of the TU (for symbols coming from TUs),
3490      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3491      Plus gold-generated indices can have duplicate entries for global symbols,
3492      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3493      These are just performance bugs, and we can't distinguish gdb-generated
3494      indices from gold-generated ones, so issue no warning here.  */
3495
3496   /* Indexes with higher version than the one supported by GDB may be no
3497      longer backward compatible.  */
3498   if (version > 8)
3499     return 0;
3500
3501   map->version = version;
3502
3503   metadata = (offset_type *) (addr + sizeof (offset_type));
3504
3505   i = 0;
3506   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3507   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3508                        / 8);
3509   ++i;
3510
3511   *types_list = addr + MAYBE_SWAP (metadata[i]);
3512   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3513                            - MAYBE_SWAP (metadata[i]))
3514                           / 8);
3515   ++i;
3516
3517   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3518   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3519   map->address_table
3520     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3521   ++i;
3522
3523   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3524   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3525   map->symbol_table
3526     = gdb::array_view<mapped_index::symbol_table_slot>
3527        ((mapped_index::symbol_table_slot *) symbol_table,
3528         (mapped_index::symbol_table_slot *) symbol_table_end);
3529
3530   ++i;
3531   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3532
3533   return 1;
3534 }
3535
3536 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3537    elements of all the CUs and return 1.  Otherwise, return 0.  */
3538
3539 static int
3540 dwarf2_read_gdb_index (struct dwarf2_per_objfile *dwarf2_per_objfile)
3541 {
3542   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3543   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3544   struct dwz_file *dwz;
3545   struct objfile *objfile = dwarf2_per_objfile->objfile;
3546
3547   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3548   if (!read_gdb_index_from_section (objfile, objfile_name (objfile),
3549                                     use_deprecated_index_sections,
3550                                     &dwarf2_per_objfile->gdb_index, map.get (),
3551                                     &cu_list, &cu_list_elements,
3552                                     &types_list, &types_list_elements))
3553     return 0;
3554
3555   /* Don't use the index if it's empty.  */
3556   if (map->symbol_table.empty ())
3557     return 0;
3558
3559   /* If there is a .dwz file, read it so we can get its CU list as
3560      well.  */
3561   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3562   if (dwz != NULL)
3563     {
3564       struct mapped_index dwz_map;
3565       const gdb_byte *dwz_types_ignore;
3566       offset_type dwz_types_elements_ignore;
3567
3568       if (!read_gdb_index_from_section (objfile,
3569                                         bfd_get_filename (dwz->dwz_bfd), 1,
3570                                         &dwz->gdb_index, &dwz_map,
3571                                         &dwz_list, &dwz_list_elements,
3572                                         &dwz_types_ignore,
3573                                         &dwz_types_elements_ignore))
3574         {
3575           warning (_("could not read '.gdb_index' section from %s; skipping"),
3576                    bfd_get_filename (dwz->dwz_bfd));
3577           return 0;
3578         }
3579     }
3580
3581   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3582                          dwz_list, dwz_list_elements);
3583
3584   if (types_list_elements)
3585     {
3586       struct dwarf2_section_info *section;
3587
3588       /* We can only handle a single .debug_types when we have an
3589          index.  */
3590       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3591         return 0;
3592
3593       section = VEC_index (dwarf2_section_info_def,
3594                            dwarf2_per_objfile->types, 0);
3595
3596       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3597                                                types_list, types_list_elements);
3598     }
3599
3600   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3601
3602   dwarf2_per_objfile->index_table = std::move (map);
3603   dwarf2_per_objfile->using_index = 1;
3604   dwarf2_per_objfile->quick_file_names_table =
3605     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3606
3607   return 1;
3608 }
3609
3610 /* die_reader_func for dw2_get_file_names.  */
3611
3612 static void
3613 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3614                            const gdb_byte *info_ptr,
3615                            struct die_info *comp_unit_die,
3616                            int has_children,
3617                            void *data)
3618 {
3619   struct dwarf2_cu *cu = reader->cu;
3620   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3621   struct dwarf2_per_objfile *dwarf2_per_objfile
3622     = cu->per_cu->dwarf2_per_objfile;
3623   struct objfile *objfile = dwarf2_per_objfile->objfile;
3624   struct dwarf2_per_cu_data *lh_cu;
3625   struct attribute *attr;
3626   int i;
3627   void **slot;
3628   struct quick_file_names *qfn;
3629
3630   gdb_assert (! this_cu->is_debug_types);
3631
3632   /* Our callers never want to match partial units -- instead they
3633      will match the enclosing full CU.  */
3634   if (comp_unit_die->tag == DW_TAG_partial_unit)
3635     {
3636       this_cu->v.quick->no_file_data = 1;
3637       return;
3638     }
3639
3640   lh_cu = this_cu;
3641   slot = NULL;
3642
3643   line_header_up lh;
3644   sect_offset line_offset {};
3645
3646   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3647   if (attr)
3648     {
3649       struct quick_file_names find_entry;
3650
3651       line_offset = (sect_offset) DW_UNSND (attr);
3652
3653       /* We may have already read in this line header (TU line header sharing).
3654          If we have we're done.  */
3655       find_entry.hash.dwo_unit = cu->dwo_unit;
3656       find_entry.hash.line_sect_off = line_offset;
3657       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3658                              &find_entry, INSERT);
3659       if (*slot != NULL)
3660         {
3661           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3662           return;
3663         }
3664
3665       lh = dwarf_decode_line_header (line_offset, cu);
3666     }
3667   if (lh == NULL)
3668     {
3669       lh_cu->v.quick->no_file_data = 1;
3670       return;
3671     }
3672
3673   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3674   qfn->hash.dwo_unit = cu->dwo_unit;
3675   qfn->hash.line_sect_off = line_offset;
3676   gdb_assert (slot != NULL);
3677   *slot = qfn;
3678
3679   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3680
3681   qfn->num_file_names = lh->file_names.size ();
3682   qfn->file_names =
3683     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3684   for (i = 0; i < lh->file_names.size (); ++i)
3685     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3686   qfn->real_names = NULL;
3687
3688   lh_cu->v.quick->file_names = qfn;
3689 }
3690
3691 /* A helper for the "quick" functions which attempts to read the line
3692    table for THIS_CU.  */
3693
3694 static struct quick_file_names *
3695 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3696 {
3697   /* This should never be called for TUs.  */
3698   gdb_assert (! this_cu->is_debug_types);
3699   /* Nor type unit groups.  */
3700   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3701
3702   if (this_cu->v.quick->file_names != NULL)
3703     return this_cu->v.quick->file_names;
3704   /* If we know there is no line data, no point in looking again.  */
3705   if (this_cu->v.quick->no_file_data)
3706     return NULL;
3707
3708   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3709
3710   if (this_cu->v.quick->no_file_data)
3711     return NULL;
3712   return this_cu->v.quick->file_names;
3713 }
3714
3715 /* A helper for the "quick" functions which computes and caches the
3716    real path for a given file name from the line table.  */
3717
3718 static const char *
3719 dw2_get_real_path (struct objfile *objfile,
3720                    struct quick_file_names *qfn, int index)
3721 {
3722   if (qfn->real_names == NULL)
3723     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3724                                       qfn->num_file_names, const char *);
3725
3726   if (qfn->real_names[index] == NULL)
3727     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3728
3729   return qfn->real_names[index];
3730 }
3731
3732 static struct symtab *
3733 dw2_find_last_source_symtab (struct objfile *objfile)
3734 {
3735   struct dwarf2_per_objfile *dwarf2_per_objfile
3736     = get_dwarf2_per_objfile (objfile);
3737   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3738   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3739
3740   if (cust == NULL)
3741     return NULL;
3742
3743   return compunit_primary_filetab (cust);
3744 }
3745
3746 /* Traversal function for dw2_forget_cached_source_info.  */
3747
3748 static int
3749 dw2_free_cached_file_names (void **slot, void *info)
3750 {
3751   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3752
3753   if (file_data->real_names)
3754     {
3755       int i;
3756
3757       for (i = 0; i < file_data->num_file_names; ++i)
3758         {
3759           xfree ((void*) file_data->real_names[i]);
3760           file_data->real_names[i] = NULL;
3761         }
3762     }
3763
3764   return 1;
3765 }
3766
3767 static void
3768 dw2_forget_cached_source_info (struct objfile *objfile)
3769 {
3770   struct dwarf2_per_objfile *dwarf2_per_objfile
3771     = get_dwarf2_per_objfile (objfile);
3772
3773   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3774                           dw2_free_cached_file_names, NULL);
3775 }
3776
3777 /* Helper function for dw2_map_symtabs_matching_filename that expands
3778    the symtabs and calls the iterator.  */
3779
3780 static int
3781 dw2_map_expand_apply (struct objfile *objfile,
3782                       struct dwarf2_per_cu_data *per_cu,
3783                       const char *name, const char *real_path,
3784                       gdb::function_view<bool (symtab *)> callback)
3785 {
3786   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3787
3788   /* Don't visit already-expanded CUs.  */
3789   if (per_cu->v.quick->compunit_symtab)
3790     return 0;
3791
3792   /* This may expand more than one symtab, and we want to iterate over
3793      all of them.  */
3794   dw2_instantiate_symtab (per_cu, false);
3795
3796   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3797                                     last_made, callback);
3798 }
3799
3800 /* Implementation of the map_symtabs_matching_filename method.  */
3801
3802 static bool
3803 dw2_map_symtabs_matching_filename
3804   (struct objfile *objfile, const char *name, const char *real_path,
3805    gdb::function_view<bool (symtab *)> callback)
3806 {
3807   const char *name_basename = lbasename (name);
3808   struct dwarf2_per_objfile *dwarf2_per_objfile
3809     = get_dwarf2_per_objfile (objfile);
3810
3811   /* The rule is CUs specify all the files, including those used by
3812      any TU, so there's no need to scan TUs here.  */
3813
3814   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3815     {
3816       /* We only need to look at symtabs not already expanded.  */
3817       if (per_cu->v.quick->compunit_symtab)
3818         continue;
3819
3820       quick_file_names *file_data = dw2_get_file_names (per_cu);
3821       if (file_data == NULL)
3822         continue;
3823
3824       for (int j = 0; j < file_data->num_file_names; ++j)
3825         {
3826           const char *this_name = file_data->file_names[j];
3827           const char *this_real_name;
3828
3829           if (compare_filenames_for_search (this_name, name))
3830             {
3831               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3832                                         callback))
3833                 return true;
3834               continue;
3835             }
3836
3837           /* Before we invoke realpath, which can get expensive when many
3838              files are involved, do a quick comparison of the basenames.  */
3839           if (! basenames_may_differ
3840               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3841             continue;
3842
3843           this_real_name = dw2_get_real_path (objfile, file_data, j);
3844           if (compare_filenames_for_search (this_real_name, name))
3845             {
3846               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3847                                         callback))
3848                 return true;
3849               continue;
3850             }
3851
3852           if (real_path != NULL)
3853             {
3854               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3855               gdb_assert (IS_ABSOLUTE_PATH (name));
3856               if (this_real_name != NULL
3857                   && FILENAME_CMP (real_path, this_real_name) == 0)
3858                 {
3859                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3860                                             callback))
3861                     return true;
3862                   continue;
3863                 }
3864             }
3865         }
3866     }
3867
3868   return false;
3869 }
3870
3871 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3872
3873 struct dw2_symtab_iterator
3874 {
3875   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3876   struct dwarf2_per_objfile *dwarf2_per_objfile;
3877   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3878   int want_specific_block;
3879   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3880      Unused if !WANT_SPECIFIC_BLOCK.  */
3881   int block_index;
3882   /* The kind of symbol we're looking for.  */
3883   domain_enum domain;
3884   /* The list of CUs from the index entry of the symbol,
3885      or NULL if not found.  */
3886   offset_type *vec;
3887   /* The next element in VEC to look at.  */
3888   int next;
3889   /* The number of elements in VEC, or zero if there is no match.  */
3890   int length;
3891   /* Have we seen a global version of the symbol?
3892      If so we can ignore all further global instances.
3893      This is to work around gold/15646, inefficient gold-generated
3894      indices.  */
3895   int global_seen;
3896 };
3897
3898 /* Initialize the index symtab iterator ITER.
3899    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3900    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3901
3902 static void
3903 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3904                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3905                       int want_specific_block,
3906                       int block_index,
3907                       domain_enum domain,
3908                       const char *name)
3909 {
3910   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3911   iter->want_specific_block = want_specific_block;
3912   iter->block_index = block_index;
3913   iter->domain = domain;
3914   iter->next = 0;
3915   iter->global_seen = 0;
3916
3917   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3918
3919   /* index is NULL if OBJF_READNOW.  */
3920   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3921     iter->length = MAYBE_SWAP (*iter->vec);
3922   else
3923     {
3924       iter->vec = NULL;
3925       iter->length = 0;
3926     }
3927 }
3928
3929 /* Return the next matching CU or NULL if there are no more.  */
3930
3931 static struct dwarf2_per_cu_data *
3932 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3933 {
3934   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3935
3936   for ( ; iter->next < iter->length; ++iter->next)
3937     {
3938       offset_type cu_index_and_attrs =
3939         MAYBE_SWAP (iter->vec[iter->next + 1]);
3940       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3941       int want_static = iter->block_index != GLOBAL_BLOCK;
3942       /* This value is only valid for index versions >= 7.  */
3943       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3944       gdb_index_symbol_kind symbol_kind =
3945         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3946       /* Only check the symbol attributes if they're present.
3947          Indices prior to version 7 don't record them,
3948          and indices >= 7 may elide them for certain symbols
3949          (gold does this).  */
3950       int attrs_valid =
3951         (dwarf2_per_objfile->index_table->version >= 7
3952          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3953
3954       /* Don't crash on bad data.  */
3955       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3956                        + dwarf2_per_objfile->all_type_units.size ()))
3957         {
3958           complaint (_(".gdb_index entry has bad CU index"
3959                        " [in module %s]"),
3960                      objfile_name (dwarf2_per_objfile->objfile));
3961           continue;
3962         }
3963
3964       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3965
3966       /* Skip if already read in.  */
3967       if (per_cu->v.quick->compunit_symtab)
3968         continue;
3969
3970       /* Check static vs global.  */
3971       if (attrs_valid)
3972         {
3973           if (iter->want_specific_block
3974               && want_static != is_static)
3975             continue;
3976           /* Work around gold/15646.  */
3977           if (!is_static && iter->global_seen)
3978             continue;
3979           if (!is_static)
3980             iter->global_seen = 1;
3981         }
3982
3983       /* Only check the symbol's kind if it has one.  */
3984       if (attrs_valid)
3985         {
3986           switch (iter->domain)
3987             {
3988             case VAR_DOMAIN:
3989               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3990                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3991                   /* Some types are also in VAR_DOMAIN.  */
3992                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3993                 continue;
3994               break;
3995             case STRUCT_DOMAIN:
3996               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3997                 continue;
3998               break;
3999             case LABEL_DOMAIN:
4000               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4001                 continue;
4002               break;
4003             default:
4004               break;
4005             }
4006         }
4007
4008       ++iter->next;
4009       return per_cu;
4010     }
4011
4012   return NULL;
4013 }
4014
4015 static struct compunit_symtab *
4016 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4017                    const char *name, domain_enum domain)
4018 {
4019   struct compunit_symtab *stab_best = NULL;
4020   struct dwarf2_per_objfile *dwarf2_per_objfile
4021     = get_dwarf2_per_objfile (objfile);
4022
4023   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4024
4025   struct dw2_symtab_iterator iter;
4026   struct dwarf2_per_cu_data *per_cu;
4027
4028   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4029
4030   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4031     {
4032       struct symbol *sym, *with_opaque = NULL;
4033       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
4034       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4035       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4036
4037       sym = block_find_symbol (block, name, domain,
4038                                block_find_non_opaque_type_preferred,
4039                                &with_opaque);
4040
4041       /* Some caution must be observed with overloaded functions
4042          and methods, since the index will not contain any overload
4043          information (but NAME might contain it).  */
4044
4045       if (sym != NULL
4046           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4047         return stab;
4048       if (with_opaque != NULL
4049           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4050         stab_best = stab;
4051
4052       /* Keep looking through other CUs.  */
4053     }
4054
4055   return stab_best;
4056 }
4057
4058 static void
4059 dw2_print_stats (struct objfile *objfile)
4060 {
4061   struct dwarf2_per_objfile *dwarf2_per_objfile
4062     = get_dwarf2_per_objfile (objfile);
4063   int total = (dwarf2_per_objfile->all_comp_units.size ()
4064                + dwarf2_per_objfile->all_type_units.size ());
4065   int count = 0;
4066
4067   for (int i = 0; i < total; ++i)
4068     {
4069       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4070
4071       if (!per_cu->v.quick->compunit_symtab)
4072         ++count;
4073     }
4074   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4075   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4076 }
4077
4078 /* This dumps minimal information about the index.
4079    It is called via "mt print objfiles".
4080    One use is to verify .gdb_index has been loaded by the
4081    gdb.dwarf2/gdb-index.exp testcase.  */
4082
4083 static void
4084 dw2_dump (struct objfile *objfile)
4085 {
4086   struct dwarf2_per_objfile *dwarf2_per_objfile
4087     = get_dwarf2_per_objfile (objfile);
4088
4089   gdb_assert (dwarf2_per_objfile->using_index);
4090   printf_filtered (".gdb_index:");
4091   if (dwarf2_per_objfile->index_table != NULL)
4092     {
4093       printf_filtered (" version %d\n",
4094                        dwarf2_per_objfile->index_table->version);
4095     }
4096   else
4097     printf_filtered (" faked for \"readnow\"\n");
4098   printf_filtered ("\n");
4099 }
4100
4101 static void
4102 dw2_relocate (struct objfile *objfile,
4103               const struct section_offsets *new_offsets,
4104               const struct section_offsets *delta)
4105 {
4106   /* There's nothing to relocate here.  */
4107 }
4108
4109 static void
4110 dw2_expand_symtabs_for_function (struct objfile *objfile,
4111                                  const char *func_name)
4112 {
4113   struct dwarf2_per_objfile *dwarf2_per_objfile
4114     = get_dwarf2_per_objfile (objfile);
4115
4116   struct dw2_symtab_iterator iter;
4117   struct dwarf2_per_cu_data *per_cu;
4118
4119   /* Note: It doesn't matter what we pass for block_index here.  */
4120   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4121                         func_name);
4122
4123   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4124     dw2_instantiate_symtab (per_cu, false);
4125
4126 }
4127
4128 static void
4129 dw2_expand_all_symtabs (struct objfile *objfile)
4130 {
4131   struct dwarf2_per_objfile *dwarf2_per_objfile
4132     = get_dwarf2_per_objfile (objfile);
4133   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4134                      + dwarf2_per_objfile->all_type_units.size ());
4135
4136   for (int i = 0; i < total_units; ++i)
4137     {
4138       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4139
4140       /* We don't want to directly expand a partial CU, because if we
4141          read it with the wrong language, then assertion failures can
4142          be triggered later on.  See PR symtab/23010.  So, tell
4143          dw2_instantiate_symtab to skip partial CUs -- any important
4144          partial CU will be read via DW_TAG_imported_unit anyway.  */
4145       dw2_instantiate_symtab (per_cu, true);
4146     }
4147 }
4148
4149 static void
4150 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4151                                   const char *fullname)
4152 {
4153   struct dwarf2_per_objfile *dwarf2_per_objfile
4154     = get_dwarf2_per_objfile (objfile);
4155
4156   /* We don't need to consider type units here.
4157      This is only called for examining code, e.g. expand_line_sal.
4158      There can be an order of magnitude (or more) more type units
4159      than comp units, and we avoid them if we can.  */
4160
4161   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4162     {
4163       /* We only need to look at symtabs not already expanded.  */
4164       if (per_cu->v.quick->compunit_symtab)
4165         continue;
4166
4167       quick_file_names *file_data = dw2_get_file_names (per_cu);
4168       if (file_data == NULL)
4169         continue;
4170
4171       for (int j = 0; j < file_data->num_file_names; ++j)
4172         {
4173           const char *this_fullname = file_data->file_names[j];
4174
4175           if (filename_cmp (this_fullname, fullname) == 0)
4176             {
4177               dw2_instantiate_symtab (per_cu, false);
4178               break;
4179             }
4180         }
4181     }
4182 }
4183
4184 static void
4185 dw2_map_matching_symbols (struct objfile *objfile,
4186                           const char * name, domain_enum domain,
4187                           int global,
4188                           int (*callback) (struct block *,
4189                                            struct symbol *, void *),
4190                           void *data, symbol_name_match_type match,
4191                           symbol_compare_ftype *ordered_compare)
4192 {
4193   /* Currently unimplemented; used for Ada.  The function can be called if the
4194      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4195      does not look for non-Ada symbols this function should just return.  */
4196 }
4197
4198 /* Symbol name matcher for .gdb_index names.
4199
4200    Symbol names in .gdb_index have a few particularities:
4201
4202    - There's no indication of which is the language of each symbol.
4203
4204      Since each language has its own symbol name matching algorithm,
4205      and we don't know which language is the right one, we must match
4206      each symbol against all languages.  This would be a potential
4207      performance problem if it were not mitigated by the
4208      mapped_index::name_components lookup table, which significantly
4209      reduces the number of times we need to call into this matcher,
4210      making it a non-issue.
4211
4212    - Symbol names in the index have no overload (parameter)
4213      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4214      appear as "foo" in the index, for example.
4215
4216      This means that the lookup names passed to the symbol name
4217      matcher functions must have no parameter information either
4218      because (e.g.) symbol search name "foo" does not match
4219      lookup-name "foo(int)" [while swapping search name for lookup
4220      name would match].
4221 */
4222 class gdb_index_symbol_name_matcher
4223 {
4224 public:
4225   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4226   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4227
4228   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4229      Returns true if any matcher matches.  */
4230   bool matches (const char *symbol_name);
4231
4232 private:
4233   /* A reference to the lookup name we're matching against.  */
4234   const lookup_name_info &m_lookup_name;
4235
4236   /* A vector holding all the different symbol name matchers, for all
4237      languages.  */
4238   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4239 };
4240
4241 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4242   (const lookup_name_info &lookup_name)
4243     : m_lookup_name (lookup_name)
4244 {
4245   /* Prepare the vector of comparison functions upfront, to avoid
4246      doing the same work for each symbol.  Care is taken to avoid
4247      matching with the same matcher more than once if/when multiple
4248      languages use the same matcher function.  */
4249   auto &matchers = m_symbol_name_matcher_funcs;
4250   matchers.reserve (nr_languages);
4251
4252   matchers.push_back (default_symbol_name_matcher);
4253
4254   for (int i = 0; i < nr_languages; i++)
4255     {
4256       const language_defn *lang = language_def ((enum language) i);
4257       symbol_name_matcher_ftype *name_matcher
4258         = get_symbol_name_matcher (lang, m_lookup_name);
4259
4260       /* Don't insert the same comparison routine more than once.
4261          Note that we do this linear walk instead of a seemingly
4262          cheaper sorted insert, or use a std::set or something like
4263          that, because relative order of function addresses is not
4264          stable.  This is not a problem in practice because the number
4265          of supported languages is low, and the cost here is tiny
4266          compared to the number of searches we'll do afterwards using
4267          this object.  */
4268       if (name_matcher != default_symbol_name_matcher
4269           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4270               == matchers.end ()))
4271         matchers.push_back (name_matcher);
4272     }
4273 }
4274
4275 bool
4276 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4277 {
4278   for (auto matches_name : m_symbol_name_matcher_funcs)
4279     if (matches_name (symbol_name, m_lookup_name, NULL))
4280       return true;
4281
4282   return false;
4283 }
4284
4285 /* Starting from a search name, return the string that finds the upper
4286    bound of all strings that start with SEARCH_NAME in a sorted name
4287    list.  Returns the empty string to indicate that the upper bound is
4288    the end of the list.  */
4289
4290 static std::string
4291 make_sort_after_prefix_name (const char *search_name)
4292 {
4293   /* When looking to complete "func", we find the upper bound of all
4294      symbols that start with "func" by looking for where we'd insert
4295      the closest string that would follow "func" in lexicographical
4296      order.  Usually, that's "func"-with-last-character-incremented,
4297      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4298      will be UTF-8 multi-byte sequences, but we can't be certain.
4299      Especially mind the 0xff character, which is a valid character in
4300      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4301      rule out compilers allowing it in identifiers.  Note that
4302      conveniently, strcmp/strcasecmp are specified to compare
4303      characters interpreted as unsigned char.  So what we do is treat
4304      the whole string as a base 256 number composed of a sequence of
4305      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4306      to 0, and carries 1 to the following more-significant position.
4307      If the very first character in SEARCH_NAME ends up incremented
4308      and carries/overflows, then the upper bound is the end of the
4309      list.  The string after the empty string is also the empty
4310      string.
4311
4312      Some examples of this operation:
4313
4314        SEARCH_NAME  => "+1" RESULT
4315
4316        "abc"              => "abd"
4317        "ab\xff"           => "ac"
4318        "\xff" "a" "\xff"  => "\xff" "b"
4319        "\xff"             => ""
4320        "\xff\xff"         => ""
4321        ""                 => ""
4322
4323      Then, with these symbols for example:
4324
4325       func
4326       func1
4327       fund
4328
4329      completing "func" looks for symbols between "func" and
4330      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4331      which finds "func" and "func1", but not "fund".
4332
4333      And with:
4334
4335       funcÿ     (Latin1 'ÿ' [0xff])
4336       funcÿ1
4337       fund
4338
4339      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4340      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4341
4342      And with:
4343
4344       ÿÿ        (Latin1 'ÿ' [0xff])
4345       ÿÿ1
4346
4347      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4348      the end of the list.
4349   */
4350   std::string after = search_name;
4351   while (!after.empty () && (unsigned char) after.back () == 0xff)
4352     after.pop_back ();
4353   if (!after.empty ())
4354     after.back () = (unsigned char) after.back () + 1;
4355   return after;
4356 }
4357
4358 /* See declaration.  */
4359
4360 std::pair<std::vector<name_component>::const_iterator,
4361           std::vector<name_component>::const_iterator>
4362 mapped_index_base::find_name_components_bounds
4363   (const lookup_name_info &lookup_name_without_params) const
4364 {
4365   auto *name_cmp
4366     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4367
4368   const char *cplus
4369     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4370
4371   /* Comparison function object for lower_bound that matches against a
4372      given symbol name.  */
4373   auto lookup_compare_lower = [&] (const name_component &elem,
4374                                    const char *name)
4375     {
4376       const char *elem_qualified = this->symbol_name_at (elem.idx);
4377       const char *elem_name = elem_qualified + elem.name_offset;
4378       return name_cmp (elem_name, name) < 0;
4379     };
4380
4381   /* Comparison function object for upper_bound that matches against a
4382      given symbol name.  */
4383   auto lookup_compare_upper = [&] (const char *name,
4384                                    const name_component &elem)
4385     {
4386       const char *elem_qualified = this->symbol_name_at (elem.idx);
4387       const char *elem_name = elem_qualified + elem.name_offset;
4388       return name_cmp (name, elem_name) < 0;
4389     };
4390
4391   auto begin = this->name_components.begin ();
4392   auto end = this->name_components.end ();
4393
4394   /* Find the lower bound.  */
4395   auto lower = [&] ()
4396     {
4397       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4398         return begin;
4399       else
4400         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4401     } ();
4402
4403   /* Find the upper bound.  */
4404   auto upper = [&] ()
4405     {
4406       if (lookup_name_without_params.completion_mode ())
4407         {
4408           /* In completion mode, we want UPPER to point past all
4409              symbols names that have the same prefix.  I.e., with
4410              these symbols, and completing "func":
4411
4412               function        << lower bound
4413               function1
4414               other_function  << upper bound
4415
4416              We find the upper bound by looking for the insertion
4417              point of "func"-with-last-character-incremented,
4418              i.e. "fund".  */
4419           std::string after = make_sort_after_prefix_name (cplus);
4420           if (after.empty ())
4421             return end;
4422           return std::lower_bound (lower, end, after.c_str (),
4423                                    lookup_compare_lower);
4424         }
4425       else
4426         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4427     } ();
4428
4429   return {lower, upper};
4430 }
4431
4432 /* See declaration.  */
4433
4434 void
4435 mapped_index_base::build_name_components ()
4436 {
4437   if (!this->name_components.empty ())
4438     return;
4439
4440   this->name_components_casing = case_sensitivity;
4441   auto *name_cmp
4442     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4443
4444   /* The code below only knows how to break apart components of C++
4445      symbol names (and other languages that use '::' as
4446      namespace/module separator).  If we add support for wild matching
4447      to some language that uses some other operator (E.g., Ada, Go and
4448      D use '.'), then we'll need to try splitting the symbol name
4449      according to that language too.  Note that Ada does support wild
4450      matching, but doesn't currently support .gdb_index.  */
4451   auto count = this->symbol_name_count ();
4452   for (offset_type idx = 0; idx < count; idx++)
4453     {
4454       if (this->symbol_name_slot_invalid (idx))
4455         continue;
4456
4457       const char *name = this->symbol_name_at (idx);
4458
4459       /* Add each name component to the name component table.  */
4460       unsigned int previous_len = 0;
4461       for (unsigned int current_len = cp_find_first_component (name);
4462            name[current_len] != '\0';
4463            current_len += cp_find_first_component (name + current_len))
4464         {
4465           gdb_assert (name[current_len] == ':');
4466           this->name_components.push_back ({previous_len, idx});
4467           /* Skip the '::'.  */
4468           current_len += 2;
4469           previous_len = current_len;
4470         }
4471       this->name_components.push_back ({previous_len, idx});
4472     }
4473
4474   /* Sort name_components elements by name.  */
4475   auto name_comp_compare = [&] (const name_component &left,
4476                                 const name_component &right)
4477     {
4478       const char *left_qualified = this->symbol_name_at (left.idx);
4479       const char *right_qualified = this->symbol_name_at (right.idx);
4480
4481       const char *left_name = left_qualified + left.name_offset;
4482       const char *right_name = right_qualified + right.name_offset;
4483
4484       return name_cmp (left_name, right_name) < 0;
4485     };
4486
4487   std::sort (this->name_components.begin (),
4488              this->name_components.end (),
4489              name_comp_compare);
4490 }
4491
4492 /* Helper for dw2_expand_symtabs_matching that works with a
4493    mapped_index_base instead of the containing objfile.  This is split
4494    to a separate function in order to be able to unit test the
4495    name_components matching using a mock mapped_index_base.  For each
4496    symbol name that matches, calls MATCH_CALLBACK, passing it the
4497    symbol's index in the mapped_index_base symbol table.  */
4498
4499 static void
4500 dw2_expand_symtabs_matching_symbol
4501   (mapped_index_base &index,
4502    const lookup_name_info &lookup_name_in,
4503    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4504    enum search_domain kind,
4505    gdb::function_view<void (offset_type)> match_callback)
4506 {
4507   lookup_name_info lookup_name_without_params
4508     = lookup_name_in.make_ignore_params ();
4509   gdb_index_symbol_name_matcher lookup_name_matcher
4510     (lookup_name_without_params);
4511
4512   /* Build the symbol name component sorted vector, if we haven't
4513      yet.  */
4514   index.build_name_components ();
4515
4516   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4517
4518   /* Now for each symbol name in range, check to see if we have a name
4519      match, and if so, call the MATCH_CALLBACK callback.  */
4520
4521   /* The same symbol may appear more than once in the range though.
4522      E.g., if we're looking for symbols that complete "w", and we have
4523      a symbol named "w1::w2", we'll find the two name components for
4524      that same symbol in the range.  To be sure we only call the
4525      callback once per symbol, we first collect the symbol name
4526      indexes that matched in a temporary vector and ignore
4527      duplicates.  */
4528   std::vector<offset_type> matches;
4529   matches.reserve (std::distance (bounds.first, bounds.second));
4530
4531   for (; bounds.first != bounds.second; ++bounds.first)
4532     {
4533       const char *qualified = index.symbol_name_at (bounds.first->idx);
4534
4535       if (!lookup_name_matcher.matches (qualified)
4536           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4537         continue;
4538
4539       matches.push_back (bounds.first->idx);
4540     }
4541
4542   std::sort (matches.begin (), matches.end ());
4543
4544   /* Finally call the callback, once per match.  */
4545   ULONGEST prev = -1;
4546   for (offset_type idx : matches)
4547     {
4548       if (prev != idx)
4549         {
4550           match_callback (idx);
4551           prev = idx;
4552         }
4553     }
4554
4555   /* Above we use a type wider than idx's for 'prev', since 0 and
4556      (offset_type)-1 are both possible values.  */
4557   static_assert (sizeof (prev) > sizeof (offset_type), "");
4558 }
4559
4560 #if GDB_SELF_TEST
4561
4562 namespace selftests { namespace dw2_expand_symtabs_matching {
4563
4564 /* A mock .gdb_index/.debug_names-like name index table, enough to
4565    exercise dw2_expand_symtabs_matching_symbol, which works with the
4566    mapped_index_base interface.  Builds an index from the symbol list
4567    passed as parameter to the constructor.  */
4568 class mock_mapped_index : public mapped_index_base
4569 {
4570 public:
4571   mock_mapped_index (gdb::array_view<const char *> symbols)
4572     : m_symbol_table (symbols)
4573   {}
4574
4575   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4576
4577   /* Return the number of names in the symbol table.  */
4578   size_t symbol_name_count () const override
4579   {
4580     return m_symbol_table.size ();
4581   }
4582
4583   /* Get the name of the symbol at IDX in the symbol table.  */
4584   const char *symbol_name_at (offset_type idx) const override
4585   {
4586     return m_symbol_table[idx];
4587   }
4588
4589 private:
4590   gdb::array_view<const char *> m_symbol_table;
4591 };
4592
4593 /* Convenience function that converts a NULL pointer to a "<null>"
4594    string, to pass to print routines.  */
4595
4596 static const char *
4597 string_or_null (const char *str)
4598 {
4599   return str != NULL ? str : "<null>";
4600 }
4601
4602 /* Check if a lookup_name_info built from
4603    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4604    index.  EXPECTED_LIST is the list of expected matches, in expected
4605    matching order.  If no match expected, then an empty list is
4606    specified.  Returns true on success.  On failure prints a warning
4607    indicating the file:line that failed, and returns false.  */
4608
4609 static bool
4610 check_match (const char *file, int line,
4611              mock_mapped_index &mock_index,
4612              const char *name, symbol_name_match_type match_type,
4613              bool completion_mode,
4614              std::initializer_list<const char *> expected_list)
4615 {
4616   lookup_name_info lookup_name (name, match_type, completion_mode);
4617
4618   bool matched = true;
4619
4620   auto mismatch = [&] (const char *expected_str,
4621                        const char *got)
4622   {
4623     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4624                "expected=\"%s\", got=\"%s\"\n"),
4625              file, line,
4626              (match_type == symbol_name_match_type::FULL
4627               ? "FULL" : "WILD"),
4628              name, string_or_null (expected_str), string_or_null (got));
4629     matched = false;
4630   };
4631
4632   auto expected_it = expected_list.begin ();
4633   auto expected_end = expected_list.end ();
4634
4635   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4636                                       NULL, ALL_DOMAIN,
4637                                       [&] (offset_type idx)
4638   {
4639     const char *matched_name = mock_index.symbol_name_at (idx);
4640     const char *expected_str
4641       = expected_it == expected_end ? NULL : *expected_it++;
4642
4643     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4644       mismatch (expected_str, matched_name);
4645   });
4646
4647   const char *expected_str
4648   = expected_it == expected_end ? NULL : *expected_it++;
4649   if (expected_str != NULL)
4650     mismatch (expected_str, NULL);
4651
4652   return matched;
4653 }
4654
4655 /* The symbols added to the mock mapped_index for testing (in
4656    canonical form).  */
4657 static const char *test_symbols[] = {
4658   "function",
4659   "std::bar",
4660   "std::zfunction",
4661   "std::zfunction2",
4662   "w1::w2",
4663   "ns::foo<char*>",
4664   "ns::foo<int>",
4665   "ns::foo<long>",
4666   "ns2::tmpl<int>::foo2",
4667   "(anonymous namespace)::A::B::C",
4668
4669   /* These are used to check that the increment-last-char in the
4670      matching algorithm for completion doesn't match "t1_fund" when
4671      completing "t1_func".  */
4672   "t1_func",
4673   "t1_func1",
4674   "t1_fund",
4675   "t1_fund1",
4676
4677   /* A UTF-8 name with multi-byte sequences to make sure that
4678      cp-name-parser understands this as a single identifier ("função"
4679      is "function" in PT).  */
4680   u8"u8função",
4681
4682   /* \377 (0xff) is Latin1 'ÿ'.  */
4683   "yfunc\377",
4684
4685   /* \377 (0xff) is Latin1 'ÿ'.  */
4686   "\377",
4687   "\377\377123",
4688
4689   /* A name with all sorts of complications.  Starts with "z" to make
4690      it easier for the completion tests below.  */
4691 #define Z_SYM_NAME \
4692   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4693     "::tuple<(anonymous namespace)::ui*, " \
4694     "std::default_delete<(anonymous namespace)::ui>, void>"
4695
4696   Z_SYM_NAME
4697 };
4698
4699 /* Returns true if the mapped_index_base::find_name_component_bounds
4700    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4701    in completion mode.  */
4702
4703 static bool
4704 check_find_bounds_finds (mapped_index_base &index,
4705                          const char *search_name,
4706                          gdb::array_view<const char *> expected_syms)
4707 {
4708   lookup_name_info lookup_name (search_name,
4709                                 symbol_name_match_type::FULL, true);
4710
4711   auto bounds = index.find_name_components_bounds (lookup_name);
4712
4713   size_t distance = std::distance (bounds.first, bounds.second);
4714   if (distance != expected_syms.size ())
4715     return false;
4716
4717   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4718     {
4719       auto nc_elem = bounds.first + exp_elem;
4720       const char *qualified = index.symbol_name_at (nc_elem->idx);
4721       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4722         return false;
4723     }
4724
4725   return true;
4726 }
4727
4728 /* Test the lower-level mapped_index::find_name_component_bounds
4729    method.  */
4730
4731 static void
4732 test_mapped_index_find_name_component_bounds ()
4733 {
4734   mock_mapped_index mock_index (test_symbols);
4735
4736   mock_index.build_name_components ();
4737
4738   /* Test the lower-level mapped_index::find_name_component_bounds
4739      method in completion mode.  */
4740   {
4741     static const char *expected_syms[] = {
4742       "t1_func",
4743       "t1_func1",
4744     };
4745
4746     SELF_CHECK (check_find_bounds_finds (mock_index,
4747                                          "t1_func", expected_syms));
4748   }
4749
4750   /* Check that the increment-last-char in the name matching algorithm
4751      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4752   {
4753     static const char *expected_syms1[] = {
4754       "\377",
4755       "\377\377123",
4756     };
4757     SELF_CHECK (check_find_bounds_finds (mock_index,
4758                                          "\377", expected_syms1));
4759
4760     static const char *expected_syms2[] = {
4761       "\377\377123",
4762     };
4763     SELF_CHECK (check_find_bounds_finds (mock_index,
4764                                          "\377\377", expected_syms2));
4765   }
4766 }
4767
4768 /* Test dw2_expand_symtabs_matching_symbol.  */
4769
4770 static void
4771 test_dw2_expand_symtabs_matching_symbol ()
4772 {
4773   mock_mapped_index mock_index (test_symbols);
4774
4775   /* We let all tests run until the end even if some fails, for debug
4776      convenience.  */
4777   bool any_mismatch = false;
4778
4779   /* Create the expected symbols list (an initializer_list).  Needed
4780      because lists have commas, and we need to pass them to CHECK,
4781      which is a macro.  */
4782 #define EXPECT(...) { __VA_ARGS__ }
4783
4784   /* Wrapper for check_match that passes down the current
4785      __FILE__/__LINE__.  */
4786 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4787   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4788                                 mock_index,                             \
4789                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4790                                 EXPECTED_LIST)
4791
4792   /* Identity checks.  */
4793   for (const char *sym : test_symbols)
4794     {
4795       /* Should be able to match all existing symbols.  */
4796       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4797                    EXPECT (sym));
4798
4799       /* Should be able to match all existing symbols with
4800          parameters.  */
4801       std::string with_params = std::string (sym) + "(int)";
4802       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4803                    EXPECT (sym));
4804
4805       /* Should be able to match all existing symbols with
4806          parameters and qualifiers.  */
4807       with_params = std::string (sym) + " ( int ) const";
4808       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4809                    EXPECT (sym));
4810
4811       /* This should really find sym, but cp-name-parser.y doesn't
4812          know about lvalue/rvalue qualifiers yet.  */
4813       with_params = std::string (sym) + " ( int ) &&";
4814       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4815                    {});
4816     }
4817
4818   /* Check that the name matching algorithm for completion doesn't get
4819      confused with Latin1 'ÿ' / 0xff.  */
4820   {
4821     static const char str[] = "\377";
4822     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4823                  EXPECT ("\377", "\377\377123"));
4824   }
4825
4826   /* Check that the increment-last-char in the matching algorithm for
4827      completion doesn't match "t1_fund" when completing "t1_func".  */
4828   {
4829     static const char str[] = "t1_func";
4830     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4831                  EXPECT ("t1_func", "t1_func1"));
4832   }
4833
4834   /* Check that completion mode works at each prefix of the expected
4835      symbol name.  */
4836   {
4837     static const char str[] = "function(int)";
4838     size_t len = strlen (str);
4839     std::string lookup;
4840
4841     for (size_t i = 1; i < len; i++)
4842       {
4843         lookup.assign (str, i);
4844         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4845                      EXPECT ("function"));
4846       }
4847   }
4848
4849   /* While "w" is a prefix of both components, the match function
4850      should still only be called once.  */
4851   {
4852     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4853                  EXPECT ("w1::w2"));
4854     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4855                  EXPECT ("w1::w2"));
4856   }
4857
4858   /* Same, with a "complicated" symbol.  */
4859   {
4860     static const char str[] = Z_SYM_NAME;
4861     size_t len = strlen (str);
4862     std::string lookup;
4863
4864     for (size_t i = 1; i < len; i++)
4865       {
4866         lookup.assign (str, i);
4867         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4868                      EXPECT (Z_SYM_NAME));
4869       }
4870   }
4871
4872   /* In FULL mode, an incomplete symbol doesn't match.  */
4873   {
4874     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4875                  {});
4876   }
4877
4878   /* A complete symbol with parameters matches any overload, since the
4879      index has no overload info.  */
4880   {
4881     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4882                  EXPECT ("std::zfunction", "std::zfunction2"));
4883     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4884                  EXPECT ("std::zfunction", "std::zfunction2"));
4885     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4886                  EXPECT ("std::zfunction", "std::zfunction2"));
4887   }
4888
4889   /* Check that whitespace is ignored appropriately.  A symbol with a
4890      template argument list. */
4891   {
4892     static const char expected[] = "ns::foo<int>";
4893     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4894                  EXPECT (expected));
4895     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4896                  EXPECT (expected));
4897   }
4898
4899   /* Check that whitespace is ignored appropriately.  A symbol with a
4900      template argument list that includes a pointer.  */
4901   {
4902     static const char expected[] = "ns::foo<char*>";
4903     /* Try both completion and non-completion modes.  */
4904     static const bool completion_mode[2] = {false, true};
4905     for (size_t i = 0; i < 2; i++)
4906       {
4907         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4908                      completion_mode[i], EXPECT (expected));
4909         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4910                      completion_mode[i], EXPECT (expected));
4911
4912         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4913                      completion_mode[i], EXPECT (expected));
4914         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4915                      completion_mode[i], EXPECT (expected));
4916       }
4917   }
4918
4919   {
4920     /* Check method qualifiers are ignored.  */
4921     static const char expected[] = "ns::foo<char*>";
4922     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4923                  symbol_name_match_type::FULL, true, EXPECT (expected));
4924     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4925                  symbol_name_match_type::FULL, true, EXPECT (expected));
4926     CHECK_MATCH ("foo < char * >  ( int ) const",
4927                  symbol_name_match_type::WILD, true, EXPECT (expected));
4928     CHECK_MATCH ("foo < char * >  ( int ) &&",
4929                  symbol_name_match_type::WILD, true, EXPECT (expected));
4930   }
4931
4932   /* Test lookup names that don't match anything.  */
4933   {
4934     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4935                  {});
4936
4937     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4938                  {});
4939   }
4940
4941   /* Some wild matching tests, exercising "(anonymous namespace)",
4942      which should not be confused with a parameter list.  */
4943   {
4944     static const char *syms[] = {
4945       "A::B::C",
4946       "B::C",
4947       "C",
4948       "A :: B :: C ( int )",
4949       "B :: C ( int )",
4950       "C ( int )",
4951     };
4952
4953     for (const char *s : syms)
4954       {
4955         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4956                      EXPECT ("(anonymous namespace)::A::B::C"));
4957       }
4958   }
4959
4960   {
4961     static const char expected[] = "ns2::tmpl<int>::foo2";
4962     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4963                  EXPECT (expected));
4964     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4965                  EXPECT (expected));
4966   }
4967
4968   SELF_CHECK (!any_mismatch);
4969
4970 #undef EXPECT
4971 #undef CHECK_MATCH
4972 }
4973
4974 static void
4975 run_test ()
4976 {
4977   test_mapped_index_find_name_component_bounds ();
4978   test_dw2_expand_symtabs_matching_symbol ();
4979 }
4980
4981 }} // namespace selftests::dw2_expand_symtabs_matching
4982
4983 #endif /* GDB_SELF_TEST */
4984
4985 /* If FILE_MATCHER is NULL or if PER_CU has
4986    dwarf2_per_cu_quick_data::MARK set (see
4987    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4988    EXPANSION_NOTIFY on it.  */
4989
4990 static void
4991 dw2_expand_symtabs_matching_one
4992   (struct dwarf2_per_cu_data *per_cu,
4993    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4994    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4995 {
4996   if (file_matcher == NULL || per_cu->v.quick->mark)
4997     {
4998       bool symtab_was_null
4999         = (per_cu->v.quick->compunit_symtab == NULL);
5000
5001       dw2_instantiate_symtab (per_cu, false);
5002
5003       if (expansion_notify != NULL
5004           && symtab_was_null
5005           && per_cu->v.quick->compunit_symtab != NULL)
5006         expansion_notify (per_cu->v.quick->compunit_symtab);
5007     }
5008 }
5009
5010 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5011    matched, to expand corresponding CUs that were marked.  IDX is the
5012    index of the symbol name that matched.  */
5013
5014 static void
5015 dw2_expand_marked_cus
5016   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5017    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5018    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5019    search_domain kind)
5020 {
5021   offset_type *vec, vec_len, vec_idx;
5022   bool global_seen = false;
5023   mapped_index &index = *dwarf2_per_objfile->index_table;
5024
5025   vec = (offset_type *) (index.constant_pool
5026                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5027   vec_len = MAYBE_SWAP (vec[0]);
5028   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5029     {
5030       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5031       /* This value is only valid for index versions >= 7.  */
5032       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5033       gdb_index_symbol_kind symbol_kind =
5034         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5035       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5036       /* Only check the symbol attributes if they're present.
5037          Indices prior to version 7 don't record them,
5038          and indices >= 7 may elide them for certain symbols
5039          (gold does this).  */
5040       int attrs_valid =
5041         (index.version >= 7
5042          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5043
5044       /* Work around gold/15646.  */
5045       if (attrs_valid)
5046         {
5047           if (!is_static && global_seen)
5048             continue;
5049           if (!is_static)
5050             global_seen = true;
5051         }
5052
5053       /* Only check the symbol's kind if it has one.  */
5054       if (attrs_valid)
5055         {
5056           switch (kind)
5057             {
5058             case VARIABLES_DOMAIN:
5059               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5060                 continue;
5061               break;
5062             case FUNCTIONS_DOMAIN:
5063               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5064                 continue;
5065               break;
5066             case TYPES_DOMAIN:
5067               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5068                 continue;
5069               break;
5070             default:
5071               break;
5072             }
5073         }
5074
5075       /* Don't crash on bad data.  */
5076       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5077                        + dwarf2_per_objfile->all_type_units.size ()))
5078         {
5079           complaint (_(".gdb_index entry has bad CU index"
5080                        " [in module %s]"),
5081                        objfile_name (dwarf2_per_objfile->objfile));
5082           continue;
5083         }
5084
5085       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5086       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5087                                        expansion_notify);
5088     }
5089 }
5090
5091 /* If FILE_MATCHER is non-NULL, set all the
5092    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5093    that match FILE_MATCHER.  */
5094
5095 static void
5096 dw_expand_symtabs_matching_file_matcher
5097   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5098    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5099 {
5100   if (file_matcher == NULL)
5101     return;
5102
5103   objfile *const objfile = dwarf2_per_objfile->objfile;
5104
5105   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5106                                             htab_eq_pointer,
5107                                             NULL, xcalloc, xfree));
5108   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5109                                                 htab_eq_pointer,
5110                                                 NULL, xcalloc, xfree));
5111
5112   /* The rule is CUs specify all the files, including those used by
5113      any TU, so there's no need to scan TUs here.  */
5114
5115   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5116     {
5117       QUIT;
5118
5119       per_cu->v.quick->mark = 0;
5120
5121       /* We only need to look at symtabs not already expanded.  */
5122       if (per_cu->v.quick->compunit_symtab)
5123         continue;
5124
5125       quick_file_names *file_data = dw2_get_file_names (per_cu);
5126       if (file_data == NULL)
5127         continue;
5128
5129       if (htab_find (visited_not_found.get (), file_data) != NULL)
5130         continue;
5131       else if (htab_find (visited_found.get (), file_data) != NULL)
5132         {
5133           per_cu->v.quick->mark = 1;
5134           continue;
5135         }
5136
5137       for (int j = 0; j < file_data->num_file_names; ++j)
5138         {
5139           const char *this_real_name;
5140
5141           if (file_matcher (file_data->file_names[j], false))
5142             {
5143               per_cu->v.quick->mark = 1;
5144               break;
5145             }
5146
5147           /* Before we invoke realpath, which can get expensive when many
5148              files are involved, do a quick comparison of the basenames.  */
5149           if (!basenames_may_differ
5150               && !file_matcher (lbasename (file_data->file_names[j]),
5151                                 true))
5152             continue;
5153
5154           this_real_name = dw2_get_real_path (objfile, file_data, j);
5155           if (file_matcher (this_real_name, false))
5156             {
5157               per_cu->v.quick->mark = 1;
5158               break;
5159             }
5160         }
5161
5162       void **slot = htab_find_slot (per_cu->v.quick->mark
5163                                     ? visited_found.get ()
5164                                     : visited_not_found.get (),
5165                                     file_data, INSERT);
5166       *slot = file_data;
5167     }
5168 }
5169
5170 static void
5171 dw2_expand_symtabs_matching
5172   (struct objfile *objfile,
5173    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5174    const lookup_name_info &lookup_name,
5175    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5176    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5177    enum search_domain kind)
5178 {
5179   struct dwarf2_per_objfile *dwarf2_per_objfile
5180     = get_dwarf2_per_objfile (objfile);
5181
5182   /* index_table is NULL if OBJF_READNOW.  */
5183   if (!dwarf2_per_objfile->index_table)
5184     return;
5185
5186   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5187
5188   mapped_index &index = *dwarf2_per_objfile->index_table;
5189
5190   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5191                                       symbol_matcher,
5192                                       kind, [&] (offset_type idx)
5193     {
5194       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5195                              expansion_notify, kind);
5196     });
5197 }
5198
5199 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5200    symtab.  */
5201
5202 static struct compunit_symtab *
5203 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5204                                           CORE_ADDR pc)
5205 {
5206   int i;
5207
5208   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5209       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5210     return cust;
5211
5212   if (cust->includes == NULL)
5213     return NULL;
5214
5215   for (i = 0; cust->includes[i]; ++i)
5216     {
5217       struct compunit_symtab *s = cust->includes[i];
5218
5219       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5220       if (s != NULL)
5221         return s;
5222     }
5223
5224   return NULL;
5225 }
5226
5227 static struct compunit_symtab *
5228 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5229                                   struct bound_minimal_symbol msymbol,
5230                                   CORE_ADDR pc,
5231                                   struct obj_section *section,
5232                                   int warn_if_readin)
5233 {
5234   struct dwarf2_per_cu_data *data;
5235   struct compunit_symtab *result;
5236
5237   if (!objfile->psymtabs_addrmap)
5238     return NULL;
5239
5240   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5241                                                      pc);
5242   if (!data)
5243     return NULL;
5244
5245   if (warn_if_readin && data->v.quick->compunit_symtab)
5246     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5247              paddress (get_objfile_arch (objfile), pc));
5248
5249   result
5250     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
5251                                                                         false),
5252                                                 pc);
5253   gdb_assert (result != NULL);
5254   return result;
5255 }
5256
5257 static void
5258 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5259                           void *data, int need_fullname)
5260 {
5261   struct dwarf2_per_objfile *dwarf2_per_objfile
5262     = get_dwarf2_per_objfile (objfile);
5263
5264   if (!dwarf2_per_objfile->filenames_cache)
5265     {
5266       dwarf2_per_objfile->filenames_cache.emplace ();
5267
5268       htab_up visited (htab_create_alloc (10,
5269                                           htab_hash_pointer, htab_eq_pointer,
5270                                           NULL, xcalloc, xfree));
5271
5272       /* The rule is CUs specify all the files, including those used
5273          by any TU, so there's no need to scan TUs here.  We can
5274          ignore file names coming from already-expanded CUs.  */
5275
5276       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5277         {
5278           if (per_cu->v.quick->compunit_symtab)
5279             {
5280               void **slot = htab_find_slot (visited.get (),
5281                                             per_cu->v.quick->file_names,
5282                                             INSERT);
5283
5284               *slot = per_cu->v.quick->file_names;
5285             }
5286         }
5287
5288       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5289         {
5290           /* We only need to look at symtabs not already expanded.  */
5291           if (per_cu->v.quick->compunit_symtab)
5292             continue;
5293
5294           quick_file_names *file_data = dw2_get_file_names (per_cu);
5295           if (file_data == NULL)
5296             continue;
5297
5298           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5299           if (*slot)
5300             {
5301               /* Already visited.  */
5302               continue;
5303             }
5304           *slot = file_data;
5305
5306           for (int j = 0; j < file_data->num_file_names; ++j)
5307             {
5308               const char *filename = file_data->file_names[j];
5309               dwarf2_per_objfile->filenames_cache->seen (filename);
5310             }
5311         }
5312     }
5313
5314   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5315     {
5316       gdb::unique_xmalloc_ptr<char> this_real_name;
5317
5318       if (need_fullname)
5319         this_real_name = gdb_realpath (filename);
5320       (*fun) (filename, this_real_name.get (), data);
5321     });
5322 }
5323
5324 static int
5325 dw2_has_symbols (struct objfile *objfile)
5326 {
5327   return 1;
5328 }
5329
5330 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5331 {
5332   dw2_has_symbols,
5333   dw2_find_last_source_symtab,
5334   dw2_forget_cached_source_info,
5335   dw2_map_symtabs_matching_filename,
5336   dw2_lookup_symbol,
5337   dw2_print_stats,
5338   dw2_dump,
5339   dw2_relocate,
5340   dw2_expand_symtabs_for_function,
5341   dw2_expand_all_symtabs,
5342   dw2_expand_symtabs_with_fullname,
5343   dw2_map_matching_symbols,
5344   dw2_expand_symtabs_matching,
5345   dw2_find_pc_sect_compunit_symtab,
5346   NULL,
5347   dw2_map_symbol_filenames
5348 };
5349
5350 /* DWARF-5 debug_names reader.  */
5351
5352 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5353 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5354
5355 /* A helper function that reads the .debug_names section in SECTION
5356    and fills in MAP.  FILENAME is the name of the file containing the
5357    section; it is used for error reporting.
5358
5359    Returns true if all went well, false otherwise.  */
5360
5361 static bool
5362 read_debug_names_from_section (struct objfile *objfile,
5363                                const char *filename,
5364                                struct dwarf2_section_info *section,
5365                                mapped_debug_names &map)
5366 {
5367   if (dwarf2_section_empty_p (section))
5368     return false;
5369
5370   /* Older elfutils strip versions could keep the section in the main
5371      executable while splitting it for the separate debug info file.  */
5372   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5373     return false;
5374
5375   dwarf2_read_section (objfile, section);
5376
5377   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5378
5379   const gdb_byte *addr = section->buffer;
5380
5381   bfd *const abfd = get_section_bfd_owner (section);
5382
5383   unsigned int bytes_read;
5384   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5385   addr += bytes_read;
5386
5387   map.dwarf5_is_dwarf64 = bytes_read != 4;
5388   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5389   if (bytes_read + length != section->size)
5390     {
5391       /* There may be multiple per-CU indices.  */
5392       warning (_("Section .debug_names in %s length %s does not match "
5393                  "section length %s, ignoring .debug_names."),
5394                filename, plongest (bytes_read + length),
5395                pulongest (section->size));
5396       return false;
5397     }
5398
5399   /* The version number.  */
5400   uint16_t version = read_2_bytes (abfd, addr);
5401   addr += 2;
5402   if (version != 5)
5403     {
5404       warning (_("Section .debug_names in %s has unsupported version %d, "
5405                  "ignoring .debug_names."),
5406                filename, version);
5407       return false;
5408     }
5409
5410   /* Padding.  */
5411   uint16_t padding = read_2_bytes (abfd, addr);
5412   addr += 2;
5413   if (padding != 0)
5414     {
5415       warning (_("Section .debug_names in %s has unsupported padding %d, "
5416                  "ignoring .debug_names."),
5417                filename, padding);
5418       return false;
5419     }
5420
5421   /* comp_unit_count - The number of CUs in the CU list.  */
5422   map.cu_count = read_4_bytes (abfd, addr);
5423   addr += 4;
5424
5425   /* local_type_unit_count - The number of TUs in the local TU
5426      list.  */
5427   map.tu_count = read_4_bytes (abfd, addr);
5428   addr += 4;
5429
5430   /* foreign_type_unit_count - The number of TUs in the foreign TU
5431      list.  */
5432   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5433   addr += 4;
5434   if (foreign_tu_count != 0)
5435     {
5436       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5437                  "ignoring .debug_names."),
5438                filename, static_cast<unsigned long> (foreign_tu_count));
5439       return false;
5440     }
5441
5442   /* bucket_count - The number of hash buckets in the hash lookup
5443      table.  */
5444   map.bucket_count = read_4_bytes (abfd, addr);
5445   addr += 4;
5446
5447   /* name_count - The number of unique names in the index.  */
5448   map.name_count = read_4_bytes (abfd, addr);
5449   addr += 4;
5450
5451   /* abbrev_table_size - The size in bytes of the abbreviations
5452      table.  */
5453   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5454   addr += 4;
5455
5456   /* augmentation_string_size - The size in bytes of the augmentation
5457      string.  This value is rounded up to a multiple of 4.  */
5458   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5459   addr += 4;
5460   map.augmentation_is_gdb = ((augmentation_string_size
5461                               == sizeof (dwarf5_augmentation))
5462                              && memcmp (addr, dwarf5_augmentation,
5463                                         sizeof (dwarf5_augmentation)) == 0);
5464   augmentation_string_size += (-augmentation_string_size) & 3;
5465   addr += augmentation_string_size;
5466
5467   /* List of CUs */
5468   map.cu_table_reordered = addr;
5469   addr += map.cu_count * map.offset_size;
5470
5471   /* List of Local TUs */
5472   map.tu_table_reordered = addr;
5473   addr += map.tu_count * map.offset_size;
5474
5475   /* Hash Lookup Table */
5476   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5477   addr += map.bucket_count * 4;
5478   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5479   addr += map.name_count * 4;
5480
5481   /* Name Table */
5482   map.name_table_string_offs_reordered = addr;
5483   addr += map.name_count * map.offset_size;
5484   map.name_table_entry_offs_reordered = addr;
5485   addr += map.name_count * map.offset_size;
5486
5487   const gdb_byte *abbrev_table_start = addr;
5488   for (;;)
5489     {
5490       unsigned int bytes_read;
5491       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5492       addr += bytes_read;
5493       if (index_num == 0)
5494         break;
5495
5496       const auto insertpair
5497         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5498       if (!insertpair.second)
5499         {
5500           warning (_("Section .debug_names in %s has duplicate index %s, "
5501                      "ignoring .debug_names."),
5502                    filename, pulongest (index_num));
5503           return false;
5504         }
5505       mapped_debug_names::index_val &indexval = insertpair.first->second;
5506       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5507       addr += bytes_read;
5508
5509       for (;;)
5510         {
5511           mapped_debug_names::index_val::attr attr;
5512           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5513           addr += bytes_read;
5514           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5515           addr += bytes_read;
5516           if (attr.form == DW_FORM_implicit_const)
5517             {
5518               attr.implicit_const = read_signed_leb128 (abfd, addr,
5519                                                         &bytes_read);
5520               addr += bytes_read;
5521             }
5522           if (attr.dw_idx == 0 && attr.form == 0)
5523             break;
5524           indexval.attr_vec.push_back (std::move (attr));
5525         }
5526     }
5527   if (addr != abbrev_table_start + abbrev_table_size)
5528     {
5529       warning (_("Section .debug_names in %s has abbreviation_table "
5530                  "of size %zu vs. written as %u, ignoring .debug_names."),
5531                filename, addr - abbrev_table_start, abbrev_table_size);
5532       return false;
5533     }
5534   map.entry_pool = addr;
5535
5536   return true;
5537 }
5538
5539 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5540    list.  */
5541
5542 static void
5543 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5544                                   const mapped_debug_names &map,
5545                                   dwarf2_section_info &section,
5546                                   bool is_dwz)
5547 {
5548   sect_offset sect_off_prev;
5549   for (uint32_t i = 0; i <= map.cu_count; ++i)
5550     {
5551       sect_offset sect_off_next;
5552       if (i < map.cu_count)
5553         {
5554           sect_off_next
5555             = (sect_offset) (extract_unsigned_integer
5556                              (map.cu_table_reordered + i * map.offset_size,
5557                               map.offset_size,
5558                               map.dwarf5_byte_order));
5559         }
5560       else
5561         sect_off_next = (sect_offset) section.size;
5562       if (i >= 1)
5563         {
5564           const ULONGEST length = sect_off_next - sect_off_prev;
5565           dwarf2_per_cu_data *per_cu
5566             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5567                                          sect_off_prev, length);
5568           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5569         }
5570       sect_off_prev = sect_off_next;
5571     }
5572 }
5573
5574 /* Read the CU list from the mapped index, and use it to create all
5575    the CU objects for this dwarf2_per_objfile.  */
5576
5577 static void
5578 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5579                              const mapped_debug_names &map,
5580                              const mapped_debug_names &dwz_map)
5581 {
5582   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5583   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5584
5585   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5586                                     dwarf2_per_objfile->info,
5587                                     false /* is_dwz */);
5588
5589   if (dwz_map.cu_count == 0)
5590     return;
5591
5592   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5593   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5594                                     true /* is_dwz */);
5595 }
5596
5597 /* Read .debug_names.  If everything went ok, initialize the "quick"
5598    elements of all the CUs and return true.  Otherwise, return false.  */
5599
5600 static bool
5601 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5602 {
5603   std::unique_ptr<mapped_debug_names> map
5604     (new mapped_debug_names (dwarf2_per_objfile));
5605   mapped_debug_names dwz_map (dwarf2_per_objfile);
5606   struct objfile *objfile = dwarf2_per_objfile->objfile;
5607
5608   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5609                                       &dwarf2_per_objfile->debug_names,
5610                                       *map))
5611     return false;
5612
5613   /* Don't use the index if it's empty.  */
5614   if (map->name_count == 0)
5615     return false;
5616
5617   /* If there is a .dwz file, read it so we can get its CU list as
5618      well.  */
5619   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5620   if (dwz != NULL)
5621     {
5622       if (!read_debug_names_from_section (objfile,
5623                                           bfd_get_filename (dwz->dwz_bfd),
5624                                           &dwz->debug_names, dwz_map))
5625         {
5626           warning (_("could not read '.debug_names' section from %s; skipping"),
5627                    bfd_get_filename (dwz->dwz_bfd));
5628           return false;
5629         }
5630     }
5631
5632   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5633
5634   if (map->tu_count != 0)
5635     {
5636       /* We can only handle a single .debug_types when we have an
5637          index.  */
5638       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5639         return false;
5640
5641       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5642                                                 dwarf2_per_objfile->types, 0);
5643
5644       create_signatured_type_table_from_debug_names
5645         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5646     }
5647
5648   create_addrmap_from_aranges (dwarf2_per_objfile,
5649                                &dwarf2_per_objfile->debug_aranges);
5650
5651   dwarf2_per_objfile->debug_names_table = std::move (map);
5652   dwarf2_per_objfile->using_index = 1;
5653   dwarf2_per_objfile->quick_file_names_table =
5654     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5655
5656   return true;
5657 }
5658
5659 /* Type used to manage iterating over all CUs looking for a symbol for
5660    .debug_names.  */
5661
5662 class dw2_debug_names_iterator
5663 {
5664 public:
5665   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5666      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5667   dw2_debug_names_iterator (const mapped_debug_names &map,
5668                             bool want_specific_block,
5669                             block_enum block_index, domain_enum domain,
5670                             const char *name)
5671     : m_map (map), m_want_specific_block (want_specific_block),
5672       m_block_index (block_index), m_domain (domain),
5673       m_addr (find_vec_in_debug_names (map, name))
5674   {}
5675
5676   dw2_debug_names_iterator (const mapped_debug_names &map,
5677                             search_domain search, uint32_t namei)
5678     : m_map (map),
5679       m_search (search),
5680       m_addr (find_vec_in_debug_names (map, namei))
5681   {}
5682
5683   /* Return the next matching CU or NULL if there are no more.  */
5684   dwarf2_per_cu_data *next ();
5685
5686 private:
5687   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5688                                                   const char *name);
5689   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5690                                                   uint32_t namei);
5691
5692   /* The internalized form of .debug_names.  */
5693   const mapped_debug_names &m_map;
5694
5695   /* If true, only look for symbols that match BLOCK_INDEX.  */
5696   const bool m_want_specific_block = false;
5697
5698   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5699      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5700      value.  */
5701   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5702
5703   /* The kind of symbol we're looking for.  */
5704   const domain_enum m_domain = UNDEF_DOMAIN;
5705   const search_domain m_search = ALL_DOMAIN;
5706
5707   /* The list of CUs from the index entry of the symbol, or NULL if
5708      not found.  */
5709   const gdb_byte *m_addr;
5710 };
5711
5712 const char *
5713 mapped_debug_names::namei_to_name (uint32_t namei) const
5714 {
5715   const ULONGEST namei_string_offs
5716     = extract_unsigned_integer ((name_table_string_offs_reordered
5717                                  + namei * offset_size),
5718                                 offset_size,
5719                                 dwarf5_byte_order);
5720   return read_indirect_string_at_offset
5721     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5722 }
5723
5724 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5725    found, return pointer to its pool data.  If NAME cannot be found,
5726    return NULL.  */
5727
5728 const gdb_byte *
5729 dw2_debug_names_iterator::find_vec_in_debug_names
5730   (const mapped_debug_names &map, const char *name)
5731 {
5732   int (*cmp) (const char *, const char *);
5733
5734   if (current_language->la_language == language_cplus
5735       || current_language->la_language == language_fortran
5736       || current_language->la_language == language_d)
5737     {
5738       /* NAME is already canonical.  Drop any qualifiers as
5739          .debug_names does not contain any.  */
5740
5741       if (strchr (name, '(') != NULL)
5742         {
5743           gdb::unique_xmalloc_ptr<char> without_params
5744             = cp_remove_params (name);
5745
5746           if (without_params != NULL)
5747             {
5748               name = without_params.get();
5749             }
5750         }
5751     }
5752
5753   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5754
5755   const uint32_t full_hash = dwarf5_djb_hash (name);
5756   uint32_t namei
5757     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5758                                 (map.bucket_table_reordered
5759                                  + (full_hash % map.bucket_count)), 4,
5760                                 map.dwarf5_byte_order);
5761   if (namei == 0)
5762     return NULL;
5763   --namei;
5764   if (namei >= map.name_count)
5765     {
5766       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5767                    "[in module %s]"),
5768                  namei, map.name_count,
5769                  objfile_name (map.dwarf2_per_objfile->objfile));
5770       return NULL;
5771     }
5772
5773   for (;;)
5774     {
5775       const uint32_t namei_full_hash
5776         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5777                                     (map.hash_table_reordered + namei), 4,
5778                                     map.dwarf5_byte_order);
5779       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5780         return NULL;
5781
5782       if (full_hash == namei_full_hash)
5783         {
5784           const char *const namei_string = map.namei_to_name (namei);
5785
5786 #if 0 /* An expensive sanity check.  */
5787           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5788             {
5789               complaint (_("Wrong .debug_names hash for string at index %u "
5790                            "[in module %s]"),
5791                          namei, objfile_name (dwarf2_per_objfile->objfile));
5792               return NULL;
5793             }
5794 #endif
5795
5796           if (cmp (namei_string, name) == 0)
5797             {
5798               const ULONGEST namei_entry_offs
5799                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5800                                              + namei * map.offset_size),
5801                                             map.offset_size, map.dwarf5_byte_order);
5802               return map.entry_pool + namei_entry_offs;
5803             }
5804         }
5805
5806       ++namei;
5807       if (namei >= map.name_count)
5808         return NULL;
5809     }
5810 }
5811
5812 const gdb_byte *
5813 dw2_debug_names_iterator::find_vec_in_debug_names
5814   (const mapped_debug_names &map, uint32_t namei)
5815 {
5816   if (namei >= map.name_count)
5817     {
5818       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5819                    "[in module %s]"),
5820                  namei, map.name_count,
5821                  objfile_name (map.dwarf2_per_objfile->objfile));
5822       return NULL;
5823     }
5824
5825   const ULONGEST namei_entry_offs
5826     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5827                                  + namei * map.offset_size),
5828                                 map.offset_size, map.dwarf5_byte_order);
5829   return map.entry_pool + namei_entry_offs;
5830 }
5831
5832 /* See dw2_debug_names_iterator.  */
5833
5834 dwarf2_per_cu_data *
5835 dw2_debug_names_iterator::next ()
5836 {
5837   if (m_addr == NULL)
5838     return NULL;
5839
5840   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5841   struct objfile *objfile = dwarf2_per_objfile->objfile;
5842   bfd *const abfd = objfile->obfd;
5843
5844  again:
5845
5846   unsigned int bytes_read;
5847   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5848   m_addr += bytes_read;
5849   if (abbrev == 0)
5850     return NULL;
5851
5852   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5853   if (indexval_it == m_map.abbrev_map.cend ())
5854     {
5855       complaint (_("Wrong .debug_names undefined abbrev code %s "
5856                    "[in module %s]"),
5857                  pulongest (abbrev), objfile_name (objfile));
5858       return NULL;
5859     }
5860   const mapped_debug_names::index_val &indexval = indexval_it->second;
5861   bool have_is_static = false;
5862   bool is_static;
5863   dwarf2_per_cu_data *per_cu = NULL;
5864   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5865     {
5866       ULONGEST ull;
5867       switch (attr.form)
5868         {
5869         case DW_FORM_implicit_const:
5870           ull = attr.implicit_const;
5871           break;
5872         case DW_FORM_flag_present:
5873           ull = 1;
5874           break;
5875         case DW_FORM_udata:
5876           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5877           m_addr += bytes_read;
5878           break;
5879         default:
5880           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5881                      dwarf_form_name (attr.form),
5882                      objfile_name (objfile));
5883           return NULL;
5884         }
5885       switch (attr.dw_idx)
5886         {
5887         case DW_IDX_compile_unit:
5888           /* Don't crash on bad data.  */
5889           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5890             {
5891               complaint (_(".debug_names entry has bad CU index %s"
5892                            " [in module %s]"),
5893                          pulongest (ull),
5894                          objfile_name (dwarf2_per_objfile->objfile));
5895               continue;
5896             }
5897           per_cu = dwarf2_per_objfile->get_cutu (ull);
5898           break;
5899         case DW_IDX_type_unit:
5900           /* Don't crash on bad data.  */
5901           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5902             {
5903               complaint (_(".debug_names entry has bad TU index %s"
5904                            " [in module %s]"),
5905                          pulongest (ull),
5906                          objfile_name (dwarf2_per_objfile->objfile));
5907               continue;
5908             }
5909           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5910           break;
5911         case DW_IDX_GNU_internal:
5912           if (!m_map.augmentation_is_gdb)
5913             break;
5914           have_is_static = true;
5915           is_static = true;
5916           break;
5917         case DW_IDX_GNU_external:
5918           if (!m_map.augmentation_is_gdb)
5919             break;
5920           have_is_static = true;
5921           is_static = false;
5922           break;
5923         }
5924     }
5925
5926   /* Skip if already read in.  */
5927   if (per_cu->v.quick->compunit_symtab)
5928     goto again;
5929
5930   /* Check static vs global.  */
5931   if (have_is_static)
5932     {
5933       const bool want_static = m_block_index != GLOBAL_BLOCK;
5934       if (m_want_specific_block && want_static != is_static)
5935         goto again;
5936     }
5937
5938   /* Match dw2_symtab_iter_next, symbol_kind
5939      and debug_names::psymbol_tag.  */
5940   switch (m_domain)
5941     {
5942     case VAR_DOMAIN:
5943       switch (indexval.dwarf_tag)
5944         {
5945         case DW_TAG_variable:
5946         case DW_TAG_subprogram:
5947         /* Some types are also in VAR_DOMAIN.  */
5948         case DW_TAG_typedef:
5949         case DW_TAG_structure_type:
5950           break;
5951         default:
5952           goto again;
5953         }
5954       break;
5955     case STRUCT_DOMAIN:
5956       switch (indexval.dwarf_tag)
5957         {
5958         case DW_TAG_typedef:
5959         case DW_TAG_structure_type:
5960           break;
5961         default:
5962           goto again;
5963         }
5964       break;
5965     case LABEL_DOMAIN:
5966       switch (indexval.dwarf_tag)
5967         {
5968         case 0:
5969         case DW_TAG_variable:
5970           break;
5971         default:
5972           goto again;
5973         }
5974       break;
5975     default:
5976       break;
5977     }
5978
5979   /* Match dw2_expand_symtabs_matching, symbol_kind and
5980      debug_names::psymbol_tag.  */
5981   switch (m_search)
5982     {
5983     case VARIABLES_DOMAIN:
5984       switch (indexval.dwarf_tag)
5985         {
5986         case DW_TAG_variable:
5987           break;
5988         default:
5989           goto again;
5990         }
5991       break;
5992     case FUNCTIONS_DOMAIN:
5993       switch (indexval.dwarf_tag)
5994         {
5995         case DW_TAG_subprogram:
5996           break;
5997         default:
5998           goto again;
5999         }
6000       break;
6001     case TYPES_DOMAIN:
6002       switch (indexval.dwarf_tag)
6003         {
6004         case DW_TAG_typedef:
6005         case DW_TAG_structure_type:
6006           break;
6007         default:
6008           goto again;
6009         }
6010       break;
6011     default:
6012       break;
6013     }
6014
6015   return per_cu;
6016 }
6017
6018 static struct compunit_symtab *
6019 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6020                                const char *name, domain_enum domain)
6021 {
6022   const block_enum block_index = static_cast<block_enum> (block_index_int);
6023   struct dwarf2_per_objfile *dwarf2_per_objfile
6024     = get_dwarf2_per_objfile (objfile);
6025
6026   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6027   if (!mapp)
6028     {
6029       /* index is NULL if OBJF_READNOW.  */
6030       return NULL;
6031     }
6032   const auto &map = *mapp;
6033
6034   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6035                                  block_index, domain, name);
6036
6037   struct compunit_symtab *stab_best = NULL;
6038   struct dwarf2_per_cu_data *per_cu;
6039   while ((per_cu = iter.next ()) != NULL)
6040     {
6041       struct symbol *sym, *with_opaque = NULL;
6042       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
6043       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6044       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6045
6046       sym = block_find_symbol (block, name, domain,
6047                                block_find_non_opaque_type_preferred,
6048                                &with_opaque);
6049
6050       /* Some caution must be observed with overloaded functions and
6051          methods, since the index will not contain any overload
6052          information (but NAME might contain it).  */
6053
6054       if (sym != NULL
6055           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6056         return stab;
6057       if (with_opaque != NULL
6058           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6059         stab_best = stab;
6060
6061       /* Keep looking through other CUs.  */
6062     }
6063
6064   return stab_best;
6065 }
6066
6067 /* This dumps minimal information about .debug_names.  It is called
6068    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6069    uses this to verify that .debug_names has been loaded.  */
6070
6071 static void
6072 dw2_debug_names_dump (struct objfile *objfile)
6073 {
6074   struct dwarf2_per_objfile *dwarf2_per_objfile
6075     = get_dwarf2_per_objfile (objfile);
6076
6077   gdb_assert (dwarf2_per_objfile->using_index);
6078   printf_filtered (".debug_names:");
6079   if (dwarf2_per_objfile->debug_names_table)
6080     printf_filtered (" exists\n");
6081   else
6082     printf_filtered (" faked for \"readnow\"\n");
6083   printf_filtered ("\n");
6084 }
6085
6086 static void
6087 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6088                                              const char *func_name)
6089 {
6090   struct dwarf2_per_objfile *dwarf2_per_objfile
6091     = get_dwarf2_per_objfile (objfile);
6092
6093   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6094   if (dwarf2_per_objfile->debug_names_table)
6095     {
6096       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6097
6098       /* Note: It doesn't matter what we pass for block_index here.  */
6099       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6100                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6101
6102       struct dwarf2_per_cu_data *per_cu;
6103       while ((per_cu = iter.next ()) != NULL)
6104         dw2_instantiate_symtab (per_cu, false);
6105     }
6106 }
6107
6108 static void
6109 dw2_debug_names_expand_symtabs_matching
6110   (struct objfile *objfile,
6111    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6112    const lookup_name_info &lookup_name,
6113    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6114    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6115    enum search_domain kind)
6116 {
6117   struct dwarf2_per_objfile *dwarf2_per_objfile
6118     = get_dwarf2_per_objfile (objfile);
6119
6120   /* debug_names_table is NULL if OBJF_READNOW.  */
6121   if (!dwarf2_per_objfile->debug_names_table)
6122     return;
6123
6124   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6125
6126   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6127
6128   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6129                                       symbol_matcher,
6130                                       kind, [&] (offset_type namei)
6131     {
6132       /* The name was matched, now expand corresponding CUs that were
6133          marked.  */
6134       dw2_debug_names_iterator iter (map, kind, namei);
6135
6136       struct dwarf2_per_cu_data *per_cu;
6137       while ((per_cu = iter.next ()) != NULL)
6138         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6139                                          expansion_notify);
6140     });
6141 }
6142
6143 const struct quick_symbol_functions dwarf2_debug_names_functions =
6144 {
6145   dw2_has_symbols,
6146   dw2_find_last_source_symtab,
6147   dw2_forget_cached_source_info,
6148   dw2_map_symtabs_matching_filename,
6149   dw2_debug_names_lookup_symbol,
6150   dw2_print_stats,
6151   dw2_debug_names_dump,
6152   dw2_relocate,
6153   dw2_debug_names_expand_symtabs_for_function,
6154   dw2_expand_all_symtabs,
6155   dw2_expand_symtabs_with_fullname,
6156   dw2_map_matching_symbols,
6157   dw2_debug_names_expand_symtabs_matching,
6158   dw2_find_pc_sect_compunit_symtab,
6159   NULL,
6160   dw2_map_symbol_filenames
6161 };
6162
6163 /* See symfile.h.  */
6164
6165 bool
6166 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6167 {
6168   struct dwarf2_per_objfile *dwarf2_per_objfile
6169     = get_dwarf2_per_objfile (objfile);
6170
6171   /* If we're about to read full symbols, don't bother with the
6172      indices.  In this case we also don't care if some other debug
6173      format is making psymtabs, because they are all about to be
6174      expanded anyway.  */
6175   if ((objfile->flags & OBJF_READNOW))
6176     {
6177       dwarf2_per_objfile->using_index = 1;
6178       create_all_comp_units (dwarf2_per_objfile);
6179       create_all_type_units (dwarf2_per_objfile);
6180       dwarf2_per_objfile->quick_file_names_table
6181         = create_quick_file_names_table
6182             (dwarf2_per_objfile->all_comp_units.size ());
6183
6184       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6185                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6186         {
6187           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6188
6189           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6190                                             struct dwarf2_per_cu_quick_data);
6191         }
6192
6193       /* Return 1 so that gdb sees the "quick" functions.  However,
6194          these functions will be no-ops because we will have expanded
6195          all symtabs.  */
6196       *index_kind = dw_index_kind::GDB_INDEX;
6197       return true;
6198     }
6199
6200   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6201     {
6202       *index_kind = dw_index_kind::DEBUG_NAMES;
6203       return true;
6204     }
6205
6206   if (dwarf2_read_gdb_index (dwarf2_per_objfile))
6207     {
6208       *index_kind = dw_index_kind::GDB_INDEX;
6209       return true;
6210     }
6211
6212   return false;
6213 }
6214
6215 \f
6216
6217 /* Build a partial symbol table.  */
6218
6219 void
6220 dwarf2_build_psymtabs (struct objfile *objfile)
6221 {
6222   struct dwarf2_per_objfile *dwarf2_per_objfile
6223     = get_dwarf2_per_objfile (objfile);
6224
6225   if (objfile->global_psymbols.capacity () == 0
6226       && objfile->static_psymbols.capacity () == 0)
6227     init_psymbol_list (objfile, 1024);
6228
6229   TRY
6230     {
6231       /* This isn't really ideal: all the data we allocate on the
6232          objfile's obstack is still uselessly kept around.  However,
6233          freeing it seems unsafe.  */
6234       psymtab_discarder psymtabs (objfile);
6235       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6236       psymtabs.keep ();
6237     }
6238   CATCH (except, RETURN_MASK_ERROR)
6239     {
6240       exception_print (gdb_stderr, except);
6241     }
6242   END_CATCH
6243 }
6244
6245 /* Return the total length of the CU described by HEADER.  */
6246
6247 static unsigned int
6248 get_cu_length (const struct comp_unit_head *header)
6249 {
6250   return header->initial_length_size + header->length;
6251 }
6252
6253 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6254
6255 static inline bool
6256 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6257 {
6258   sect_offset bottom = cu_header->sect_off;
6259   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6260
6261   return sect_off >= bottom && sect_off < top;
6262 }
6263
6264 /* Find the base address of the compilation unit for range lists and
6265    location lists.  It will normally be specified by DW_AT_low_pc.
6266    In DWARF-3 draft 4, the base address could be overridden by
6267    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6268    compilation units with discontinuous ranges.  */
6269
6270 static void
6271 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6272 {
6273   struct attribute *attr;
6274
6275   cu->base_known = 0;
6276   cu->base_address = 0;
6277
6278   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6279   if (attr)
6280     {
6281       cu->base_address = attr_value_as_address (attr);
6282       cu->base_known = 1;
6283     }
6284   else
6285     {
6286       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6287       if (attr)
6288         {
6289           cu->base_address = attr_value_as_address (attr);
6290           cu->base_known = 1;
6291         }
6292     }
6293 }
6294
6295 /* Read in the comp unit header information from the debug_info at info_ptr.
6296    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6297    NOTE: This leaves members offset, first_die_offset to be filled in
6298    by the caller.  */
6299
6300 static const gdb_byte *
6301 read_comp_unit_head (struct comp_unit_head *cu_header,
6302                      const gdb_byte *info_ptr,
6303                      struct dwarf2_section_info *section,
6304                      rcuh_kind section_kind)
6305 {
6306   int signed_addr;
6307   unsigned int bytes_read;
6308   const char *filename = get_section_file_name (section);
6309   bfd *abfd = get_section_bfd_owner (section);
6310
6311   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6312   cu_header->initial_length_size = bytes_read;
6313   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6314   info_ptr += bytes_read;
6315   cu_header->version = read_2_bytes (abfd, info_ptr);
6316   if (cu_header->version < 2 || cu_header->version > 5)
6317     error (_("Dwarf Error: wrong version in compilation unit header "
6318            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6319            cu_header->version, filename);
6320   info_ptr += 2;
6321   if (cu_header->version < 5)
6322     switch (section_kind)
6323       {
6324       case rcuh_kind::COMPILE:
6325         cu_header->unit_type = DW_UT_compile;
6326         break;
6327       case rcuh_kind::TYPE:
6328         cu_header->unit_type = DW_UT_type;
6329         break;
6330       default:
6331         internal_error (__FILE__, __LINE__,
6332                         _("read_comp_unit_head: invalid section_kind"));
6333       }
6334   else
6335     {
6336       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6337                                                  (read_1_byte (abfd, info_ptr));
6338       info_ptr += 1;
6339       switch (cu_header->unit_type)
6340         {
6341         case DW_UT_compile:
6342           if (section_kind != rcuh_kind::COMPILE)
6343             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6344                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6345                    filename);
6346           break;
6347         case DW_UT_type:
6348           section_kind = rcuh_kind::TYPE;
6349           break;
6350         default:
6351           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6352                  "(is %d, should be %d or %d) [in module %s]"),
6353                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6354         }
6355
6356       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6357       info_ptr += 1;
6358     }
6359   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6360                                                           cu_header,
6361                                                           &bytes_read);
6362   info_ptr += bytes_read;
6363   if (cu_header->version < 5)
6364     {
6365       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6366       info_ptr += 1;
6367     }
6368   signed_addr = bfd_get_sign_extend_vma (abfd);
6369   if (signed_addr < 0)
6370     internal_error (__FILE__, __LINE__,
6371                     _("read_comp_unit_head: dwarf from non elf file"));
6372   cu_header->signed_addr_p = signed_addr;
6373
6374   if (section_kind == rcuh_kind::TYPE)
6375     {
6376       LONGEST type_offset;
6377
6378       cu_header->signature = read_8_bytes (abfd, info_ptr);
6379       info_ptr += 8;
6380
6381       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6382       info_ptr += bytes_read;
6383       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6384       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6385         error (_("Dwarf Error: Too big type_offset in compilation unit "
6386                "header (is %s) [in module %s]"), plongest (type_offset),
6387                filename);
6388     }
6389
6390   return info_ptr;
6391 }
6392
6393 /* Helper function that returns the proper abbrev section for
6394    THIS_CU.  */
6395
6396 static struct dwarf2_section_info *
6397 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6398 {
6399   struct dwarf2_section_info *abbrev;
6400   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6401
6402   if (this_cu->is_dwz)
6403     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6404   else
6405     abbrev = &dwarf2_per_objfile->abbrev;
6406
6407   return abbrev;
6408 }
6409
6410 /* Subroutine of read_and_check_comp_unit_head and
6411    read_and_check_type_unit_head to simplify them.
6412    Perform various error checking on the header.  */
6413
6414 static void
6415 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6416                             struct comp_unit_head *header,
6417                             struct dwarf2_section_info *section,
6418                             struct dwarf2_section_info *abbrev_section)
6419 {
6420   const char *filename = get_section_file_name (section);
6421
6422   if (to_underlying (header->abbrev_sect_off)
6423       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6424     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6425            "(offset %s + 6) [in module %s]"),
6426            sect_offset_str (header->abbrev_sect_off),
6427            sect_offset_str (header->sect_off),
6428            filename);
6429
6430   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6431      avoid potential 32-bit overflow.  */
6432   if (((ULONGEST) header->sect_off + get_cu_length (header))
6433       > section->size)
6434     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6435            "(offset %s + 0) [in module %s]"),
6436            header->length, sect_offset_str (header->sect_off),
6437            filename);
6438 }
6439
6440 /* Read in a CU/TU header and perform some basic error checking.
6441    The contents of the header are stored in HEADER.
6442    The result is a pointer to the start of the first DIE.  */
6443
6444 static const gdb_byte *
6445 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6446                                struct comp_unit_head *header,
6447                                struct dwarf2_section_info *section,
6448                                struct dwarf2_section_info *abbrev_section,
6449                                const gdb_byte *info_ptr,
6450                                rcuh_kind section_kind)
6451 {
6452   const gdb_byte *beg_of_comp_unit = info_ptr;
6453
6454   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6455
6456   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6457
6458   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6459
6460   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6461                               abbrev_section);
6462
6463   return info_ptr;
6464 }
6465
6466 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6467
6468 static sect_offset
6469 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6470                     struct dwarf2_section_info *section,
6471                     sect_offset sect_off)
6472 {
6473   bfd *abfd = get_section_bfd_owner (section);
6474   const gdb_byte *info_ptr;
6475   unsigned int initial_length_size, offset_size;
6476   uint16_t version;
6477
6478   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6479   info_ptr = section->buffer + to_underlying (sect_off);
6480   read_initial_length (abfd, info_ptr, &initial_length_size);
6481   offset_size = initial_length_size == 4 ? 4 : 8;
6482   info_ptr += initial_length_size;
6483
6484   version = read_2_bytes (abfd, info_ptr);
6485   info_ptr += 2;
6486   if (version >= 5)
6487     {
6488       /* Skip unit type and address size.  */
6489       info_ptr += 2;
6490     }
6491
6492   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6493 }
6494
6495 /* Allocate a new partial symtab for file named NAME and mark this new
6496    partial symtab as being an include of PST.  */
6497
6498 static void
6499 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6500                                struct objfile *objfile)
6501 {
6502   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6503
6504   if (!IS_ABSOLUTE_PATH (subpst->filename))
6505     {
6506       /* It shares objfile->objfile_obstack.  */
6507       subpst->dirname = pst->dirname;
6508     }
6509
6510   subpst->textlow = 0;
6511   subpst->texthigh = 0;
6512
6513   subpst->dependencies
6514     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6515   subpst->dependencies[0] = pst;
6516   subpst->number_of_dependencies = 1;
6517
6518   subpst->globals_offset = 0;
6519   subpst->n_global_syms = 0;
6520   subpst->statics_offset = 0;
6521   subpst->n_static_syms = 0;
6522   subpst->compunit_symtab = NULL;
6523   subpst->read_symtab = pst->read_symtab;
6524   subpst->readin = 0;
6525
6526   /* No private part is necessary for include psymtabs.  This property
6527      can be used to differentiate between such include psymtabs and
6528      the regular ones.  */
6529   subpst->read_symtab_private = NULL;
6530 }
6531
6532 /* Read the Line Number Program data and extract the list of files
6533    included by the source file represented by PST.  Build an include
6534    partial symtab for each of these included files.  */
6535
6536 static void
6537 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6538                                struct die_info *die,
6539                                struct partial_symtab *pst)
6540 {
6541   line_header_up lh;
6542   struct attribute *attr;
6543
6544   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6545   if (attr)
6546     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6547   if (lh == NULL)
6548     return;  /* No linetable, so no includes.  */
6549
6550   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6551   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6552 }
6553
6554 static hashval_t
6555 hash_signatured_type (const void *item)
6556 {
6557   const struct signatured_type *sig_type
6558     = (const struct signatured_type *) item;
6559
6560   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6561   return sig_type->signature;
6562 }
6563
6564 static int
6565 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6566 {
6567   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6568   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6569
6570   return lhs->signature == rhs->signature;
6571 }
6572
6573 /* Allocate a hash table for signatured types.  */
6574
6575 static htab_t
6576 allocate_signatured_type_table (struct objfile *objfile)
6577 {
6578   return htab_create_alloc_ex (41,
6579                                hash_signatured_type,
6580                                eq_signatured_type,
6581                                NULL,
6582                                &objfile->objfile_obstack,
6583                                hashtab_obstack_allocate,
6584                                dummy_obstack_deallocate);
6585 }
6586
6587 /* A helper function to add a signatured type CU to a table.  */
6588
6589 static int
6590 add_signatured_type_cu_to_table (void **slot, void *datum)
6591 {
6592   struct signatured_type *sigt = (struct signatured_type *) *slot;
6593   std::vector<signatured_type *> *all_type_units
6594     = (std::vector<signatured_type *> *) datum;
6595
6596   all_type_units->push_back (sigt);
6597
6598   return 1;
6599 }
6600
6601 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6602    and fill them into TYPES_HTAB.  It will process only type units,
6603    therefore DW_UT_type.  */
6604
6605 static void
6606 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6607                               struct dwo_file *dwo_file,
6608                               dwarf2_section_info *section, htab_t &types_htab,
6609                               rcuh_kind section_kind)
6610 {
6611   struct objfile *objfile = dwarf2_per_objfile->objfile;
6612   struct dwarf2_section_info *abbrev_section;
6613   bfd *abfd;
6614   const gdb_byte *info_ptr, *end_ptr;
6615
6616   abbrev_section = (dwo_file != NULL
6617                     ? &dwo_file->sections.abbrev
6618                     : &dwarf2_per_objfile->abbrev);
6619
6620   if (dwarf_read_debug)
6621     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6622                         get_section_name (section),
6623                         get_section_file_name (abbrev_section));
6624
6625   dwarf2_read_section (objfile, section);
6626   info_ptr = section->buffer;
6627
6628   if (info_ptr == NULL)
6629     return;
6630
6631   /* We can't set abfd until now because the section may be empty or
6632      not present, in which case the bfd is unknown.  */
6633   abfd = get_section_bfd_owner (section);
6634
6635   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6636      because we don't need to read any dies: the signature is in the
6637      header.  */
6638
6639   end_ptr = info_ptr + section->size;
6640   while (info_ptr < end_ptr)
6641     {
6642       struct signatured_type *sig_type;
6643       struct dwo_unit *dwo_tu;
6644       void **slot;
6645       const gdb_byte *ptr = info_ptr;
6646       struct comp_unit_head header;
6647       unsigned int length;
6648
6649       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6650
6651       /* Initialize it due to a false compiler warning.  */
6652       header.signature = -1;
6653       header.type_cu_offset_in_tu = (cu_offset) -1;
6654
6655       /* We need to read the type's signature in order to build the hash
6656          table, but we don't need anything else just yet.  */
6657
6658       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6659                                            abbrev_section, ptr, section_kind);
6660
6661       length = get_cu_length (&header);
6662
6663       /* Skip dummy type units.  */
6664       if (ptr >= info_ptr + length
6665           || peek_abbrev_code (abfd, ptr) == 0
6666           || header.unit_type != DW_UT_type)
6667         {
6668           info_ptr += length;
6669           continue;
6670         }
6671
6672       if (types_htab == NULL)
6673         {
6674           if (dwo_file)
6675             types_htab = allocate_dwo_unit_table (objfile);
6676           else
6677             types_htab = allocate_signatured_type_table (objfile);
6678         }
6679
6680       if (dwo_file)
6681         {
6682           sig_type = NULL;
6683           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6684                                    struct dwo_unit);
6685           dwo_tu->dwo_file = dwo_file;
6686           dwo_tu->signature = header.signature;
6687           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6688           dwo_tu->section = section;
6689           dwo_tu->sect_off = sect_off;
6690           dwo_tu->length = length;
6691         }
6692       else
6693         {
6694           /* N.B.: type_offset is not usable if this type uses a DWO file.
6695              The real type_offset is in the DWO file.  */
6696           dwo_tu = NULL;
6697           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6698                                      struct signatured_type);
6699           sig_type->signature = header.signature;
6700           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6701           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6702           sig_type->per_cu.is_debug_types = 1;
6703           sig_type->per_cu.section = section;
6704           sig_type->per_cu.sect_off = sect_off;
6705           sig_type->per_cu.length = length;
6706         }
6707
6708       slot = htab_find_slot (types_htab,
6709                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6710                              INSERT);
6711       gdb_assert (slot != NULL);
6712       if (*slot != NULL)
6713         {
6714           sect_offset dup_sect_off;
6715
6716           if (dwo_file)
6717             {
6718               const struct dwo_unit *dup_tu
6719                 = (const struct dwo_unit *) *slot;
6720
6721               dup_sect_off = dup_tu->sect_off;
6722             }
6723           else
6724             {
6725               const struct signatured_type *dup_tu
6726                 = (const struct signatured_type *) *slot;
6727
6728               dup_sect_off = dup_tu->per_cu.sect_off;
6729             }
6730
6731           complaint (_("debug type entry at offset %s is duplicate to"
6732                        " the entry at offset %s, signature %s"),
6733                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6734                      hex_string (header.signature));
6735         }
6736       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6737
6738       if (dwarf_read_debug > 1)
6739         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6740                             sect_offset_str (sect_off),
6741                             hex_string (header.signature));
6742
6743       info_ptr += length;
6744     }
6745 }
6746
6747 /* Create the hash table of all entries in the .debug_types
6748    (or .debug_types.dwo) section(s).
6749    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6750    otherwise it is NULL.
6751
6752    The result is a pointer to the hash table or NULL if there are no types.
6753
6754    Note: This function processes DWO files only, not DWP files.  */
6755
6756 static void
6757 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6758                                struct dwo_file *dwo_file,
6759                                VEC (dwarf2_section_info_def) *types,
6760                                htab_t &types_htab)
6761 {
6762   int ix;
6763   struct dwarf2_section_info *section;
6764
6765   if (VEC_empty (dwarf2_section_info_def, types))
6766     return;
6767
6768   for (ix = 0;
6769        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6770        ++ix)
6771     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6772                                   types_htab, rcuh_kind::TYPE);
6773 }
6774
6775 /* Create the hash table of all entries in the .debug_types section,
6776    and initialize all_type_units.
6777    The result is zero if there is an error (e.g. missing .debug_types section),
6778    otherwise non-zero.  */
6779
6780 static int
6781 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6782 {
6783   htab_t types_htab = NULL;
6784
6785   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6786                                 &dwarf2_per_objfile->info, types_htab,
6787                                 rcuh_kind::COMPILE);
6788   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6789                                  dwarf2_per_objfile->types, types_htab);
6790   if (types_htab == NULL)
6791     {
6792       dwarf2_per_objfile->signatured_types = NULL;
6793       return 0;
6794     }
6795
6796   dwarf2_per_objfile->signatured_types = types_htab;
6797
6798   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6799   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6800
6801   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6802                           &dwarf2_per_objfile->all_type_units);
6803
6804   return 1;
6805 }
6806
6807 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6808    If SLOT is non-NULL, it is the entry to use in the hash table.
6809    Otherwise we find one.  */
6810
6811 static struct signatured_type *
6812 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6813                void **slot)
6814 {
6815   struct objfile *objfile = dwarf2_per_objfile->objfile;
6816
6817   if (dwarf2_per_objfile->all_type_units.size ()
6818       == dwarf2_per_objfile->all_type_units.capacity ())
6819     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6820
6821   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6822                                               struct signatured_type);
6823
6824   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6825   sig_type->signature = sig;
6826   sig_type->per_cu.is_debug_types = 1;
6827   if (dwarf2_per_objfile->using_index)
6828     {
6829       sig_type->per_cu.v.quick =
6830         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6831                         struct dwarf2_per_cu_quick_data);
6832     }
6833
6834   if (slot == NULL)
6835     {
6836       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6837                              sig_type, INSERT);
6838     }
6839   gdb_assert (*slot == NULL);
6840   *slot = sig_type;
6841   /* The rest of sig_type must be filled in by the caller.  */
6842   return sig_type;
6843 }
6844
6845 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6846    Fill in SIG_ENTRY with DWO_ENTRY.  */
6847
6848 static void
6849 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6850                                   struct signatured_type *sig_entry,
6851                                   struct dwo_unit *dwo_entry)
6852 {
6853   /* Make sure we're not clobbering something we don't expect to.  */
6854   gdb_assert (! sig_entry->per_cu.queued);
6855   gdb_assert (sig_entry->per_cu.cu == NULL);
6856   if (dwarf2_per_objfile->using_index)
6857     {
6858       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6859       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6860     }
6861   else
6862       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6863   gdb_assert (sig_entry->signature == dwo_entry->signature);
6864   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6865   gdb_assert (sig_entry->type_unit_group == NULL);
6866   gdb_assert (sig_entry->dwo_unit == NULL);
6867
6868   sig_entry->per_cu.section = dwo_entry->section;
6869   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6870   sig_entry->per_cu.length = dwo_entry->length;
6871   sig_entry->per_cu.reading_dwo_directly = 1;
6872   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6873   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6874   sig_entry->dwo_unit = dwo_entry;
6875 }
6876
6877 /* Subroutine of lookup_signatured_type.
6878    If we haven't read the TU yet, create the signatured_type data structure
6879    for a TU to be read in directly from a DWO file, bypassing the stub.
6880    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6881    using .gdb_index, then when reading a CU we want to stay in the DWO file
6882    containing that CU.  Otherwise we could end up reading several other DWO
6883    files (due to comdat folding) to process the transitive closure of all the
6884    mentioned TUs, and that can be slow.  The current DWO file will have every
6885    type signature that it needs.
6886    We only do this for .gdb_index because in the psymtab case we already have
6887    to read all the DWOs to build the type unit groups.  */
6888
6889 static struct signatured_type *
6890 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6891 {
6892   struct dwarf2_per_objfile *dwarf2_per_objfile
6893     = cu->per_cu->dwarf2_per_objfile;
6894   struct objfile *objfile = dwarf2_per_objfile->objfile;
6895   struct dwo_file *dwo_file;
6896   struct dwo_unit find_dwo_entry, *dwo_entry;
6897   struct signatured_type find_sig_entry, *sig_entry;
6898   void **slot;
6899
6900   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6901
6902   /* If TU skeletons have been removed then we may not have read in any
6903      TUs yet.  */
6904   if (dwarf2_per_objfile->signatured_types == NULL)
6905     {
6906       dwarf2_per_objfile->signatured_types
6907         = allocate_signatured_type_table (objfile);
6908     }
6909
6910   /* We only ever need to read in one copy of a signatured type.
6911      Use the global signatured_types array to do our own comdat-folding
6912      of types.  If this is the first time we're reading this TU, and
6913      the TU has an entry in .gdb_index, replace the recorded data from
6914      .gdb_index with this TU.  */
6915
6916   find_sig_entry.signature = sig;
6917   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6918                          &find_sig_entry, INSERT);
6919   sig_entry = (struct signatured_type *) *slot;
6920
6921   /* We can get here with the TU already read, *or* in the process of being
6922      read.  Don't reassign the global entry to point to this DWO if that's
6923      the case.  Also note that if the TU is already being read, it may not
6924      have come from a DWO, the program may be a mix of Fission-compiled
6925      code and non-Fission-compiled code.  */
6926
6927   /* Have we already tried to read this TU?
6928      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6929      needn't exist in the global table yet).  */
6930   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6931     return sig_entry;
6932
6933   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6934      dwo_unit of the TU itself.  */
6935   dwo_file = cu->dwo_unit->dwo_file;
6936
6937   /* Ok, this is the first time we're reading this TU.  */
6938   if (dwo_file->tus == NULL)
6939     return NULL;
6940   find_dwo_entry.signature = sig;
6941   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
6942   if (dwo_entry == NULL)
6943     return NULL;
6944
6945   /* If the global table doesn't have an entry for this TU, add one.  */
6946   if (sig_entry == NULL)
6947     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6948
6949   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6950   sig_entry->per_cu.tu_read = 1;
6951   return sig_entry;
6952 }
6953
6954 /* Subroutine of lookup_signatured_type.
6955    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6956    then try the DWP file.  If the TU stub (skeleton) has been removed then
6957    it won't be in .gdb_index.  */
6958
6959 static struct signatured_type *
6960 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6961 {
6962   struct dwarf2_per_objfile *dwarf2_per_objfile
6963     = cu->per_cu->dwarf2_per_objfile;
6964   struct objfile *objfile = dwarf2_per_objfile->objfile;
6965   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
6966   struct dwo_unit *dwo_entry;
6967   struct signatured_type find_sig_entry, *sig_entry;
6968   void **slot;
6969
6970   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6971   gdb_assert (dwp_file != NULL);
6972
6973   /* If TU skeletons have been removed then we may not have read in any
6974      TUs yet.  */
6975   if (dwarf2_per_objfile->signatured_types == NULL)
6976     {
6977       dwarf2_per_objfile->signatured_types
6978         = allocate_signatured_type_table (objfile);
6979     }
6980
6981   find_sig_entry.signature = sig;
6982   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6983                          &find_sig_entry, INSERT);
6984   sig_entry = (struct signatured_type *) *slot;
6985
6986   /* Have we already tried to read this TU?
6987      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6988      needn't exist in the global table yet).  */
6989   if (sig_entry != NULL)
6990     return sig_entry;
6991
6992   if (dwp_file->tus == NULL)
6993     return NULL;
6994   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
6995                                       sig, 1 /* is_debug_types */);
6996   if (dwo_entry == NULL)
6997     return NULL;
6998
6999   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7000   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7001
7002   return sig_entry;
7003 }
7004
7005 /* Lookup a signature based type for DW_FORM_ref_sig8.
7006    Returns NULL if signature SIG is not present in the table.
7007    It is up to the caller to complain about this.  */
7008
7009 static struct signatured_type *
7010 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7011 {
7012   struct dwarf2_per_objfile *dwarf2_per_objfile
7013     = cu->per_cu->dwarf2_per_objfile;
7014
7015   if (cu->dwo_unit
7016       && dwarf2_per_objfile->using_index)
7017     {
7018       /* We're in a DWO/DWP file, and we're using .gdb_index.
7019          These cases require special processing.  */
7020       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7021         return lookup_dwo_signatured_type (cu, sig);
7022       else
7023         return lookup_dwp_signatured_type (cu, sig);
7024     }
7025   else
7026     {
7027       struct signatured_type find_entry, *entry;
7028
7029       if (dwarf2_per_objfile->signatured_types == NULL)
7030         return NULL;
7031       find_entry.signature = sig;
7032       entry = ((struct signatured_type *)
7033                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7034       return entry;
7035     }
7036 }
7037 \f
7038 /* Low level DIE reading support.  */
7039
7040 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7041
7042 static void
7043 init_cu_die_reader (struct die_reader_specs *reader,
7044                     struct dwarf2_cu *cu,
7045                     struct dwarf2_section_info *section,
7046                     struct dwo_file *dwo_file,
7047                     struct abbrev_table *abbrev_table)
7048 {
7049   gdb_assert (section->readin && section->buffer != NULL);
7050   reader->abfd = get_section_bfd_owner (section);
7051   reader->cu = cu;
7052   reader->dwo_file = dwo_file;
7053   reader->die_section = section;
7054   reader->buffer = section->buffer;
7055   reader->buffer_end = section->buffer + section->size;
7056   reader->comp_dir = NULL;
7057   reader->abbrev_table = abbrev_table;
7058 }
7059
7060 /* Subroutine of init_cutu_and_read_dies to simplify it.
7061    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7062    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7063    already.
7064
7065    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7066    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7067    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7068    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7069    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7070    STUB_COMP_DIR may be non-NULL.
7071    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7072    are filled in with the info of the DIE from the DWO file.
7073    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7074    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7075    kept around for at least as long as *RESULT_READER.
7076
7077    The result is non-zero if a valid (non-dummy) DIE was found.  */
7078
7079 static int
7080 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7081                         struct dwo_unit *dwo_unit,
7082                         struct die_info *stub_comp_unit_die,
7083                         const char *stub_comp_dir,
7084                         struct die_reader_specs *result_reader,
7085                         const gdb_byte **result_info_ptr,
7086                         struct die_info **result_comp_unit_die,
7087                         int *result_has_children,
7088                         abbrev_table_up *result_dwo_abbrev_table)
7089 {
7090   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7091   struct objfile *objfile = dwarf2_per_objfile->objfile;
7092   struct dwarf2_cu *cu = this_cu->cu;
7093   bfd *abfd;
7094   const gdb_byte *begin_info_ptr, *info_ptr;
7095   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7096   int i,num_extra_attrs;
7097   struct dwarf2_section_info *dwo_abbrev_section;
7098   struct attribute *attr;
7099   struct die_info *comp_unit_die;
7100
7101   /* At most one of these may be provided.  */
7102   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7103
7104   /* These attributes aren't processed until later:
7105      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7106      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7107      referenced later.  However, these attributes are found in the stub
7108      which we won't have later.  In order to not impose this complication
7109      on the rest of the code, we read them here and copy them to the
7110      DWO CU/TU die.  */
7111
7112   stmt_list = NULL;
7113   low_pc = NULL;
7114   high_pc = NULL;
7115   ranges = NULL;
7116   comp_dir = NULL;
7117
7118   if (stub_comp_unit_die != NULL)
7119     {
7120       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7121          DWO file.  */
7122       if (! this_cu->is_debug_types)
7123         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7124       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7125       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7126       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7127       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7128
7129       /* There should be a DW_AT_addr_base attribute here (if needed).
7130          We need the value before we can process DW_FORM_GNU_addr_index.  */
7131       cu->addr_base = 0;
7132       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7133       if (attr)
7134         cu->addr_base = DW_UNSND (attr);
7135
7136       /* There should be a DW_AT_ranges_base attribute here (if needed).
7137          We need the value before we can process DW_AT_ranges.  */
7138       cu->ranges_base = 0;
7139       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7140       if (attr)
7141         cu->ranges_base = DW_UNSND (attr);
7142     }
7143   else if (stub_comp_dir != NULL)
7144     {
7145       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7146       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7147       comp_dir->name = DW_AT_comp_dir;
7148       comp_dir->form = DW_FORM_string;
7149       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7150       DW_STRING (comp_dir) = stub_comp_dir;
7151     }
7152
7153   /* Set up for reading the DWO CU/TU.  */
7154   cu->dwo_unit = dwo_unit;
7155   dwarf2_section_info *section = dwo_unit->section;
7156   dwarf2_read_section (objfile, section);
7157   abfd = get_section_bfd_owner (section);
7158   begin_info_ptr = info_ptr = (section->buffer
7159                                + to_underlying (dwo_unit->sect_off));
7160   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7161
7162   if (this_cu->is_debug_types)
7163     {
7164       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7165
7166       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7167                                                 &cu->header, section,
7168                                                 dwo_abbrev_section,
7169                                                 info_ptr, rcuh_kind::TYPE);
7170       /* This is not an assert because it can be caused by bad debug info.  */
7171       if (sig_type->signature != cu->header.signature)
7172         {
7173           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7174                    " TU at offset %s [in module %s]"),
7175                  hex_string (sig_type->signature),
7176                  hex_string (cu->header.signature),
7177                  sect_offset_str (dwo_unit->sect_off),
7178                  bfd_get_filename (abfd));
7179         }
7180       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7181       /* For DWOs coming from DWP files, we don't know the CU length
7182          nor the type's offset in the TU until now.  */
7183       dwo_unit->length = get_cu_length (&cu->header);
7184       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7185
7186       /* Establish the type offset that can be used to lookup the type.
7187          For DWO files, we don't know it until now.  */
7188       sig_type->type_offset_in_section
7189         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7190     }
7191   else
7192     {
7193       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7194                                                 &cu->header, section,
7195                                                 dwo_abbrev_section,
7196                                                 info_ptr, rcuh_kind::COMPILE);
7197       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7198       /* For DWOs coming from DWP files, we don't know the CU length
7199          until now.  */
7200       dwo_unit->length = get_cu_length (&cu->header);
7201     }
7202
7203   *result_dwo_abbrev_table
7204     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7205                                cu->header.abbrev_sect_off);
7206   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7207                       result_dwo_abbrev_table->get ());
7208
7209   /* Read in the die, but leave space to copy over the attributes
7210      from the stub.  This has the benefit of simplifying the rest of
7211      the code - all the work to maintain the illusion of a single
7212      DW_TAG_{compile,type}_unit DIE is done here.  */
7213   num_extra_attrs = ((stmt_list != NULL)
7214                      + (low_pc != NULL)
7215                      + (high_pc != NULL)
7216                      + (ranges != NULL)
7217                      + (comp_dir != NULL));
7218   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7219                               result_has_children, num_extra_attrs);
7220
7221   /* Copy over the attributes from the stub to the DIE we just read in.  */
7222   comp_unit_die = *result_comp_unit_die;
7223   i = comp_unit_die->num_attrs;
7224   if (stmt_list != NULL)
7225     comp_unit_die->attrs[i++] = *stmt_list;
7226   if (low_pc != NULL)
7227     comp_unit_die->attrs[i++] = *low_pc;
7228   if (high_pc != NULL)
7229     comp_unit_die->attrs[i++] = *high_pc;
7230   if (ranges != NULL)
7231     comp_unit_die->attrs[i++] = *ranges;
7232   if (comp_dir != NULL)
7233     comp_unit_die->attrs[i++] = *comp_dir;
7234   comp_unit_die->num_attrs += num_extra_attrs;
7235
7236   if (dwarf_die_debug)
7237     {
7238       fprintf_unfiltered (gdb_stdlog,
7239                           "Read die from %s@0x%x of %s:\n",
7240                           get_section_name (section),
7241                           (unsigned) (begin_info_ptr - section->buffer),
7242                           bfd_get_filename (abfd));
7243       dump_die (comp_unit_die, dwarf_die_debug);
7244     }
7245
7246   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7247      TUs by skipping the stub and going directly to the entry in the DWO file.
7248      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7249      to get it via circuitous means.  Blech.  */
7250   if (comp_dir != NULL)
7251     result_reader->comp_dir = DW_STRING (comp_dir);
7252
7253   /* Skip dummy compilation units.  */
7254   if (info_ptr >= begin_info_ptr + dwo_unit->length
7255       || peek_abbrev_code (abfd, info_ptr) == 0)
7256     return 0;
7257
7258   *result_info_ptr = info_ptr;
7259   return 1;
7260 }
7261
7262 /* Subroutine of init_cutu_and_read_dies to simplify it.
7263    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7264    Returns NULL if the specified DWO unit cannot be found.  */
7265
7266 static struct dwo_unit *
7267 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7268                  struct die_info *comp_unit_die)
7269 {
7270   struct dwarf2_cu *cu = this_cu->cu;
7271   ULONGEST signature;
7272   struct dwo_unit *dwo_unit;
7273   const char *comp_dir, *dwo_name;
7274
7275   gdb_assert (cu != NULL);
7276
7277   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7278   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7279   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7280
7281   if (this_cu->is_debug_types)
7282     {
7283       struct signatured_type *sig_type;
7284
7285       /* Since this_cu is the first member of struct signatured_type,
7286          we can go from a pointer to one to a pointer to the other.  */
7287       sig_type = (struct signatured_type *) this_cu;
7288       signature = sig_type->signature;
7289       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7290     }
7291   else
7292     {
7293       struct attribute *attr;
7294
7295       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7296       if (! attr)
7297         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7298                  " [in module %s]"),
7299                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7300       signature = DW_UNSND (attr);
7301       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7302                                        signature);
7303     }
7304
7305   return dwo_unit;
7306 }
7307
7308 /* Subroutine of init_cutu_and_read_dies to simplify it.
7309    See it for a description of the parameters.
7310    Read a TU directly from a DWO file, bypassing the stub.  */
7311
7312 static void
7313 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7314                            int use_existing_cu, int keep,
7315                            die_reader_func_ftype *die_reader_func,
7316                            void *data)
7317 {
7318   std::unique_ptr<dwarf2_cu> new_cu;
7319   struct signatured_type *sig_type;
7320   struct die_reader_specs reader;
7321   const gdb_byte *info_ptr;
7322   struct die_info *comp_unit_die;
7323   int has_children;
7324   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7325
7326   /* Verify we can do the following downcast, and that we have the
7327      data we need.  */
7328   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7329   sig_type = (struct signatured_type *) this_cu;
7330   gdb_assert (sig_type->dwo_unit != NULL);
7331
7332   if (use_existing_cu && this_cu->cu != NULL)
7333     {
7334       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7335       /* There's no need to do the rereading_dwo_cu handling that
7336          init_cutu_and_read_dies does since we don't read the stub.  */
7337     }
7338   else
7339     {
7340       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7341       gdb_assert (this_cu->cu == NULL);
7342       new_cu.reset (new dwarf2_cu (this_cu));
7343     }
7344
7345   /* A future optimization, if needed, would be to use an existing
7346      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7347      could share abbrev tables.  */
7348
7349   /* The abbreviation table used by READER, this must live at least as long as
7350      READER.  */
7351   abbrev_table_up dwo_abbrev_table;
7352
7353   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7354                               NULL /* stub_comp_unit_die */,
7355                               sig_type->dwo_unit->dwo_file->comp_dir,
7356                               &reader, &info_ptr,
7357                               &comp_unit_die, &has_children,
7358                               &dwo_abbrev_table) == 0)
7359     {
7360       /* Dummy die.  */
7361       return;
7362     }
7363
7364   /* All the "real" work is done here.  */
7365   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7366
7367   /* This duplicates the code in init_cutu_and_read_dies,
7368      but the alternative is making the latter more complex.
7369      This function is only for the special case of using DWO files directly:
7370      no point in overly complicating the general case just to handle this.  */
7371   if (new_cu != NULL && keep)
7372     {
7373       /* Link this CU into read_in_chain.  */
7374       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7375       dwarf2_per_objfile->read_in_chain = this_cu;
7376       /* The chain owns it now.  */
7377       new_cu.release ();
7378     }
7379 }
7380
7381 /* Initialize a CU (or TU) and read its DIEs.
7382    If the CU defers to a DWO file, read the DWO file as well.
7383
7384    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7385    Otherwise the table specified in the comp unit header is read in and used.
7386    This is an optimization for when we already have the abbrev table.
7387
7388    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7389    Otherwise, a new CU is allocated with xmalloc.
7390
7391    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7392    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7393
7394    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7395    linker) then DIE_READER_FUNC will not get called.  */
7396
7397 static void
7398 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7399                          struct abbrev_table *abbrev_table,
7400                          int use_existing_cu, int keep,
7401                          bool skip_partial,
7402                          die_reader_func_ftype *die_reader_func,
7403                          void *data)
7404 {
7405   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7406   struct objfile *objfile = dwarf2_per_objfile->objfile;
7407   struct dwarf2_section_info *section = this_cu->section;
7408   bfd *abfd = get_section_bfd_owner (section);
7409   struct dwarf2_cu *cu;
7410   const gdb_byte *begin_info_ptr, *info_ptr;
7411   struct die_reader_specs reader;
7412   struct die_info *comp_unit_die;
7413   int has_children;
7414   struct attribute *attr;
7415   struct signatured_type *sig_type = NULL;
7416   struct dwarf2_section_info *abbrev_section;
7417   /* Non-zero if CU currently points to a DWO file and we need to
7418      reread it.  When this happens we need to reread the skeleton die
7419      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7420   int rereading_dwo_cu = 0;
7421
7422   if (dwarf_die_debug)
7423     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7424                         this_cu->is_debug_types ? "type" : "comp",
7425                         sect_offset_str (this_cu->sect_off));
7426
7427   if (use_existing_cu)
7428     gdb_assert (keep);
7429
7430   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7431      file (instead of going through the stub), short-circuit all of this.  */
7432   if (this_cu->reading_dwo_directly)
7433     {
7434       /* Narrow down the scope of possibilities to have to understand.  */
7435       gdb_assert (this_cu->is_debug_types);
7436       gdb_assert (abbrev_table == NULL);
7437       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7438                                  die_reader_func, data);
7439       return;
7440     }
7441
7442   /* This is cheap if the section is already read in.  */
7443   dwarf2_read_section (objfile, section);
7444
7445   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7446
7447   abbrev_section = get_abbrev_section_for_cu (this_cu);
7448
7449   std::unique_ptr<dwarf2_cu> new_cu;
7450   if (use_existing_cu && this_cu->cu != NULL)
7451     {
7452       cu = this_cu->cu;
7453       /* If this CU is from a DWO file we need to start over, we need to
7454          refetch the attributes from the skeleton CU.
7455          This could be optimized by retrieving those attributes from when we
7456          were here the first time: the previous comp_unit_die was stored in
7457          comp_unit_obstack.  But there's no data yet that we need this
7458          optimization.  */
7459       if (cu->dwo_unit != NULL)
7460         rereading_dwo_cu = 1;
7461     }
7462   else
7463     {
7464       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7465       gdb_assert (this_cu->cu == NULL);
7466       new_cu.reset (new dwarf2_cu (this_cu));
7467       cu = new_cu.get ();
7468     }
7469
7470   /* Get the header.  */
7471   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7472     {
7473       /* We already have the header, there's no need to read it in again.  */
7474       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7475     }
7476   else
7477     {
7478       if (this_cu->is_debug_types)
7479         {
7480           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7481                                                     &cu->header, section,
7482                                                     abbrev_section, info_ptr,
7483                                                     rcuh_kind::TYPE);
7484
7485           /* Since per_cu is the first member of struct signatured_type,
7486              we can go from a pointer to one to a pointer to the other.  */
7487           sig_type = (struct signatured_type *) this_cu;
7488           gdb_assert (sig_type->signature == cu->header.signature);
7489           gdb_assert (sig_type->type_offset_in_tu
7490                       == cu->header.type_cu_offset_in_tu);
7491           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7492
7493           /* LENGTH has not been set yet for type units if we're
7494              using .gdb_index.  */
7495           this_cu->length = get_cu_length (&cu->header);
7496
7497           /* Establish the type offset that can be used to lookup the type.  */
7498           sig_type->type_offset_in_section =
7499             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7500
7501           this_cu->dwarf_version = cu->header.version;
7502         }
7503       else
7504         {
7505           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7506                                                     &cu->header, section,
7507                                                     abbrev_section,
7508                                                     info_ptr,
7509                                                     rcuh_kind::COMPILE);
7510
7511           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7512           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7513           this_cu->dwarf_version = cu->header.version;
7514         }
7515     }
7516
7517   /* Skip dummy compilation units.  */
7518   if (info_ptr >= begin_info_ptr + this_cu->length
7519       || peek_abbrev_code (abfd, info_ptr) == 0)
7520     return;
7521
7522   /* If we don't have them yet, read the abbrevs for this compilation unit.
7523      And if we need to read them now, make sure they're freed when we're
7524      done (own the table through ABBREV_TABLE_HOLDER).  */
7525   abbrev_table_up abbrev_table_holder;
7526   if (abbrev_table != NULL)
7527     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7528   else
7529     {
7530       abbrev_table_holder
7531         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7532                                    cu->header.abbrev_sect_off);
7533       abbrev_table = abbrev_table_holder.get ();
7534     }
7535
7536   /* Read the top level CU/TU die.  */
7537   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7538   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7539
7540   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7541     return;
7542
7543   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7544      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7545      table from the DWO file and pass the ownership over to us.  It will be
7546      referenced from READER, so we must make sure to free it after we're done
7547      with READER.
7548
7549      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7550      DWO CU, that this test will fail (the attribute will not be present).  */
7551   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7552   abbrev_table_up dwo_abbrev_table;
7553   if (attr)
7554     {
7555       struct dwo_unit *dwo_unit;
7556       struct die_info *dwo_comp_unit_die;
7557
7558       if (has_children)
7559         {
7560           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7561                        " has children (offset %s) [in module %s]"),
7562                      sect_offset_str (this_cu->sect_off),
7563                      bfd_get_filename (abfd));
7564         }
7565       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7566       if (dwo_unit != NULL)
7567         {
7568           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7569                                       comp_unit_die, NULL,
7570                                       &reader, &info_ptr,
7571                                       &dwo_comp_unit_die, &has_children,
7572                                       &dwo_abbrev_table) == 0)
7573             {
7574               /* Dummy die.  */
7575               return;
7576             }
7577           comp_unit_die = dwo_comp_unit_die;
7578         }
7579       else
7580         {
7581           /* Yikes, we couldn't find the rest of the DIE, we only have
7582              the stub.  A complaint has already been logged.  There's
7583              not much more we can do except pass on the stub DIE to
7584              die_reader_func.  We don't want to throw an error on bad
7585              debug info.  */
7586         }
7587     }
7588
7589   /* All of the above is setup for this call.  Yikes.  */
7590   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7591
7592   /* Done, clean up.  */
7593   if (new_cu != NULL && keep)
7594     {
7595       /* Link this CU into read_in_chain.  */
7596       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7597       dwarf2_per_objfile->read_in_chain = this_cu;
7598       /* The chain owns it now.  */
7599       new_cu.release ();
7600     }
7601 }
7602
7603 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7604    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7605    to have already done the lookup to find the DWO file).
7606
7607    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7608    THIS_CU->is_debug_types, but nothing else.
7609
7610    We fill in THIS_CU->length.
7611
7612    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7613    linker) then DIE_READER_FUNC will not get called.
7614
7615    THIS_CU->cu is always freed when done.
7616    This is done in order to not leave THIS_CU->cu in a state where we have
7617    to care whether it refers to the "main" CU or the DWO CU.  */
7618
7619 static void
7620 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7621                                    struct dwo_file *dwo_file,
7622                                    die_reader_func_ftype *die_reader_func,
7623                                    void *data)
7624 {
7625   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7626   struct objfile *objfile = dwarf2_per_objfile->objfile;
7627   struct dwarf2_section_info *section = this_cu->section;
7628   bfd *abfd = get_section_bfd_owner (section);
7629   struct dwarf2_section_info *abbrev_section;
7630   const gdb_byte *begin_info_ptr, *info_ptr;
7631   struct die_reader_specs reader;
7632   struct die_info *comp_unit_die;
7633   int has_children;
7634
7635   if (dwarf_die_debug)
7636     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7637                         this_cu->is_debug_types ? "type" : "comp",
7638                         sect_offset_str (this_cu->sect_off));
7639
7640   gdb_assert (this_cu->cu == NULL);
7641
7642   abbrev_section = (dwo_file != NULL
7643                     ? &dwo_file->sections.abbrev
7644                     : get_abbrev_section_for_cu (this_cu));
7645
7646   /* This is cheap if the section is already read in.  */
7647   dwarf2_read_section (objfile, section);
7648
7649   struct dwarf2_cu cu (this_cu);
7650
7651   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7652   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7653                                             &cu.header, section,
7654                                             abbrev_section, info_ptr,
7655                                             (this_cu->is_debug_types
7656                                              ? rcuh_kind::TYPE
7657                                              : rcuh_kind::COMPILE));
7658
7659   this_cu->length = get_cu_length (&cu.header);
7660
7661   /* Skip dummy compilation units.  */
7662   if (info_ptr >= begin_info_ptr + this_cu->length
7663       || peek_abbrev_code (abfd, info_ptr) == 0)
7664     return;
7665
7666   abbrev_table_up abbrev_table
7667     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7668                                cu.header.abbrev_sect_off);
7669
7670   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7671   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7672
7673   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7674 }
7675
7676 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7677    does not lookup the specified DWO file.
7678    This cannot be used to read DWO files.
7679
7680    THIS_CU->cu is always freed when done.
7681    This is done in order to not leave THIS_CU->cu in a state where we have
7682    to care whether it refers to the "main" CU or the DWO CU.
7683    We can revisit this if the data shows there's a performance issue.  */
7684
7685 static void
7686 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7687                                 die_reader_func_ftype *die_reader_func,
7688                                 void *data)
7689 {
7690   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7691 }
7692 \f
7693 /* Type Unit Groups.
7694
7695    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7696    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7697    so that all types coming from the same compilation (.o file) are grouped
7698    together.  A future step could be to put the types in the same symtab as
7699    the CU the types ultimately came from.  */
7700
7701 static hashval_t
7702 hash_type_unit_group (const void *item)
7703 {
7704   const struct type_unit_group *tu_group
7705     = (const struct type_unit_group *) item;
7706
7707   return hash_stmt_list_entry (&tu_group->hash);
7708 }
7709
7710 static int
7711 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7712 {
7713   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7714   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7715
7716   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7717 }
7718
7719 /* Allocate a hash table for type unit groups.  */
7720
7721 static htab_t
7722 allocate_type_unit_groups_table (struct objfile *objfile)
7723 {
7724   return htab_create_alloc_ex (3,
7725                                hash_type_unit_group,
7726                                eq_type_unit_group,
7727                                NULL,
7728                                &objfile->objfile_obstack,
7729                                hashtab_obstack_allocate,
7730                                dummy_obstack_deallocate);
7731 }
7732
7733 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7734    partial symtabs.  We combine several TUs per psymtab to not let the size
7735    of any one psymtab grow too big.  */
7736 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7737 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7738
7739 /* Helper routine for get_type_unit_group.
7740    Create the type_unit_group object used to hold one or more TUs.  */
7741
7742 static struct type_unit_group *
7743 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7744 {
7745   struct dwarf2_per_objfile *dwarf2_per_objfile
7746     = cu->per_cu->dwarf2_per_objfile;
7747   struct objfile *objfile = dwarf2_per_objfile->objfile;
7748   struct dwarf2_per_cu_data *per_cu;
7749   struct type_unit_group *tu_group;
7750
7751   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7752                              struct type_unit_group);
7753   per_cu = &tu_group->per_cu;
7754   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7755
7756   if (dwarf2_per_objfile->using_index)
7757     {
7758       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7759                                         struct dwarf2_per_cu_quick_data);
7760     }
7761   else
7762     {
7763       unsigned int line_offset = to_underlying (line_offset_struct);
7764       struct partial_symtab *pst;
7765       char *name;
7766
7767       /* Give the symtab a useful name for debug purposes.  */
7768       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7769         name = xstrprintf ("<type_units_%d>",
7770                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7771       else
7772         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
7773
7774       pst = create_partial_symtab (per_cu, name);
7775       pst->anonymous = 1;
7776
7777       xfree (name);
7778     }
7779
7780   tu_group->hash.dwo_unit = cu->dwo_unit;
7781   tu_group->hash.line_sect_off = line_offset_struct;
7782
7783   return tu_group;
7784 }
7785
7786 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7787    STMT_LIST is a DW_AT_stmt_list attribute.  */
7788
7789 static struct type_unit_group *
7790 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7791 {
7792   struct dwarf2_per_objfile *dwarf2_per_objfile
7793     = cu->per_cu->dwarf2_per_objfile;
7794   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7795   struct type_unit_group *tu_group;
7796   void **slot;
7797   unsigned int line_offset;
7798   struct type_unit_group type_unit_group_for_lookup;
7799
7800   if (dwarf2_per_objfile->type_unit_groups == NULL)
7801     {
7802       dwarf2_per_objfile->type_unit_groups =
7803         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7804     }
7805
7806   /* Do we need to create a new group, or can we use an existing one?  */
7807
7808   if (stmt_list)
7809     {
7810       line_offset = DW_UNSND (stmt_list);
7811       ++tu_stats->nr_symtab_sharers;
7812     }
7813   else
7814     {
7815       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7816          We can do various things here like create one group per TU or
7817          spread them over multiple groups to split up the expansion work.
7818          To avoid worst case scenarios (too many groups or too large groups)
7819          we, umm, group them in bunches.  */
7820       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7821                      | (tu_stats->nr_stmt_less_type_units
7822                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7823       ++tu_stats->nr_stmt_less_type_units;
7824     }
7825
7826   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7827   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7828   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7829                          &type_unit_group_for_lookup, INSERT);
7830   if (*slot != NULL)
7831     {
7832       tu_group = (struct type_unit_group *) *slot;
7833       gdb_assert (tu_group != NULL);
7834     }
7835   else
7836     {
7837       sect_offset line_offset_struct = (sect_offset) line_offset;
7838       tu_group = create_type_unit_group (cu, line_offset_struct);
7839       *slot = tu_group;
7840       ++tu_stats->nr_symtabs;
7841     }
7842
7843   return tu_group;
7844 }
7845 \f
7846 /* Partial symbol tables.  */
7847
7848 /* Create a psymtab named NAME and assign it to PER_CU.
7849
7850    The caller must fill in the following details:
7851    dirname, textlow, texthigh.  */
7852
7853 static struct partial_symtab *
7854 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7855 {
7856   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7857   struct partial_symtab *pst;
7858
7859   pst = start_psymtab_common (objfile, name, 0,
7860                               objfile->global_psymbols,
7861                               objfile->static_psymbols);
7862
7863   pst->psymtabs_addrmap_supported = 1;
7864
7865   /* This is the glue that links PST into GDB's symbol API.  */
7866   pst->read_symtab_private = per_cu;
7867   pst->read_symtab = dwarf2_read_symtab;
7868   per_cu->v.psymtab = pst;
7869
7870   return pst;
7871 }
7872
7873 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7874    type.  */
7875
7876 struct process_psymtab_comp_unit_data
7877 {
7878   /* True if we are reading a DW_TAG_partial_unit.  */
7879
7880   int want_partial_unit;
7881
7882   /* The "pretend" language that is used if the CU doesn't declare a
7883      language.  */
7884
7885   enum language pretend_language;
7886 };
7887
7888 /* die_reader_func for process_psymtab_comp_unit.  */
7889
7890 static void
7891 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7892                                   const gdb_byte *info_ptr,
7893                                   struct die_info *comp_unit_die,
7894                                   int has_children,
7895                                   void *data)
7896 {
7897   struct dwarf2_cu *cu = reader->cu;
7898   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7899   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7900   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7901   CORE_ADDR baseaddr;
7902   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7903   struct partial_symtab *pst;
7904   enum pc_bounds_kind cu_bounds_kind;
7905   const char *filename;
7906   struct process_psymtab_comp_unit_data *info
7907     = (struct process_psymtab_comp_unit_data *) data;
7908
7909   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7910     return;
7911
7912   gdb_assert (! per_cu->is_debug_types);
7913
7914   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7915
7916   /* Allocate a new partial symbol table structure.  */
7917   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7918   if (filename == NULL)
7919     filename = "";
7920
7921   pst = create_partial_symtab (per_cu, filename);
7922
7923   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7924   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7925
7926   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7927
7928   dwarf2_find_base_address (comp_unit_die, cu);
7929
7930   /* Possibly set the default values of LOWPC and HIGHPC from
7931      `DW_AT_ranges'.  */
7932   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7933                                          &best_highpc, cu, pst);
7934   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7935     /* Store the contiguous range if it is not empty; it can be empty for
7936        CUs with no code.  */
7937     addrmap_set_empty (objfile->psymtabs_addrmap,
7938                        gdbarch_adjust_dwarf2_addr (gdbarch,
7939                                                    best_lowpc + baseaddr),
7940                        gdbarch_adjust_dwarf2_addr (gdbarch,
7941                                                    best_highpc + baseaddr) - 1,
7942                        pst);
7943
7944   /* Check if comp unit has_children.
7945      If so, read the rest of the partial symbols from this comp unit.
7946      If not, there's no more debug_info for this comp unit.  */
7947   if (has_children)
7948     {
7949       struct partial_die_info *first_die;
7950       CORE_ADDR lowpc, highpc;
7951
7952       lowpc = ((CORE_ADDR) -1);
7953       highpc = ((CORE_ADDR) 0);
7954
7955       first_die = load_partial_dies (reader, info_ptr, 1);
7956
7957       scan_partial_symbols (first_die, &lowpc, &highpc,
7958                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7959
7960       /* If we didn't find a lowpc, set it to highpc to avoid
7961          complaints from `maint check'.  */
7962       if (lowpc == ((CORE_ADDR) -1))
7963         lowpc = highpc;
7964
7965       /* If the compilation unit didn't have an explicit address range,
7966          then use the information extracted from its child dies.  */
7967       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7968         {
7969           best_lowpc = lowpc;
7970           best_highpc = highpc;
7971         }
7972     }
7973   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
7974   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
7975
7976   end_psymtab_common (objfile, pst);
7977
7978   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
7979     {
7980       int i;
7981       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7982       struct dwarf2_per_cu_data *iter;
7983
7984       /* Fill in 'dependencies' here; we fill in 'users' in a
7985          post-pass.  */
7986       pst->number_of_dependencies = len;
7987       pst->dependencies =
7988         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7989       for (i = 0;
7990            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7991                         i, iter);
7992            ++i)
7993         pst->dependencies[i] = iter->v.psymtab;
7994
7995       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7996     }
7997
7998   /* Get the list of files included in the current compilation unit,
7999      and build a psymtab for each of them.  */
8000   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8001
8002   if (dwarf_read_debug)
8003     {
8004       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8005
8006       fprintf_unfiltered (gdb_stdlog,
8007                           "Psymtab for %s unit @%s: %s - %s"
8008                           ", %d global, %d static syms\n",
8009                           per_cu->is_debug_types ? "type" : "comp",
8010                           sect_offset_str (per_cu->sect_off),
8011                           paddress (gdbarch, pst->textlow),
8012                           paddress (gdbarch, pst->texthigh),
8013                           pst->n_global_syms, pst->n_static_syms);
8014     }
8015 }
8016
8017 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8018    Process compilation unit THIS_CU for a psymtab.  */
8019
8020 static void
8021 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8022                            int want_partial_unit,
8023                            enum language pretend_language)
8024 {
8025   /* If this compilation unit was already read in, free the
8026      cached copy in order to read it in again.  This is
8027      necessary because we skipped some symbols when we first
8028      read in the compilation unit (see load_partial_dies).
8029      This problem could be avoided, but the benefit is unclear.  */
8030   if (this_cu->cu != NULL)
8031     free_one_cached_comp_unit (this_cu);
8032
8033   if (this_cu->is_debug_types)
8034     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8035                              build_type_psymtabs_reader, NULL);
8036   else
8037     {
8038       process_psymtab_comp_unit_data info;
8039       info.want_partial_unit = want_partial_unit;
8040       info.pretend_language = pretend_language;
8041       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8042                                process_psymtab_comp_unit_reader, &info);
8043     }
8044
8045   /* Age out any secondary CUs.  */
8046   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8047 }
8048
8049 /* Reader function for build_type_psymtabs.  */
8050
8051 static void
8052 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8053                             const gdb_byte *info_ptr,
8054                             struct die_info *type_unit_die,
8055                             int has_children,
8056                             void *data)
8057 {
8058   struct dwarf2_per_objfile *dwarf2_per_objfile
8059     = reader->cu->per_cu->dwarf2_per_objfile;
8060   struct objfile *objfile = dwarf2_per_objfile->objfile;
8061   struct dwarf2_cu *cu = reader->cu;
8062   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8063   struct signatured_type *sig_type;
8064   struct type_unit_group *tu_group;
8065   struct attribute *attr;
8066   struct partial_die_info *first_die;
8067   CORE_ADDR lowpc, highpc;
8068   struct partial_symtab *pst;
8069
8070   gdb_assert (data == NULL);
8071   gdb_assert (per_cu->is_debug_types);
8072   sig_type = (struct signatured_type *) per_cu;
8073
8074   if (! has_children)
8075     return;
8076
8077   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8078   tu_group = get_type_unit_group (cu, attr);
8079
8080   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8081
8082   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8083   pst = create_partial_symtab (per_cu, "");
8084   pst->anonymous = 1;
8085
8086   first_die = load_partial_dies (reader, info_ptr, 1);
8087
8088   lowpc = (CORE_ADDR) -1;
8089   highpc = (CORE_ADDR) 0;
8090   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8091
8092   end_psymtab_common (objfile, pst);
8093 }
8094
8095 /* Struct used to sort TUs by their abbreviation table offset.  */
8096
8097 struct tu_abbrev_offset
8098 {
8099   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8100   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8101   {}
8102
8103   signatured_type *sig_type;
8104   sect_offset abbrev_offset;
8105 };
8106
8107 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8108
8109 static bool
8110 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8111                           const struct tu_abbrev_offset &b)
8112 {
8113   return a.abbrev_offset < b.abbrev_offset;
8114 }
8115
8116 /* Efficiently read all the type units.
8117    This does the bulk of the work for build_type_psymtabs.
8118
8119    The efficiency is because we sort TUs by the abbrev table they use and
8120    only read each abbrev table once.  In one program there are 200K TUs
8121    sharing 8K abbrev tables.
8122
8123    The main purpose of this function is to support building the
8124    dwarf2_per_objfile->type_unit_groups table.
8125    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8126    can collapse the search space by grouping them by stmt_list.
8127    The savings can be significant, in the same program from above the 200K TUs
8128    share 8K stmt_list tables.
8129
8130    FUNC is expected to call get_type_unit_group, which will create the
8131    struct type_unit_group if necessary and add it to
8132    dwarf2_per_objfile->type_unit_groups.  */
8133
8134 static void
8135 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8136 {
8137   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8138   abbrev_table_up abbrev_table;
8139   sect_offset abbrev_offset;
8140
8141   /* It's up to the caller to not call us multiple times.  */
8142   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8143
8144   if (dwarf2_per_objfile->all_type_units.empty ())
8145     return;
8146
8147   /* TUs typically share abbrev tables, and there can be way more TUs than
8148      abbrev tables.  Sort by abbrev table to reduce the number of times we
8149      read each abbrev table in.
8150      Alternatives are to punt or to maintain a cache of abbrev tables.
8151      This is simpler and efficient enough for now.
8152
8153      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8154      symtab to use).  Typically TUs with the same abbrev offset have the same
8155      stmt_list value too so in practice this should work well.
8156
8157      The basic algorithm here is:
8158
8159       sort TUs by abbrev table
8160       for each TU with same abbrev table:
8161         read abbrev table if first user
8162         read TU top level DIE
8163           [IWBN if DWO skeletons had DW_AT_stmt_list]
8164         call FUNC  */
8165
8166   if (dwarf_read_debug)
8167     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8168
8169   /* Sort in a separate table to maintain the order of all_type_units
8170      for .gdb_index: TU indices directly index all_type_units.  */
8171   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8172   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8173
8174   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8175     sorted_by_abbrev.emplace_back
8176       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8177                                      sig_type->per_cu.section,
8178                                      sig_type->per_cu.sect_off));
8179
8180   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8181              sort_tu_by_abbrev_offset);
8182
8183   abbrev_offset = (sect_offset) ~(unsigned) 0;
8184
8185   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8186     {
8187       /* Switch to the next abbrev table if necessary.  */
8188       if (abbrev_table == NULL
8189           || tu.abbrev_offset != abbrev_offset)
8190         {
8191           abbrev_offset = tu.abbrev_offset;
8192           abbrev_table =
8193             abbrev_table_read_table (dwarf2_per_objfile,
8194                                      &dwarf2_per_objfile->abbrev,
8195                                      abbrev_offset);
8196           ++tu_stats->nr_uniq_abbrev_tables;
8197         }
8198
8199       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8200                                0, 0, false, build_type_psymtabs_reader, NULL);
8201     }
8202 }
8203
8204 /* Print collected type unit statistics.  */
8205
8206 static void
8207 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8208 {
8209   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8210
8211   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8212   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8213                       dwarf2_per_objfile->all_type_units.size ());
8214   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8215                       tu_stats->nr_uniq_abbrev_tables);
8216   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8217                       tu_stats->nr_symtabs);
8218   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8219                       tu_stats->nr_symtab_sharers);
8220   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8221                       tu_stats->nr_stmt_less_type_units);
8222   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8223                       tu_stats->nr_all_type_units_reallocs);
8224 }
8225
8226 /* Traversal function for build_type_psymtabs.  */
8227
8228 static int
8229 build_type_psymtab_dependencies (void **slot, void *info)
8230 {
8231   struct dwarf2_per_objfile *dwarf2_per_objfile
8232     = (struct dwarf2_per_objfile *) info;
8233   struct objfile *objfile = dwarf2_per_objfile->objfile;
8234   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8235   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8236   struct partial_symtab *pst = per_cu->v.psymtab;
8237   int len = VEC_length (sig_type_ptr, tu_group->tus);
8238   struct signatured_type *iter;
8239   int i;
8240
8241   gdb_assert (len > 0);
8242   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8243
8244   pst->number_of_dependencies = len;
8245   pst->dependencies =
8246     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8247   for (i = 0;
8248        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8249        ++i)
8250     {
8251       gdb_assert (iter->per_cu.is_debug_types);
8252       pst->dependencies[i] = iter->per_cu.v.psymtab;
8253       iter->type_unit_group = tu_group;
8254     }
8255
8256   VEC_free (sig_type_ptr, tu_group->tus);
8257
8258   return 1;
8259 }
8260
8261 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8262    Build partial symbol tables for the .debug_types comp-units.  */
8263
8264 static void
8265 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8266 {
8267   if (! create_all_type_units (dwarf2_per_objfile))
8268     return;
8269
8270   build_type_psymtabs_1 (dwarf2_per_objfile);
8271 }
8272
8273 /* Traversal function for process_skeletonless_type_unit.
8274    Read a TU in a DWO file and build partial symbols for it.  */
8275
8276 static int
8277 process_skeletonless_type_unit (void **slot, void *info)
8278 {
8279   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8280   struct dwarf2_per_objfile *dwarf2_per_objfile
8281     = (struct dwarf2_per_objfile *) info;
8282   struct signatured_type find_entry, *entry;
8283
8284   /* If this TU doesn't exist in the global table, add it and read it in.  */
8285
8286   if (dwarf2_per_objfile->signatured_types == NULL)
8287     {
8288       dwarf2_per_objfile->signatured_types
8289         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8290     }
8291
8292   find_entry.signature = dwo_unit->signature;
8293   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8294                          INSERT);
8295   /* If we've already seen this type there's nothing to do.  What's happening
8296      is we're doing our own version of comdat-folding here.  */
8297   if (*slot != NULL)
8298     return 1;
8299
8300   /* This does the job that create_all_type_units would have done for
8301      this TU.  */
8302   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8303   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8304   *slot = entry;
8305
8306   /* This does the job that build_type_psymtabs_1 would have done.  */
8307   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8308                            build_type_psymtabs_reader, NULL);
8309
8310   return 1;
8311 }
8312
8313 /* Traversal function for process_skeletonless_type_units.  */
8314
8315 static int
8316 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8317 {
8318   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8319
8320   if (dwo_file->tus != NULL)
8321     {
8322       htab_traverse_noresize (dwo_file->tus,
8323                               process_skeletonless_type_unit, info);
8324     }
8325
8326   return 1;
8327 }
8328
8329 /* Scan all TUs of DWO files, verifying we've processed them.
8330    This is needed in case a TU was emitted without its skeleton.
8331    Note: This can't be done until we know what all the DWO files are.  */
8332
8333 static void
8334 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8335 {
8336   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8337   if (get_dwp_file (dwarf2_per_objfile) == NULL
8338       && dwarf2_per_objfile->dwo_files != NULL)
8339     {
8340       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8341                               process_dwo_file_for_skeletonless_type_units,
8342                               dwarf2_per_objfile);
8343     }
8344 }
8345
8346 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8347
8348 static void
8349 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8350 {
8351   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8352     {
8353       struct partial_symtab *pst = per_cu->v.psymtab;
8354
8355       if (pst == NULL)
8356         continue;
8357
8358       for (int j = 0; j < pst->number_of_dependencies; ++j)
8359         {
8360           /* Set the 'user' field only if it is not already set.  */
8361           if (pst->dependencies[j]->user == NULL)
8362             pst->dependencies[j]->user = pst;
8363         }
8364     }
8365 }
8366
8367 /* Build the partial symbol table by doing a quick pass through the
8368    .debug_info and .debug_abbrev sections.  */
8369
8370 static void
8371 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8372 {
8373   struct objfile *objfile = dwarf2_per_objfile->objfile;
8374
8375   if (dwarf_read_debug)
8376     {
8377       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8378                           objfile_name (objfile));
8379     }
8380
8381   dwarf2_per_objfile->reading_partial_symbols = 1;
8382
8383   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8384
8385   /* Any cached compilation units will be linked by the per-objfile
8386      read_in_chain.  Make sure to free them when we're done.  */
8387   free_cached_comp_units freer (dwarf2_per_objfile);
8388
8389   build_type_psymtabs (dwarf2_per_objfile);
8390
8391   create_all_comp_units (dwarf2_per_objfile);
8392
8393   /* Create a temporary address map on a temporary obstack.  We later
8394      copy this to the final obstack.  */
8395   auto_obstack temp_obstack;
8396
8397   scoped_restore save_psymtabs_addrmap
8398     = make_scoped_restore (&objfile->psymtabs_addrmap,
8399                            addrmap_create_mutable (&temp_obstack));
8400
8401   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8402     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8403
8404   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8405   process_skeletonless_type_units (dwarf2_per_objfile);
8406
8407   /* Now that all TUs have been processed we can fill in the dependencies.  */
8408   if (dwarf2_per_objfile->type_unit_groups != NULL)
8409     {
8410       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8411                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8412     }
8413
8414   if (dwarf_read_debug)
8415     print_tu_stats (dwarf2_per_objfile);
8416
8417   set_partial_user (dwarf2_per_objfile);
8418
8419   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8420                                                     &objfile->objfile_obstack);
8421   /* At this point we want to keep the address map.  */
8422   save_psymtabs_addrmap.release ();
8423
8424   if (dwarf_read_debug)
8425     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8426                         objfile_name (objfile));
8427 }
8428
8429 /* die_reader_func for load_partial_comp_unit.  */
8430
8431 static void
8432 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8433                                const gdb_byte *info_ptr,
8434                                struct die_info *comp_unit_die,
8435                                int has_children,
8436                                void *data)
8437 {
8438   struct dwarf2_cu *cu = reader->cu;
8439
8440   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8441
8442   /* Check if comp unit has_children.
8443      If so, read the rest of the partial symbols from this comp unit.
8444      If not, there's no more debug_info for this comp unit.  */
8445   if (has_children)
8446     load_partial_dies (reader, info_ptr, 0);
8447 }
8448
8449 /* Load the partial DIEs for a secondary CU into memory.
8450    This is also used when rereading a primary CU with load_all_dies.  */
8451
8452 static void
8453 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8454 {
8455   init_cutu_and_read_dies (this_cu, NULL, 1, 1, false,
8456                            load_partial_comp_unit_reader, NULL);
8457 }
8458
8459 static void
8460 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8461                               struct dwarf2_section_info *section,
8462                               struct dwarf2_section_info *abbrev_section,
8463                               unsigned int is_dwz)
8464 {
8465   const gdb_byte *info_ptr;
8466   struct objfile *objfile = dwarf2_per_objfile->objfile;
8467
8468   if (dwarf_read_debug)
8469     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8470                         get_section_name (section),
8471                         get_section_file_name (section));
8472
8473   dwarf2_read_section (objfile, section);
8474
8475   info_ptr = section->buffer;
8476
8477   while (info_ptr < section->buffer + section->size)
8478     {
8479       struct dwarf2_per_cu_data *this_cu;
8480
8481       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8482
8483       comp_unit_head cu_header;
8484       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8485                                      abbrev_section, info_ptr,
8486                                      rcuh_kind::COMPILE);
8487
8488       /* Save the compilation unit for later lookup.  */
8489       if (cu_header.unit_type != DW_UT_type)
8490         {
8491           this_cu = XOBNEW (&objfile->objfile_obstack,
8492                             struct dwarf2_per_cu_data);
8493           memset (this_cu, 0, sizeof (*this_cu));
8494         }
8495       else
8496         {
8497           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8498                                   struct signatured_type);
8499           memset (sig_type, 0, sizeof (*sig_type));
8500           sig_type->signature = cu_header.signature;
8501           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8502           this_cu = &sig_type->per_cu;
8503         }
8504       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8505       this_cu->sect_off = sect_off;
8506       this_cu->length = cu_header.length + cu_header.initial_length_size;
8507       this_cu->is_dwz = is_dwz;
8508       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8509       this_cu->section = section;
8510
8511       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8512
8513       info_ptr = info_ptr + this_cu->length;
8514     }
8515 }
8516
8517 /* Create a list of all compilation units in OBJFILE.
8518    This is only done for -readnow and building partial symtabs.  */
8519
8520 static void
8521 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8522 {
8523   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8524   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8525                                 &dwarf2_per_objfile->abbrev, 0);
8526
8527   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8528   if (dwz != NULL)
8529     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8530                                   1);
8531 }
8532
8533 /* Process all loaded DIEs for compilation unit CU, starting at
8534    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8535    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8536    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8537    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8538
8539 static void
8540 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8541                       CORE_ADDR *highpc, int set_addrmap,
8542                       struct dwarf2_cu *cu)
8543 {
8544   struct partial_die_info *pdi;
8545
8546   /* Now, march along the PDI's, descending into ones which have
8547      interesting children but skipping the children of the other ones,
8548      until we reach the end of the compilation unit.  */
8549
8550   pdi = first_die;
8551
8552   while (pdi != NULL)
8553     {
8554       pdi->fixup (cu);
8555
8556       /* Anonymous namespaces or modules have no name but have interesting
8557          children, so we need to look at them.  Ditto for anonymous
8558          enums.  */
8559
8560       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8561           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8562           || pdi->tag == DW_TAG_imported_unit
8563           || pdi->tag == DW_TAG_inlined_subroutine)
8564         {
8565           switch (pdi->tag)
8566             {
8567             case DW_TAG_subprogram:
8568             case DW_TAG_inlined_subroutine:
8569               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8570               break;
8571             case DW_TAG_constant:
8572             case DW_TAG_variable:
8573             case DW_TAG_typedef:
8574             case DW_TAG_union_type:
8575               if (!pdi->is_declaration)
8576                 {
8577                   add_partial_symbol (pdi, cu);
8578                 }
8579               break;
8580             case DW_TAG_class_type:
8581             case DW_TAG_interface_type:
8582             case DW_TAG_structure_type:
8583               if (!pdi->is_declaration)
8584                 {
8585                   add_partial_symbol (pdi, cu);
8586                 }
8587               if ((cu->language == language_rust
8588                    || cu->language == language_cplus) && pdi->has_children)
8589                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8590                                       set_addrmap, cu);
8591               break;
8592             case DW_TAG_enumeration_type:
8593               if (!pdi->is_declaration)
8594                 add_partial_enumeration (pdi, cu);
8595               break;
8596             case DW_TAG_base_type:
8597             case DW_TAG_subrange_type:
8598               /* File scope base type definitions are added to the partial
8599                  symbol table.  */
8600               add_partial_symbol (pdi, cu);
8601               break;
8602             case DW_TAG_namespace:
8603               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8604               break;
8605             case DW_TAG_module:
8606               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8607               break;
8608             case DW_TAG_imported_unit:
8609               {
8610                 struct dwarf2_per_cu_data *per_cu;
8611
8612                 /* For now we don't handle imported units in type units.  */
8613                 if (cu->per_cu->is_debug_types)
8614                   {
8615                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8616                              " supported in type units [in module %s]"),
8617                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8618                   }
8619
8620                 per_cu = dwarf2_find_containing_comp_unit
8621                            (pdi->d.sect_off, pdi->is_dwz,
8622                             cu->per_cu->dwarf2_per_objfile);
8623
8624                 /* Go read the partial unit, if needed.  */
8625                 if (per_cu->v.psymtab == NULL)
8626                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8627
8628                 VEC_safe_push (dwarf2_per_cu_ptr,
8629                                cu->per_cu->imported_symtabs, per_cu);
8630               }
8631               break;
8632             case DW_TAG_imported_declaration:
8633               add_partial_symbol (pdi, cu);
8634               break;
8635             default:
8636               break;
8637             }
8638         }
8639
8640       /* If the die has a sibling, skip to the sibling.  */
8641
8642       pdi = pdi->die_sibling;
8643     }
8644 }
8645
8646 /* Functions used to compute the fully scoped name of a partial DIE.
8647
8648    Normally, this is simple.  For C++, the parent DIE's fully scoped
8649    name is concatenated with "::" and the partial DIE's name.
8650    Enumerators are an exception; they use the scope of their parent
8651    enumeration type, i.e. the name of the enumeration type is not
8652    prepended to the enumerator.
8653
8654    There are two complexities.  One is DW_AT_specification; in this
8655    case "parent" means the parent of the target of the specification,
8656    instead of the direct parent of the DIE.  The other is compilers
8657    which do not emit DW_TAG_namespace; in this case we try to guess
8658    the fully qualified name of structure types from their members'
8659    linkage names.  This must be done using the DIE's children rather
8660    than the children of any DW_AT_specification target.  We only need
8661    to do this for structures at the top level, i.e. if the target of
8662    any DW_AT_specification (if any; otherwise the DIE itself) does not
8663    have a parent.  */
8664
8665 /* Compute the scope prefix associated with PDI's parent, in
8666    compilation unit CU.  The result will be allocated on CU's
8667    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8668    field.  NULL is returned if no prefix is necessary.  */
8669 static const char *
8670 partial_die_parent_scope (struct partial_die_info *pdi,
8671                           struct dwarf2_cu *cu)
8672 {
8673   const char *grandparent_scope;
8674   struct partial_die_info *parent, *real_pdi;
8675
8676   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8677      then this means the parent of the specification DIE.  */
8678
8679   real_pdi = pdi;
8680   while (real_pdi->has_specification)
8681     real_pdi = find_partial_die (real_pdi->spec_offset,
8682                                  real_pdi->spec_is_dwz, cu);
8683
8684   parent = real_pdi->die_parent;
8685   if (parent == NULL)
8686     return NULL;
8687
8688   if (parent->scope_set)
8689     return parent->scope;
8690
8691   parent->fixup (cu);
8692
8693   grandparent_scope = partial_die_parent_scope (parent, cu);
8694
8695   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8696      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8697      Work around this problem here.  */
8698   if (cu->language == language_cplus
8699       && parent->tag == DW_TAG_namespace
8700       && strcmp (parent->name, "::") == 0
8701       && grandparent_scope == NULL)
8702     {
8703       parent->scope = NULL;
8704       parent->scope_set = 1;
8705       return NULL;
8706     }
8707
8708   if (pdi->tag == DW_TAG_enumerator)
8709     /* Enumerators should not get the name of the enumeration as a prefix.  */
8710     parent->scope = grandparent_scope;
8711   else if (parent->tag == DW_TAG_namespace
8712       || parent->tag == DW_TAG_module
8713       || parent->tag == DW_TAG_structure_type
8714       || parent->tag == DW_TAG_class_type
8715       || parent->tag == DW_TAG_interface_type
8716       || parent->tag == DW_TAG_union_type
8717       || parent->tag == DW_TAG_enumeration_type)
8718     {
8719       if (grandparent_scope == NULL)
8720         parent->scope = parent->name;
8721       else
8722         parent->scope = typename_concat (&cu->comp_unit_obstack,
8723                                          grandparent_scope,
8724                                          parent->name, 0, cu);
8725     }
8726   else
8727     {
8728       /* FIXME drow/2004-04-01: What should we be doing with
8729          function-local names?  For partial symbols, we should probably be
8730          ignoring them.  */
8731       complaint (_("unhandled containing DIE tag %d for DIE at %s"),
8732                  parent->tag, sect_offset_str (pdi->sect_off));
8733       parent->scope = grandparent_scope;
8734     }
8735
8736   parent->scope_set = 1;
8737   return parent->scope;
8738 }
8739
8740 /* Return the fully scoped name associated with PDI, from compilation unit
8741    CU.  The result will be allocated with malloc.  */
8742
8743 static char *
8744 partial_die_full_name (struct partial_die_info *pdi,
8745                        struct dwarf2_cu *cu)
8746 {
8747   const char *parent_scope;
8748
8749   /* If this is a template instantiation, we can not work out the
8750      template arguments from partial DIEs.  So, unfortunately, we have
8751      to go through the full DIEs.  At least any work we do building
8752      types here will be reused if full symbols are loaded later.  */
8753   if (pdi->has_template_arguments)
8754     {
8755       pdi->fixup (cu);
8756
8757       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8758         {
8759           struct die_info *die;
8760           struct attribute attr;
8761           struct dwarf2_cu *ref_cu = cu;
8762
8763           /* DW_FORM_ref_addr is using section offset.  */
8764           attr.name = (enum dwarf_attribute) 0;
8765           attr.form = DW_FORM_ref_addr;
8766           attr.u.unsnd = to_underlying (pdi->sect_off);
8767           die = follow_die_ref (NULL, &attr, &ref_cu);
8768
8769           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8770         }
8771     }
8772
8773   parent_scope = partial_die_parent_scope (pdi, cu);
8774   if (parent_scope == NULL)
8775     return NULL;
8776   else
8777     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8778 }
8779
8780 static void
8781 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8782 {
8783   struct dwarf2_per_objfile *dwarf2_per_objfile
8784     = cu->per_cu->dwarf2_per_objfile;
8785   struct objfile *objfile = dwarf2_per_objfile->objfile;
8786   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8787   CORE_ADDR addr = 0;
8788   const char *actual_name = NULL;
8789   CORE_ADDR baseaddr;
8790   char *built_actual_name;
8791
8792   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8793
8794   built_actual_name = partial_die_full_name (pdi, cu);
8795   if (built_actual_name != NULL)
8796     actual_name = built_actual_name;
8797
8798   if (actual_name == NULL)
8799     actual_name = pdi->name;
8800
8801   switch (pdi->tag)
8802     {
8803     case DW_TAG_inlined_subroutine:
8804     case DW_TAG_subprogram:
8805       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
8806       if (pdi->is_external || cu->language == language_ada)
8807         {
8808           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8809              of the global scope.  But in Ada, we want to be able to access
8810              nested procedures globally.  So all Ada subprograms are stored
8811              in the global scope.  */
8812           add_psymbol_to_list (actual_name, strlen (actual_name),
8813                                built_actual_name != NULL,
8814                                VAR_DOMAIN, LOC_BLOCK,
8815                                &objfile->global_psymbols,
8816                                addr, cu->language, objfile);
8817         }
8818       else
8819         {
8820           add_psymbol_to_list (actual_name, strlen (actual_name),
8821                                built_actual_name != NULL,
8822                                VAR_DOMAIN, LOC_BLOCK,
8823                                &objfile->static_psymbols,
8824                                addr, cu->language, objfile);
8825         }
8826
8827       if (pdi->main_subprogram && actual_name != NULL)
8828         set_objfile_main_name (objfile, actual_name, cu->language);
8829       break;
8830     case DW_TAG_constant:
8831       {
8832         std::vector<partial_symbol *> *list;
8833
8834         if (pdi->is_external)
8835           list = &objfile->global_psymbols;
8836         else
8837           list = &objfile->static_psymbols;
8838         add_psymbol_to_list (actual_name, strlen (actual_name),
8839                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8840                              list, 0, cu->language, objfile);
8841       }
8842       break;
8843     case DW_TAG_variable:
8844       if (pdi->d.locdesc)
8845         addr = decode_locdesc (pdi->d.locdesc, cu);
8846
8847       if (pdi->d.locdesc
8848           && addr == 0
8849           && !dwarf2_per_objfile->has_section_at_zero)
8850         {
8851           /* A global or static variable may also have been stripped
8852              out by the linker if unused, in which case its address
8853              will be nullified; do not add such variables into partial
8854              symbol table then.  */
8855         }
8856       else if (pdi->is_external)
8857         {
8858           /* Global Variable.
8859              Don't enter into the minimal symbol tables as there is
8860              a minimal symbol table entry from the ELF symbols already.
8861              Enter into partial symbol table if it has a location
8862              descriptor or a type.
8863              If the location descriptor is missing, new_symbol will create
8864              a LOC_UNRESOLVED symbol, the address of the variable will then
8865              be determined from the minimal symbol table whenever the variable
8866              is referenced.
8867              The address for the partial symbol table entry is not
8868              used by GDB, but it comes in handy for debugging partial symbol
8869              table building.  */
8870
8871           if (pdi->d.locdesc || pdi->has_type)
8872             add_psymbol_to_list (actual_name, strlen (actual_name),
8873                                  built_actual_name != NULL,
8874                                  VAR_DOMAIN, LOC_STATIC,
8875                                  &objfile->global_psymbols,
8876                                  addr + baseaddr,
8877                                  cu->language, objfile);
8878         }
8879       else
8880         {
8881           int has_loc = pdi->d.locdesc != NULL;
8882
8883           /* Static Variable.  Skip symbols whose value we cannot know (those
8884              without location descriptors or constant values).  */
8885           if (!has_loc && !pdi->has_const_value)
8886             {
8887               xfree (built_actual_name);
8888               return;
8889             }
8890
8891           add_psymbol_to_list (actual_name, strlen (actual_name),
8892                                built_actual_name != NULL,
8893                                VAR_DOMAIN, LOC_STATIC,
8894                                &objfile->static_psymbols,
8895                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
8896                                cu->language, objfile);
8897         }
8898       break;
8899     case DW_TAG_typedef:
8900     case DW_TAG_base_type:
8901     case DW_TAG_subrange_type:
8902       add_psymbol_to_list (actual_name, strlen (actual_name),
8903                            built_actual_name != NULL,
8904                            VAR_DOMAIN, LOC_TYPEDEF,
8905                            &objfile->static_psymbols,
8906                            0, cu->language, objfile);
8907       break;
8908     case DW_TAG_imported_declaration:
8909     case DW_TAG_namespace:
8910       add_psymbol_to_list (actual_name, strlen (actual_name),
8911                            built_actual_name != NULL,
8912                            VAR_DOMAIN, LOC_TYPEDEF,
8913                            &objfile->global_psymbols,
8914                            0, cu->language, objfile);
8915       break;
8916     case DW_TAG_module:
8917       add_psymbol_to_list (actual_name, strlen (actual_name),
8918                            built_actual_name != NULL,
8919                            MODULE_DOMAIN, LOC_TYPEDEF,
8920                            &objfile->global_psymbols,
8921                            0, cu->language, objfile);
8922       break;
8923     case DW_TAG_class_type:
8924     case DW_TAG_interface_type:
8925     case DW_TAG_structure_type:
8926     case DW_TAG_union_type:
8927     case DW_TAG_enumeration_type:
8928       /* Skip external references.  The DWARF standard says in the section
8929          about "Structure, Union, and Class Type Entries": "An incomplete
8930          structure, union or class type is represented by a structure,
8931          union or class entry that does not have a byte size attribute
8932          and that has a DW_AT_declaration attribute."  */
8933       if (!pdi->has_byte_size && pdi->is_declaration)
8934         {
8935           xfree (built_actual_name);
8936           return;
8937         }
8938
8939       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8940          static vs. global.  */
8941       add_psymbol_to_list (actual_name, strlen (actual_name),
8942                            built_actual_name != NULL,
8943                            STRUCT_DOMAIN, LOC_TYPEDEF,
8944                            cu->language == language_cplus
8945                            ? &objfile->global_psymbols
8946                            : &objfile->static_psymbols,
8947                            0, cu->language, objfile);
8948
8949       break;
8950     case DW_TAG_enumerator:
8951       add_psymbol_to_list (actual_name, strlen (actual_name),
8952                            built_actual_name != NULL,
8953                            VAR_DOMAIN, LOC_CONST,
8954                            cu->language == language_cplus
8955                            ? &objfile->global_psymbols
8956                            : &objfile->static_psymbols,
8957                            0, cu->language, objfile);
8958       break;
8959     default:
8960       break;
8961     }
8962
8963   xfree (built_actual_name);
8964 }
8965
8966 /* Read a partial die corresponding to a namespace; also, add a symbol
8967    corresponding to that namespace to the symbol table.  NAMESPACE is
8968    the name of the enclosing namespace.  */
8969
8970 static void
8971 add_partial_namespace (struct partial_die_info *pdi,
8972                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8973                        int set_addrmap, struct dwarf2_cu *cu)
8974 {
8975   /* Add a symbol for the namespace.  */
8976
8977   add_partial_symbol (pdi, cu);
8978
8979   /* Now scan partial symbols in that namespace.  */
8980
8981   if (pdi->has_children)
8982     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8983 }
8984
8985 /* Read a partial die corresponding to a Fortran module.  */
8986
8987 static void
8988 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8989                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8990 {
8991   /* Add a symbol for the namespace.  */
8992
8993   add_partial_symbol (pdi, cu);
8994
8995   /* Now scan partial symbols in that module.  */
8996
8997   if (pdi->has_children)
8998     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8999 }
9000
9001 /* Read a partial die corresponding to a subprogram or an inlined
9002    subprogram and create a partial symbol for that subprogram.
9003    When the CU language allows it, this routine also defines a partial
9004    symbol for each nested subprogram that this subprogram contains.
9005    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9006    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9007
9008    PDI may also be a lexical block, in which case we simply search
9009    recursively for subprograms defined inside that lexical block.
9010    Again, this is only performed when the CU language allows this
9011    type of definitions.  */
9012
9013 static void
9014 add_partial_subprogram (struct partial_die_info *pdi,
9015                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9016                         int set_addrmap, struct dwarf2_cu *cu)
9017 {
9018   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9019     {
9020       if (pdi->has_pc_info)
9021         {
9022           if (pdi->lowpc < *lowpc)
9023             *lowpc = pdi->lowpc;
9024           if (pdi->highpc > *highpc)
9025             *highpc = pdi->highpc;
9026           if (set_addrmap)
9027             {
9028               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9029               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9030               CORE_ADDR baseaddr;
9031               CORE_ADDR highpc;
9032               CORE_ADDR lowpc;
9033
9034               baseaddr = ANOFFSET (objfile->section_offsets,
9035                                    SECT_OFF_TEXT (objfile));
9036               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9037                                                   pdi->lowpc + baseaddr);
9038               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9039                                                    pdi->highpc + baseaddr);
9040               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9041                                  cu->per_cu->v.psymtab);
9042             }
9043         }
9044
9045       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9046         {
9047           if (!pdi->is_declaration)
9048             /* Ignore subprogram DIEs that do not have a name, they are
9049                illegal.  Do not emit a complaint at this point, we will
9050                do so when we convert this psymtab into a symtab.  */
9051             if (pdi->name)
9052               add_partial_symbol (pdi, cu);
9053         }
9054     }
9055
9056   if (! pdi->has_children)
9057     return;
9058
9059   if (cu->language == language_ada)
9060     {
9061       pdi = pdi->die_child;
9062       while (pdi != NULL)
9063         {
9064           pdi->fixup (cu);
9065           if (pdi->tag == DW_TAG_subprogram
9066               || pdi->tag == DW_TAG_inlined_subroutine
9067               || pdi->tag == DW_TAG_lexical_block)
9068             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9069           pdi = pdi->die_sibling;
9070         }
9071     }
9072 }
9073
9074 /* Read a partial die corresponding to an enumeration type.  */
9075
9076 static void
9077 add_partial_enumeration (struct partial_die_info *enum_pdi,
9078                          struct dwarf2_cu *cu)
9079 {
9080   struct partial_die_info *pdi;
9081
9082   if (enum_pdi->name != NULL)
9083     add_partial_symbol (enum_pdi, cu);
9084
9085   pdi = enum_pdi->die_child;
9086   while (pdi)
9087     {
9088       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9089         complaint (_("malformed enumerator DIE ignored"));
9090       else
9091         add_partial_symbol (pdi, cu);
9092       pdi = pdi->die_sibling;
9093     }
9094 }
9095
9096 /* Return the initial uleb128 in the die at INFO_PTR.  */
9097
9098 static unsigned int
9099 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9100 {
9101   unsigned int bytes_read;
9102
9103   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9104 }
9105
9106 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9107    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9108
9109    Return the corresponding abbrev, or NULL if the number is zero (indicating
9110    an empty DIE).  In either case *BYTES_READ will be set to the length of
9111    the initial number.  */
9112
9113 static struct abbrev_info *
9114 peek_die_abbrev (const die_reader_specs &reader,
9115                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9116 {
9117   dwarf2_cu *cu = reader.cu;
9118   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9119   unsigned int abbrev_number
9120     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9121
9122   if (abbrev_number == 0)
9123     return NULL;
9124
9125   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9126   if (!abbrev)
9127     {
9128       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9129                " at offset %s [in module %s]"),
9130              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9131              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9132     }
9133
9134   return abbrev;
9135 }
9136
9137 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9138    Returns a pointer to the end of a series of DIEs, terminated by an empty
9139    DIE.  Any children of the skipped DIEs will also be skipped.  */
9140
9141 static const gdb_byte *
9142 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9143 {
9144   while (1)
9145     {
9146       unsigned int bytes_read;
9147       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9148
9149       if (abbrev == NULL)
9150         return info_ptr + bytes_read;
9151       else
9152         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9153     }
9154 }
9155
9156 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9157    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9158    abbrev corresponding to that skipped uleb128 should be passed in
9159    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9160    children.  */
9161
9162 static const gdb_byte *
9163 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9164               struct abbrev_info *abbrev)
9165 {
9166   unsigned int bytes_read;
9167   struct attribute attr;
9168   bfd *abfd = reader->abfd;
9169   struct dwarf2_cu *cu = reader->cu;
9170   const gdb_byte *buffer = reader->buffer;
9171   const gdb_byte *buffer_end = reader->buffer_end;
9172   unsigned int form, i;
9173
9174   for (i = 0; i < abbrev->num_attrs; i++)
9175     {
9176       /* The only abbrev we care about is DW_AT_sibling.  */
9177       if (abbrev->attrs[i].name == DW_AT_sibling)
9178         {
9179           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9180           if (attr.form == DW_FORM_ref_addr)
9181             complaint (_("ignoring absolute DW_AT_sibling"));
9182           else
9183             {
9184               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9185               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9186
9187               if (sibling_ptr < info_ptr)
9188                 complaint (_("DW_AT_sibling points backwards"));
9189               else if (sibling_ptr > reader->buffer_end)
9190                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9191               else
9192                 return sibling_ptr;
9193             }
9194         }
9195
9196       /* If it isn't DW_AT_sibling, skip this attribute.  */
9197       form = abbrev->attrs[i].form;
9198     skip_attribute:
9199       switch (form)
9200         {
9201         case DW_FORM_ref_addr:
9202           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9203              and later it is offset sized.  */
9204           if (cu->header.version == 2)
9205             info_ptr += cu->header.addr_size;
9206           else
9207             info_ptr += cu->header.offset_size;
9208           break;
9209         case DW_FORM_GNU_ref_alt:
9210           info_ptr += cu->header.offset_size;
9211           break;
9212         case DW_FORM_addr:
9213           info_ptr += cu->header.addr_size;
9214           break;
9215         case DW_FORM_data1:
9216         case DW_FORM_ref1:
9217         case DW_FORM_flag:
9218           info_ptr += 1;
9219           break;
9220         case DW_FORM_flag_present:
9221         case DW_FORM_implicit_const:
9222           break;
9223         case DW_FORM_data2:
9224         case DW_FORM_ref2:
9225           info_ptr += 2;
9226           break;
9227         case DW_FORM_data4:
9228         case DW_FORM_ref4:
9229           info_ptr += 4;
9230           break;
9231         case DW_FORM_data8:
9232         case DW_FORM_ref8:
9233         case DW_FORM_ref_sig8:
9234           info_ptr += 8;
9235           break;
9236         case DW_FORM_data16:
9237           info_ptr += 16;
9238           break;
9239         case DW_FORM_string:
9240           read_direct_string (abfd, info_ptr, &bytes_read);
9241           info_ptr += bytes_read;
9242           break;
9243         case DW_FORM_sec_offset:
9244         case DW_FORM_strp:
9245         case DW_FORM_GNU_strp_alt:
9246           info_ptr += cu->header.offset_size;
9247           break;
9248         case DW_FORM_exprloc:
9249         case DW_FORM_block:
9250           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9251           info_ptr += bytes_read;
9252           break;
9253         case DW_FORM_block1:
9254           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9255           break;
9256         case DW_FORM_block2:
9257           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9258           break;
9259         case DW_FORM_block4:
9260           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9261           break;
9262         case DW_FORM_sdata:
9263         case DW_FORM_udata:
9264         case DW_FORM_ref_udata:
9265         case DW_FORM_GNU_addr_index:
9266         case DW_FORM_GNU_str_index:
9267           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9268           break;
9269         case DW_FORM_indirect:
9270           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9271           info_ptr += bytes_read;
9272           /* We need to continue parsing from here, so just go back to
9273              the top.  */
9274           goto skip_attribute;
9275
9276         default:
9277           error (_("Dwarf Error: Cannot handle %s "
9278                    "in DWARF reader [in module %s]"),
9279                  dwarf_form_name (form),
9280                  bfd_get_filename (abfd));
9281         }
9282     }
9283
9284   if (abbrev->has_children)
9285     return skip_children (reader, info_ptr);
9286   else
9287     return info_ptr;
9288 }
9289
9290 /* Locate ORIG_PDI's sibling.
9291    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9292
9293 static const gdb_byte *
9294 locate_pdi_sibling (const struct die_reader_specs *reader,
9295                     struct partial_die_info *orig_pdi,
9296                     const gdb_byte *info_ptr)
9297 {
9298   /* Do we know the sibling already?  */
9299
9300   if (orig_pdi->sibling)
9301     return orig_pdi->sibling;
9302
9303   /* Are there any children to deal with?  */
9304
9305   if (!orig_pdi->has_children)
9306     return info_ptr;
9307
9308   /* Skip the children the long way.  */
9309
9310   return skip_children (reader, info_ptr);
9311 }
9312
9313 /* Expand this partial symbol table into a full symbol table.  SELF is
9314    not NULL.  */
9315
9316 static void
9317 dwarf2_read_symtab (struct partial_symtab *self,
9318                     struct objfile *objfile)
9319 {
9320   struct dwarf2_per_objfile *dwarf2_per_objfile
9321     = get_dwarf2_per_objfile (objfile);
9322
9323   if (self->readin)
9324     {
9325       warning (_("bug: psymtab for %s is already read in."),
9326                self->filename);
9327     }
9328   else
9329     {
9330       if (info_verbose)
9331         {
9332           printf_filtered (_("Reading in symbols for %s..."),
9333                            self->filename);
9334           gdb_flush (gdb_stdout);
9335         }
9336
9337       /* If this psymtab is constructed from a debug-only objfile, the
9338          has_section_at_zero flag will not necessarily be correct.  We
9339          can get the correct value for this flag by looking at the data
9340          associated with the (presumably stripped) associated objfile.  */
9341       if (objfile->separate_debug_objfile_backlink)
9342         {
9343           struct dwarf2_per_objfile *dpo_backlink
9344             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9345
9346           dwarf2_per_objfile->has_section_at_zero
9347             = dpo_backlink->has_section_at_zero;
9348         }
9349
9350       dwarf2_per_objfile->reading_partial_symbols = 0;
9351
9352       psymtab_to_symtab_1 (self);
9353
9354       /* Finish up the debug error message.  */
9355       if (info_verbose)
9356         printf_filtered (_("done.\n"));
9357     }
9358
9359   process_cu_includes (dwarf2_per_objfile);
9360 }
9361 \f
9362 /* Reading in full CUs.  */
9363
9364 /* Add PER_CU to the queue.  */
9365
9366 static void
9367 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9368                  enum language pretend_language)
9369 {
9370   struct dwarf2_queue_item *item;
9371
9372   per_cu->queued = 1;
9373   item = XNEW (struct dwarf2_queue_item);
9374   item->per_cu = per_cu;
9375   item->pretend_language = pretend_language;
9376   item->next = NULL;
9377
9378   if (dwarf2_queue == NULL)
9379     dwarf2_queue = item;
9380   else
9381     dwarf2_queue_tail->next = item;
9382
9383   dwarf2_queue_tail = item;
9384 }
9385
9386 /* If PER_CU is not yet queued, add it to the queue.
9387    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9388    dependency.
9389    The result is non-zero if PER_CU was queued, otherwise the result is zero
9390    meaning either PER_CU is already queued or it is already loaded.
9391
9392    N.B. There is an invariant here that if a CU is queued then it is loaded.
9393    The caller is required to load PER_CU if we return non-zero.  */
9394
9395 static int
9396 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9397                        struct dwarf2_per_cu_data *per_cu,
9398                        enum language pretend_language)
9399 {
9400   /* We may arrive here during partial symbol reading, if we need full
9401      DIEs to process an unusual case (e.g. template arguments).  Do
9402      not queue PER_CU, just tell our caller to load its DIEs.  */
9403   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9404     {
9405       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9406         return 1;
9407       return 0;
9408     }
9409
9410   /* Mark the dependence relation so that we don't flush PER_CU
9411      too early.  */
9412   if (dependent_cu != NULL)
9413     dwarf2_add_dependence (dependent_cu, per_cu);
9414
9415   /* If it's already on the queue, we have nothing to do.  */
9416   if (per_cu->queued)
9417     return 0;
9418
9419   /* If the compilation unit is already loaded, just mark it as
9420      used.  */
9421   if (per_cu->cu != NULL)
9422     {
9423       per_cu->cu->last_used = 0;
9424       return 0;
9425     }
9426
9427   /* Add it to the queue.  */
9428   queue_comp_unit (per_cu, pretend_language);
9429
9430   return 1;
9431 }
9432
9433 /* Process the queue.  */
9434
9435 static void
9436 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9437 {
9438   struct dwarf2_queue_item *item, *next_item;
9439
9440   if (dwarf_read_debug)
9441     {
9442       fprintf_unfiltered (gdb_stdlog,
9443                           "Expanding one or more symtabs of objfile %s ...\n",
9444                           objfile_name (dwarf2_per_objfile->objfile));
9445     }
9446
9447   /* The queue starts out with one item, but following a DIE reference
9448      may load a new CU, adding it to the end of the queue.  */
9449   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9450     {
9451       if ((dwarf2_per_objfile->using_index
9452            ? !item->per_cu->v.quick->compunit_symtab
9453            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9454           /* Skip dummy CUs.  */
9455           && item->per_cu->cu != NULL)
9456         {
9457           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9458           unsigned int debug_print_threshold;
9459           char buf[100];
9460
9461           if (per_cu->is_debug_types)
9462             {
9463               struct signatured_type *sig_type =
9464                 (struct signatured_type *) per_cu;
9465
9466               sprintf (buf, "TU %s at offset %s",
9467                        hex_string (sig_type->signature),
9468                        sect_offset_str (per_cu->sect_off));
9469               /* There can be 100s of TUs.
9470                  Only print them in verbose mode.  */
9471               debug_print_threshold = 2;
9472             }
9473           else
9474             {
9475               sprintf (buf, "CU at offset %s",
9476                        sect_offset_str (per_cu->sect_off));
9477               debug_print_threshold = 1;
9478             }
9479
9480           if (dwarf_read_debug >= debug_print_threshold)
9481             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9482
9483           if (per_cu->is_debug_types)
9484             process_full_type_unit (per_cu, item->pretend_language);
9485           else
9486             process_full_comp_unit (per_cu, item->pretend_language);
9487
9488           if (dwarf_read_debug >= debug_print_threshold)
9489             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9490         }
9491
9492       item->per_cu->queued = 0;
9493       next_item = item->next;
9494       xfree (item);
9495     }
9496
9497   dwarf2_queue_tail = NULL;
9498
9499   if (dwarf_read_debug)
9500     {
9501       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9502                           objfile_name (dwarf2_per_objfile->objfile));
9503     }
9504 }
9505
9506 /* Read in full symbols for PST, and anything it depends on.  */
9507
9508 static void
9509 psymtab_to_symtab_1 (struct partial_symtab *pst)
9510 {
9511   struct dwarf2_per_cu_data *per_cu;
9512   int i;
9513
9514   if (pst->readin)
9515     return;
9516
9517   for (i = 0; i < pst->number_of_dependencies; i++)
9518     if (!pst->dependencies[i]->readin
9519         && pst->dependencies[i]->user == NULL)
9520       {
9521         /* Inform about additional files that need to be read in.  */
9522         if (info_verbose)
9523           {
9524             /* FIXME: i18n: Need to make this a single string.  */
9525             fputs_filtered (" ", gdb_stdout);
9526             wrap_here ("");
9527             fputs_filtered ("and ", gdb_stdout);
9528             wrap_here ("");
9529             printf_filtered ("%s...", pst->dependencies[i]->filename);
9530             wrap_here ("");     /* Flush output.  */
9531             gdb_flush (gdb_stdout);
9532           }
9533         psymtab_to_symtab_1 (pst->dependencies[i]);
9534       }
9535
9536   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9537
9538   if (per_cu == NULL)
9539     {
9540       /* It's an include file, no symbols to read for it.
9541          Everything is in the parent symtab.  */
9542       pst->readin = 1;
9543       return;
9544     }
9545
9546   dw2_do_instantiate_symtab (per_cu, false);
9547 }
9548
9549 /* Trivial hash function for die_info: the hash value of a DIE
9550    is its offset in .debug_info for this objfile.  */
9551
9552 static hashval_t
9553 die_hash (const void *item)
9554 {
9555   const struct die_info *die = (const struct die_info *) item;
9556
9557   return to_underlying (die->sect_off);
9558 }
9559
9560 /* Trivial comparison function for die_info structures: two DIEs
9561    are equal if they have the same offset.  */
9562
9563 static int
9564 die_eq (const void *item_lhs, const void *item_rhs)
9565 {
9566   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9567   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9568
9569   return die_lhs->sect_off == die_rhs->sect_off;
9570 }
9571
9572 /* die_reader_func for load_full_comp_unit.
9573    This is identical to read_signatured_type_reader,
9574    but is kept separate for now.  */
9575
9576 static void
9577 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9578                             const gdb_byte *info_ptr,
9579                             struct die_info *comp_unit_die,
9580                             int has_children,
9581                             void *data)
9582 {
9583   struct dwarf2_cu *cu = reader->cu;
9584   enum language *language_ptr = (enum language *) data;
9585
9586   gdb_assert (cu->die_hash == NULL);
9587   cu->die_hash =
9588     htab_create_alloc_ex (cu->header.length / 12,
9589                           die_hash,
9590                           die_eq,
9591                           NULL,
9592                           &cu->comp_unit_obstack,
9593                           hashtab_obstack_allocate,
9594                           dummy_obstack_deallocate);
9595
9596   if (has_children)
9597     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9598                                                   &info_ptr, comp_unit_die);
9599   cu->dies = comp_unit_die;
9600   /* comp_unit_die is not stored in die_hash, no need.  */
9601
9602   /* We try not to read any attributes in this function, because not
9603      all CUs needed for references have been loaded yet, and symbol
9604      table processing isn't initialized.  But we have to set the CU language,
9605      or we won't be able to build types correctly.
9606      Similarly, if we do not read the producer, we can not apply
9607      producer-specific interpretation.  */
9608   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9609 }
9610
9611 /* Load the DIEs associated with PER_CU into memory.  */
9612
9613 static void
9614 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9615                      bool skip_partial,
9616                      enum language pretend_language)
9617 {
9618   gdb_assert (! this_cu->is_debug_types);
9619
9620   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9621                            load_full_comp_unit_reader, &pretend_language);
9622 }
9623
9624 /* Add a DIE to the delayed physname list.  */
9625
9626 static void
9627 add_to_method_list (struct type *type, int fnfield_index, int index,
9628                     const char *name, struct die_info *die,
9629                     struct dwarf2_cu *cu)
9630 {
9631   struct delayed_method_info mi;
9632   mi.type = type;
9633   mi.fnfield_index = fnfield_index;
9634   mi.index = index;
9635   mi.name = name;
9636   mi.die = die;
9637   cu->method_list.push_back (mi);
9638 }
9639
9640 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9641    "const" / "volatile".  If so, decrements LEN by the length of the
9642    modifier and return true.  Otherwise return false.  */
9643
9644 template<size_t N>
9645 static bool
9646 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9647 {
9648   size_t mod_len = sizeof (mod) - 1;
9649   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9650     {
9651       len -= mod_len;
9652       return true;
9653     }
9654   return false;
9655 }
9656
9657 /* Compute the physnames of any methods on the CU's method list.
9658
9659    The computation of method physnames is delayed in order to avoid the
9660    (bad) condition that one of the method's formal parameters is of an as yet
9661    incomplete type.  */
9662
9663 static void
9664 compute_delayed_physnames (struct dwarf2_cu *cu)
9665 {
9666   /* Only C++ delays computing physnames.  */
9667   if (cu->method_list.empty ())
9668     return;
9669   gdb_assert (cu->language == language_cplus);
9670
9671   for (const delayed_method_info &mi : cu->method_list)
9672     {
9673       const char *physname;
9674       struct fn_fieldlist *fn_flp
9675         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9676       physname = dwarf2_physname (mi.name, mi.die, cu);
9677       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9678         = physname ? physname : "";
9679
9680       /* Since there's no tag to indicate whether a method is a
9681          const/volatile overload, extract that information out of the
9682          demangled name.  */
9683       if (physname != NULL)
9684         {
9685           size_t len = strlen (physname);
9686
9687           while (1)
9688             {
9689               if (physname[len] == ')') /* shortcut */
9690                 break;
9691               else if (check_modifier (physname, len, " const"))
9692                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9693               else if (check_modifier (physname, len, " volatile"))
9694                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9695               else
9696                 break;
9697             }
9698         }
9699     }
9700
9701   /* The list is no longer needed.  */
9702   cu->method_list.clear ();
9703 }
9704
9705 /* A wrapper for add_symbol_to_list to ensure that SYMBOL's language is
9706    the same as all other symbols in LISTHEAD.  If a new symbol is added
9707    with a different language, this function asserts.  */
9708
9709 static inline void
9710 dw2_add_symbol_to_list (struct symbol *symbol, struct pending **listhead)
9711 {
9712   /* Only assert if LISTHEAD already contains symbols of a different
9713      language (dict_create_hashed/insert_symbol_hashed requires that all
9714      symbols in this list are of the same language).  */
9715   gdb_assert ((*listhead) == NULL
9716               || (SYMBOL_LANGUAGE ((*listhead)->symbol[0])
9717                   == SYMBOL_LANGUAGE (symbol)));
9718
9719   add_symbol_to_list (symbol, listhead);
9720 }
9721
9722 /* Go objects should be embedded in a DW_TAG_module DIE,
9723    and it's not clear if/how imported objects will appear.
9724    To keep Go support simple until that's worked out,
9725    go back through what we've read and create something usable.
9726    We could do this while processing each DIE, and feels kinda cleaner,
9727    but that way is more invasive.
9728    This is to, for example, allow the user to type "p var" or "b main"
9729    without having to specify the package name, and allow lookups
9730    of module.object to work in contexts that use the expression
9731    parser.  */
9732
9733 static void
9734 fixup_go_packaging (struct dwarf2_cu *cu)
9735 {
9736   char *package_name = NULL;
9737   struct pending *list;
9738   int i;
9739
9740   for (list = *cu->builder->get_global_symbols ();
9741        list != NULL;
9742        list = list->next)
9743     {
9744       for (i = 0; i < list->nsyms; ++i)
9745         {
9746           struct symbol *sym = list->symbol[i];
9747
9748           if (SYMBOL_LANGUAGE (sym) == language_go
9749               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9750             {
9751               char *this_package_name = go_symbol_package_name (sym);
9752
9753               if (this_package_name == NULL)
9754                 continue;
9755               if (package_name == NULL)
9756                 package_name = this_package_name;
9757               else
9758                 {
9759                   struct objfile *objfile
9760                     = cu->per_cu->dwarf2_per_objfile->objfile;
9761                   if (strcmp (package_name, this_package_name) != 0)
9762                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9763                                (symbol_symtab (sym) != NULL
9764                                 ? symtab_to_filename_for_display
9765                                     (symbol_symtab (sym))
9766                                 : objfile_name (objfile)),
9767                                this_package_name, package_name);
9768                   xfree (this_package_name);
9769                 }
9770             }
9771         }
9772     }
9773
9774   if (package_name != NULL)
9775     {
9776       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9777       const char *saved_package_name
9778         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9779                                         package_name,
9780                                         strlen (package_name));
9781       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9782                                      saved_package_name);
9783       struct symbol *sym;
9784
9785       sym = allocate_symbol (objfile);
9786       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9787       SYMBOL_SET_NAMES (sym, saved_package_name,
9788                         strlen (saved_package_name), 0, objfile);
9789       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9790          e.g., "main" finds the "main" module and not C's main().  */
9791       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9792       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9793       SYMBOL_TYPE (sym) = type;
9794
9795       dw2_add_symbol_to_list (sym, cu->builder->get_global_symbols ());
9796
9797       xfree (package_name);
9798     }
9799 }
9800
9801 /* Allocate a fully-qualified name consisting of the two parts on the
9802    obstack.  */
9803
9804 static const char *
9805 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9806 {
9807   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9808 }
9809
9810 /* A helper that allocates a struct discriminant_info to attach to a
9811    union type.  */
9812
9813 static struct discriminant_info *
9814 alloc_discriminant_info (struct type *type, int discriminant_index,
9815                          int default_index)
9816 {
9817   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9818   gdb_assert (discriminant_index == -1
9819               || (discriminant_index >= 0
9820                   && discriminant_index < TYPE_NFIELDS (type)));
9821   gdb_assert (default_index == -1
9822               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9823
9824   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9825
9826   struct discriminant_info *disc
9827     = ((struct discriminant_info *)
9828        TYPE_ZALLOC (type,
9829                     offsetof (struct discriminant_info, discriminants)
9830                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9831   disc->default_index = default_index;
9832   disc->discriminant_index = discriminant_index;
9833
9834   struct dynamic_prop prop;
9835   prop.kind = PROP_UNDEFINED;
9836   prop.data.baton = disc;
9837
9838   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9839
9840   return disc;
9841 }
9842
9843 /* Some versions of rustc emitted enums in an unusual way.
9844
9845    Ordinary enums were emitted as unions.  The first element of each
9846    structure in the union was named "RUST$ENUM$DISR".  This element
9847    held the discriminant.
9848
9849    These versions of Rust also implemented the "non-zero"
9850    optimization.  When the enum had two values, and one is empty and
9851    the other holds a pointer that cannot be zero, the pointer is used
9852    as the discriminant, with a zero value meaning the empty variant.
9853    Here, the union's first member is of the form
9854    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9855    where the fieldnos are the indices of the fields that should be
9856    traversed in order to find the field (which may be several fields deep)
9857    and the variantname is the name of the variant of the case when the
9858    field is zero.
9859
9860    This function recognizes whether TYPE is of one of these forms,
9861    and, if so, smashes it to be a variant type.  */
9862
9863 static void
9864 quirk_rust_enum (struct type *type, struct objfile *objfile)
9865 {
9866   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9867
9868   /* We don't need to deal with empty enums.  */
9869   if (TYPE_NFIELDS (type) == 0)
9870     return;
9871
9872 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9873   if (TYPE_NFIELDS (type) == 1
9874       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9875     {
9876       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9877
9878       /* Decode the field name to find the offset of the
9879          discriminant.  */
9880       ULONGEST bit_offset = 0;
9881       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9882       while (name[0] >= '0' && name[0] <= '9')
9883         {
9884           char *tail;
9885           unsigned long index = strtoul (name, &tail, 10);
9886           name = tail;
9887           if (*name != '$'
9888               || index >= TYPE_NFIELDS (field_type)
9889               || (TYPE_FIELD_LOC_KIND (field_type, index)
9890                   != FIELD_LOC_KIND_BITPOS))
9891             {
9892               complaint (_("Could not parse Rust enum encoding string \"%s\""
9893                            "[in module %s]"),
9894                          TYPE_FIELD_NAME (type, 0),
9895                          objfile_name (objfile));
9896               return;
9897             }
9898           ++name;
9899
9900           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9901           field_type = TYPE_FIELD_TYPE (field_type, index);
9902         }
9903
9904       /* Make a union to hold the variants.  */
9905       struct type *union_type = alloc_type (objfile);
9906       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9907       TYPE_NFIELDS (union_type) = 3;
9908       TYPE_FIELDS (union_type)
9909         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9910       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9911       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9912
9913       /* Put the discriminant must at index 0.  */
9914       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9915       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9916       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9917       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9918
9919       /* The order of fields doesn't really matter, so put the real
9920          field at index 1 and the data-less field at index 2.  */
9921       struct discriminant_info *disc
9922         = alloc_discriminant_info (union_type, 0, 1);
9923       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9924       TYPE_FIELD_NAME (union_type, 1)
9925         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9926       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9927         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9928                               TYPE_FIELD_NAME (union_type, 1));
9929
9930       const char *dataless_name
9931         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9932                               name);
9933       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9934                                               dataless_name);
9935       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9936       /* NAME points into the original discriminant name, which
9937          already has the correct lifetime.  */
9938       TYPE_FIELD_NAME (union_type, 2) = name;
9939       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9940       disc->discriminants[2] = 0;
9941
9942       /* Smash this type to be a structure type.  We have to do this
9943          because the type has already been recorded.  */
9944       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9945       TYPE_NFIELDS (type) = 1;
9946       TYPE_FIELDS (type)
9947         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9948
9949       /* Install the variant part.  */
9950       TYPE_FIELD_TYPE (type, 0) = union_type;
9951       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9952       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9953     }
9954   else if (TYPE_NFIELDS (type) == 1)
9955     {
9956       /* We assume that a union with a single field is a univariant
9957          enum.  */
9958       /* Smash this type to be a structure type.  We have to do this
9959          because the type has already been recorded.  */
9960       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9961
9962       /* Make a union to hold the variants.  */
9963       struct type *union_type = alloc_type (objfile);
9964       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9965       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
9966       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9967       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9968       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
9969
9970       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
9971       const char *variant_name
9972         = rust_last_path_segment (TYPE_NAME (field_type));
9973       TYPE_FIELD_NAME (union_type, 0) = variant_name;
9974       TYPE_NAME (field_type)
9975         = rust_fully_qualify (&objfile->objfile_obstack,
9976                               TYPE_NAME (type), variant_name);
9977
9978       /* Install the union in the outer struct type.  */
9979       TYPE_NFIELDS (type) = 1;
9980       TYPE_FIELDS (type)
9981         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
9982       TYPE_FIELD_TYPE (type, 0) = union_type;
9983       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9984       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9985
9986       alloc_discriminant_info (union_type, -1, 0);
9987     }
9988   else
9989     {
9990       struct type *disr_type = nullptr;
9991       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
9992         {
9993           disr_type = TYPE_FIELD_TYPE (type, i);
9994
9995           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
9996             {
9997               /* All fields of a true enum will be structs.  */
9998               return;
9999             }
10000           else if (TYPE_NFIELDS (disr_type) == 0)
10001             {
10002               /* Could be data-less variant, so keep going.  */
10003               disr_type = nullptr;
10004             }
10005           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10006                            "RUST$ENUM$DISR") != 0)
10007             {
10008               /* Not a Rust enum.  */
10009               return;
10010             }
10011           else
10012             {
10013               /* Found one.  */
10014               break;
10015             }
10016         }
10017
10018       /* If we got here without a discriminant, then it's probably
10019          just a union.  */
10020       if (disr_type == nullptr)
10021         return;
10022
10023       /* Smash this type to be a structure type.  We have to do this
10024          because the type has already been recorded.  */
10025       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10026
10027       /* Make a union to hold the variants.  */
10028       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10029       struct type *union_type = alloc_type (objfile);
10030       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10031       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10032       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10033       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10034       TYPE_FIELDS (union_type)
10035         = (struct field *) TYPE_ZALLOC (union_type,
10036                                         (TYPE_NFIELDS (union_type)
10037                                          * sizeof (struct field)));
10038
10039       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10040               TYPE_NFIELDS (type) * sizeof (struct field));
10041
10042       /* Install the discriminant at index 0 in the union.  */
10043       TYPE_FIELD (union_type, 0) = *disr_field;
10044       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10045       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10046
10047       /* Install the union in the outer struct type.  */
10048       TYPE_FIELD_TYPE (type, 0) = union_type;
10049       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10050       TYPE_NFIELDS (type) = 1;
10051
10052       /* Set the size and offset of the union type.  */
10053       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10054
10055       /* We need a way to find the correct discriminant given a
10056          variant name.  For convenience we build a map here.  */
10057       struct type *enum_type = FIELD_TYPE (*disr_field);
10058       std::unordered_map<std::string, ULONGEST> discriminant_map;
10059       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10060         {
10061           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10062             {
10063               const char *name
10064                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10065               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10066             }
10067         }
10068
10069       int n_fields = TYPE_NFIELDS (union_type);
10070       struct discriminant_info *disc
10071         = alloc_discriminant_info (union_type, 0, -1);
10072       /* Skip the discriminant here.  */
10073       for (int i = 1; i < n_fields; ++i)
10074         {
10075           /* Find the final word in the name of this variant's type.
10076              That name can be used to look up the correct
10077              discriminant.  */
10078           const char *variant_name
10079             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10080                                                                   i)));
10081
10082           auto iter = discriminant_map.find (variant_name);
10083           if (iter != discriminant_map.end ())
10084             disc->discriminants[i] = iter->second;
10085
10086           /* Remove the discriminant field, if it exists.  */
10087           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10088           if (TYPE_NFIELDS (sub_type) > 0)
10089             {
10090               --TYPE_NFIELDS (sub_type);
10091               ++TYPE_FIELDS (sub_type);
10092             }
10093           TYPE_FIELD_NAME (union_type, i) = variant_name;
10094           TYPE_NAME (sub_type)
10095             = rust_fully_qualify (&objfile->objfile_obstack,
10096                                   TYPE_NAME (type), variant_name);
10097         }
10098     }
10099 }
10100
10101 /* Rewrite some Rust unions to be structures with variants parts.  */
10102
10103 static void
10104 rust_union_quirks (struct dwarf2_cu *cu)
10105 {
10106   gdb_assert (cu->language == language_rust);
10107   for (type *type_ : cu->rust_unions)
10108     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10109   /* We don't need this any more.  */
10110   cu->rust_unions.clear ();
10111 }
10112
10113 /* Return the symtab for PER_CU.  This works properly regardless of
10114    whether we're using the index or psymtabs.  */
10115
10116 static struct compunit_symtab *
10117 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10118 {
10119   return (per_cu->dwarf2_per_objfile->using_index
10120           ? per_cu->v.quick->compunit_symtab
10121           : per_cu->v.psymtab->compunit_symtab);
10122 }
10123
10124 /* A helper function for computing the list of all symbol tables
10125    included by PER_CU.  */
10126
10127 static void
10128 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10129                                 htab_t all_children, htab_t all_type_symtabs,
10130                                 struct dwarf2_per_cu_data *per_cu,
10131                                 struct compunit_symtab *immediate_parent)
10132 {
10133   void **slot;
10134   int ix;
10135   struct compunit_symtab *cust;
10136   struct dwarf2_per_cu_data *iter;
10137
10138   slot = htab_find_slot (all_children, per_cu, INSERT);
10139   if (*slot != NULL)
10140     {
10141       /* This inclusion and its children have been processed.  */
10142       return;
10143     }
10144
10145   *slot = per_cu;
10146   /* Only add a CU if it has a symbol table.  */
10147   cust = get_compunit_symtab (per_cu);
10148   if (cust != NULL)
10149     {
10150       /* If this is a type unit only add its symbol table if we haven't
10151          seen it yet (type unit per_cu's can share symtabs).  */
10152       if (per_cu->is_debug_types)
10153         {
10154           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10155           if (*slot == NULL)
10156             {
10157               *slot = cust;
10158               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10159               if (cust->user == NULL)
10160                 cust->user = immediate_parent;
10161             }
10162         }
10163       else
10164         {
10165           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10166           if (cust->user == NULL)
10167             cust->user = immediate_parent;
10168         }
10169     }
10170
10171   for (ix = 0;
10172        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10173        ++ix)
10174     {
10175       recursively_compute_inclusions (result, all_children,
10176                                       all_type_symtabs, iter, cust);
10177     }
10178 }
10179
10180 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10181    PER_CU.  */
10182
10183 static void
10184 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10185 {
10186   gdb_assert (! per_cu->is_debug_types);
10187
10188   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10189     {
10190       int ix, len;
10191       struct dwarf2_per_cu_data *per_cu_iter;
10192       struct compunit_symtab *compunit_symtab_iter;
10193       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10194       htab_t all_children, all_type_symtabs;
10195       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10196
10197       /* If we don't have a symtab, we can just skip this case.  */
10198       if (cust == NULL)
10199         return;
10200
10201       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10202                                         NULL, xcalloc, xfree);
10203       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10204                                             NULL, xcalloc, xfree);
10205
10206       for (ix = 0;
10207            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10208                         ix, per_cu_iter);
10209            ++ix)
10210         {
10211           recursively_compute_inclusions (&result_symtabs, all_children,
10212                                           all_type_symtabs, per_cu_iter,
10213                                           cust);
10214         }
10215
10216       /* Now we have a transitive closure of all the included symtabs.  */
10217       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10218       cust->includes
10219         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10220                      struct compunit_symtab *, len + 1);
10221       for (ix = 0;
10222            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10223                         compunit_symtab_iter);
10224            ++ix)
10225         cust->includes[ix] = compunit_symtab_iter;
10226       cust->includes[len] = NULL;
10227
10228       VEC_free (compunit_symtab_ptr, result_symtabs);
10229       htab_delete (all_children);
10230       htab_delete (all_type_symtabs);
10231     }
10232 }
10233
10234 /* Compute the 'includes' field for the symtabs of all the CUs we just
10235    read.  */
10236
10237 static void
10238 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10239 {
10240   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10241     {
10242       if (! iter->is_debug_types)
10243         compute_compunit_symtab_includes (iter);
10244     }
10245
10246   dwarf2_per_objfile->just_read_cus.clear ();
10247 }
10248
10249 /* Generate full symbol information for PER_CU, whose DIEs have
10250    already been loaded into memory.  */
10251
10252 static void
10253 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10254                         enum language pretend_language)
10255 {
10256   struct dwarf2_cu *cu = per_cu->cu;
10257   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10258   struct objfile *objfile = dwarf2_per_objfile->objfile;
10259   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10260   CORE_ADDR lowpc, highpc;
10261   struct compunit_symtab *cust;
10262   CORE_ADDR baseaddr;
10263   struct block *static_block;
10264   CORE_ADDR addr;
10265
10266   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10267
10268   /* Clear the list here in case something was left over.  */
10269   cu->method_list.clear ();
10270
10271   cu->language = pretend_language;
10272   cu->language_defn = language_def (cu->language);
10273
10274   /* Do line number decoding in read_file_scope () */
10275   process_die (cu->dies, cu);
10276
10277   /* For now fudge the Go package.  */
10278   if (cu->language == language_go)
10279     fixup_go_packaging (cu);
10280
10281   /* Now that we have processed all the DIEs in the CU, all the types 
10282      should be complete, and it should now be safe to compute all of the
10283      physnames.  */
10284   compute_delayed_physnames (cu);
10285
10286   if (cu->language == language_rust)
10287     rust_union_quirks (cu);
10288
10289   /* Some compilers don't define a DW_AT_high_pc attribute for the
10290      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10291      it, by scanning the DIE's below the compilation unit.  */
10292   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10293
10294   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10295   static_block = cu->builder->end_symtab_get_static_block (addr, 0, 1);
10296
10297   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10298      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10299      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10300      addrmap to help ensure it has an accurate map of pc values belonging to
10301      this comp unit.  */
10302   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10303
10304   cust = cu->builder->end_symtab_from_static_block (static_block,
10305                                                     SECT_OFF_TEXT (objfile),
10306                                                     0);
10307
10308   if (cust != NULL)
10309     {
10310       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10311
10312       /* Set symtab language to language from DW_AT_language.  If the
10313          compilation is from a C file generated by language preprocessors, do
10314          not set the language if it was already deduced by start_subfile.  */
10315       if (!(cu->language == language_c
10316             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10317         COMPUNIT_FILETABS (cust)->language = cu->language;
10318
10319       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10320          produce DW_AT_location with location lists but it can be possibly
10321          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10322          there were bugs in prologue debug info, fixed later in GCC-4.5
10323          by "unwind info for epilogues" patch (which is not directly related).
10324
10325          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10326          needed, it would be wrong due to missing DW_AT_producer there.
10327
10328          Still one can confuse GDB by using non-standard GCC compilation
10329          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10330          */ 
10331       if (cu->has_loclist && gcc_4_minor >= 5)
10332         cust->locations_valid = 1;
10333
10334       if (gcc_4_minor >= 5)
10335         cust->epilogue_unwind_valid = 1;
10336
10337       cust->call_site_htab = cu->call_site_htab;
10338     }
10339
10340   if (dwarf2_per_objfile->using_index)
10341     per_cu->v.quick->compunit_symtab = cust;
10342   else
10343     {
10344       struct partial_symtab *pst = per_cu->v.psymtab;
10345       pst->compunit_symtab = cust;
10346       pst->readin = 1;
10347     }
10348
10349   /* Push it for inclusion processing later.  */
10350   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10351
10352   /* Not needed any more.  */
10353   cu->builder.reset ();
10354 }
10355
10356 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10357    already been loaded into memory.  */
10358
10359 static void
10360 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10361                         enum language pretend_language)
10362 {
10363   struct dwarf2_cu *cu = per_cu->cu;
10364   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10365   struct objfile *objfile = dwarf2_per_objfile->objfile;
10366   struct compunit_symtab *cust;
10367   struct signatured_type *sig_type;
10368
10369   gdb_assert (per_cu->is_debug_types);
10370   sig_type = (struct signatured_type *) per_cu;
10371
10372   /* Clear the list here in case something was left over.  */
10373   cu->method_list.clear ();
10374
10375   cu->language = pretend_language;
10376   cu->language_defn = language_def (cu->language);
10377
10378   /* The symbol tables are set up in read_type_unit_scope.  */
10379   process_die (cu->dies, cu);
10380
10381   /* For now fudge the Go package.  */
10382   if (cu->language == language_go)
10383     fixup_go_packaging (cu);
10384
10385   /* Now that we have processed all the DIEs in the CU, all the types 
10386      should be complete, and it should now be safe to compute all of the
10387      physnames.  */
10388   compute_delayed_physnames (cu);
10389
10390   if (cu->language == language_rust)
10391     rust_union_quirks (cu);
10392
10393   /* TUs share symbol tables.
10394      If this is the first TU to use this symtab, complete the construction
10395      of it with end_expandable_symtab.  Otherwise, complete the addition of
10396      this TU's symbols to the existing symtab.  */
10397   if (sig_type->type_unit_group->compunit_symtab == NULL)
10398     {
10399       cust = cu->builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10400       sig_type->type_unit_group->compunit_symtab = cust;
10401
10402       if (cust != NULL)
10403         {
10404           /* Set symtab language to language from DW_AT_language.  If the
10405              compilation is from a C file generated by language preprocessors,
10406              do not set the language if it was already deduced by
10407              start_subfile.  */
10408           if (!(cu->language == language_c
10409                 && COMPUNIT_FILETABS (cust)->language != language_c))
10410             COMPUNIT_FILETABS (cust)->language = cu->language;
10411         }
10412     }
10413   else
10414     {
10415       cu->builder->augment_type_symtab ();
10416       cust = sig_type->type_unit_group->compunit_symtab;
10417     }
10418
10419   if (dwarf2_per_objfile->using_index)
10420     per_cu->v.quick->compunit_symtab = cust;
10421   else
10422     {
10423       struct partial_symtab *pst = per_cu->v.psymtab;
10424       pst->compunit_symtab = cust;
10425       pst->readin = 1;
10426     }
10427
10428   /* Not needed any more.  */
10429   cu->builder.reset ();
10430 }
10431
10432 /* Process an imported unit DIE.  */
10433
10434 static void
10435 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10436 {
10437   struct attribute *attr;
10438
10439   /* For now we don't handle imported units in type units.  */
10440   if (cu->per_cu->is_debug_types)
10441     {
10442       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10443                " supported in type units [in module %s]"),
10444              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10445     }
10446
10447   attr = dwarf2_attr (die, DW_AT_import, cu);
10448   if (attr != NULL)
10449     {
10450       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10451       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10452       dwarf2_per_cu_data *per_cu
10453         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10454                                             cu->per_cu->dwarf2_per_objfile);
10455
10456       /* If necessary, add it to the queue and load its DIEs.  */
10457       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10458         load_full_comp_unit (per_cu, false, cu->language);
10459
10460       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10461                      per_cu);
10462     }
10463 }
10464
10465 /* RAII object that represents a process_die scope: i.e.,
10466    starts/finishes processing a DIE.  */
10467 class process_die_scope
10468 {
10469 public:
10470   process_die_scope (die_info *die, dwarf2_cu *cu)
10471     : m_die (die), m_cu (cu)
10472   {
10473     /* We should only be processing DIEs not already in process.  */
10474     gdb_assert (!m_die->in_process);
10475     m_die->in_process = true;
10476   }
10477
10478   ~process_die_scope ()
10479   {
10480     m_die->in_process = false;
10481
10482     /* If we're done processing the DIE for the CU that owns the line
10483        header, we don't need the line header anymore.  */
10484     if (m_cu->line_header_die_owner == m_die)
10485       {
10486         delete m_cu->line_header;
10487         m_cu->line_header = NULL;
10488         m_cu->line_header_die_owner = NULL;
10489       }
10490   }
10491
10492 private:
10493   die_info *m_die;
10494   dwarf2_cu *m_cu;
10495 };
10496
10497 /* Process a die and its children.  */
10498
10499 static void
10500 process_die (struct die_info *die, struct dwarf2_cu *cu)
10501 {
10502   process_die_scope scope (die, cu);
10503
10504   switch (die->tag)
10505     {
10506     case DW_TAG_padding:
10507       break;
10508     case DW_TAG_compile_unit:
10509     case DW_TAG_partial_unit:
10510       read_file_scope (die, cu);
10511       break;
10512     case DW_TAG_type_unit:
10513       read_type_unit_scope (die, cu);
10514       break;
10515     case DW_TAG_subprogram:
10516     case DW_TAG_inlined_subroutine:
10517       read_func_scope (die, cu);
10518       break;
10519     case DW_TAG_lexical_block:
10520     case DW_TAG_try_block:
10521     case DW_TAG_catch_block:
10522       read_lexical_block_scope (die, cu);
10523       break;
10524     case DW_TAG_call_site:
10525     case DW_TAG_GNU_call_site:
10526       read_call_site_scope (die, cu);
10527       break;
10528     case DW_TAG_class_type:
10529     case DW_TAG_interface_type:
10530     case DW_TAG_structure_type:
10531     case DW_TAG_union_type:
10532       process_structure_scope (die, cu);
10533       break;
10534     case DW_TAG_enumeration_type:
10535       process_enumeration_scope (die, cu);
10536       break;
10537
10538     /* These dies have a type, but processing them does not create
10539        a symbol or recurse to process the children.  Therefore we can
10540        read them on-demand through read_type_die.  */
10541     case DW_TAG_subroutine_type:
10542     case DW_TAG_set_type:
10543     case DW_TAG_array_type:
10544     case DW_TAG_pointer_type:
10545     case DW_TAG_ptr_to_member_type:
10546     case DW_TAG_reference_type:
10547     case DW_TAG_rvalue_reference_type:
10548     case DW_TAG_string_type:
10549       break;
10550
10551     case DW_TAG_base_type:
10552     case DW_TAG_subrange_type:
10553     case DW_TAG_typedef:
10554       /* Add a typedef symbol for the type definition, if it has a
10555          DW_AT_name.  */
10556       new_symbol (die, read_type_die (die, cu), cu);
10557       break;
10558     case DW_TAG_common_block:
10559       read_common_block (die, cu);
10560       break;
10561     case DW_TAG_common_inclusion:
10562       break;
10563     case DW_TAG_namespace:
10564       cu->processing_has_namespace_info = 1;
10565       read_namespace (die, cu);
10566       break;
10567     case DW_TAG_module:
10568       cu->processing_has_namespace_info = 1;
10569       read_module (die, cu);
10570       break;
10571     case DW_TAG_imported_declaration:
10572       cu->processing_has_namespace_info = 1;
10573       if (read_namespace_alias (die, cu))
10574         break;
10575       /* The declaration is not a global namespace alias.  */
10576       /* Fall through.  */
10577     case DW_TAG_imported_module:
10578       cu->processing_has_namespace_info = 1;
10579       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10580                                  || cu->language != language_fortran))
10581         complaint (_("Tag '%s' has unexpected children"),
10582                    dwarf_tag_name (die->tag));
10583       read_import_statement (die, cu);
10584       break;
10585
10586     case DW_TAG_imported_unit:
10587       process_imported_unit_die (die, cu);
10588       break;
10589
10590     case DW_TAG_variable:
10591       read_variable (die, cu);
10592       break;
10593
10594     default:
10595       new_symbol (die, NULL, cu);
10596       break;
10597     }
10598 }
10599 \f
10600 /* DWARF name computation.  */
10601
10602 /* A helper function for dwarf2_compute_name which determines whether DIE
10603    needs to have the name of the scope prepended to the name listed in the
10604    die.  */
10605
10606 static int
10607 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10608 {
10609   struct attribute *attr;
10610
10611   switch (die->tag)
10612     {
10613     case DW_TAG_namespace:
10614     case DW_TAG_typedef:
10615     case DW_TAG_class_type:
10616     case DW_TAG_interface_type:
10617     case DW_TAG_structure_type:
10618     case DW_TAG_union_type:
10619     case DW_TAG_enumeration_type:
10620     case DW_TAG_enumerator:
10621     case DW_TAG_subprogram:
10622     case DW_TAG_inlined_subroutine:
10623     case DW_TAG_member:
10624     case DW_TAG_imported_declaration:
10625       return 1;
10626
10627     case DW_TAG_variable:
10628     case DW_TAG_constant:
10629       /* We only need to prefix "globally" visible variables.  These include
10630          any variable marked with DW_AT_external or any variable that
10631          lives in a namespace.  [Variables in anonymous namespaces
10632          require prefixing, but they are not DW_AT_external.]  */
10633
10634       if (dwarf2_attr (die, DW_AT_specification, cu))
10635         {
10636           struct dwarf2_cu *spec_cu = cu;
10637
10638           return die_needs_namespace (die_specification (die, &spec_cu),
10639                                       spec_cu);
10640         }
10641
10642       attr = dwarf2_attr (die, DW_AT_external, cu);
10643       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10644           && die->parent->tag != DW_TAG_module)
10645         return 0;
10646       /* A variable in a lexical block of some kind does not need a
10647          namespace, even though in C++ such variables may be external
10648          and have a mangled name.  */
10649       if (die->parent->tag ==  DW_TAG_lexical_block
10650           || die->parent->tag ==  DW_TAG_try_block
10651           || die->parent->tag ==  DW_TAG_catch_block
10652           || die->parent->tag == DW_TAG_subprogram)
10653         return 0;
10654       return 1;
10655
10656     default:
10657       return 0;
10658     }
10659 }
10660
10661 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10662    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10663    defined for the given DIE.  */
10664
10665 static struct attribute *
10666 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10667 {
10668   struct attribute *attr;
10669
10670   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10671   if (attr == NULL)
10672     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10673
10674   return attr;
10675 }
10676
10677 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10678    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10679    defined for the given DIE.  */
10680
10681 static const char *
10682 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10683 {
10684   const char *linkage_name;
10685
10686   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10687   if (linkage_name == NULL)
10688     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10689
10690   return linkage_name;
10691 }
10692
10693 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10694    compute the physname for the object, which include a method's:
10695    - formal parameters (C++),
10696    - receiver type (Go),
10697
10698    The term "physname" is a bit confusing.
10699    For C++, for example, it is the demangled name.
10700    For Go, for example, it's the mangled name.
10701
10702    For Ada, return the DIE's linkage name rather than the fully qualified
10703    name.  PHYSNAME is ignored..
10704
10705    The result is allocated on the objfile_obstack and canonicalized.  */
10706
10707 static const char *
10708 dwarf2_compute_name (const char *name,
10709                      struct die_info *die, struct dwarf2_cu *cu,
10710                      int physname)
10711 {
10712   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10713
10714   if (name == NULL)
10715     name = dwarf2_name (die, cu);
10716
10717   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10718      but otherwise compute it by typename_concat inside GDB.
10719      FIXME: Actually this is not really true, or at least not always true.
10720      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10721      Fortran names because there is no mangling standard.  So new_symbol
10722      will set the demangled name to the result of dwarf2_full_name, and it is
10723      the demangled name that GDB uses if it exists.  */
10724   if (cu->language == language_ada
10725       || (cu->language == language_fortran && physname))
10726     {
10727       /* For Ada unit, we prefer the linkage name over the name, as
10728          the former contains the exported name, which the user expects
10729          to be able to reference.  Ideally, we want the user to be able
10730          to reference this entity using either natural or linkage name,
10731          but we haven't started looking at this enhancement yet.  */
10732       const char *linkage_name = dw2_linkage_name (die, cu);
10733
10734       if (linkage_name != NULL)
10735         return linkage_name;
10736     }
10737
10738   /* These are the only languages we know how to qualify names in.  */
10739   if (name != NULL
10740       && (cu->language == language_cplus
10741           || cu->language == language_fortran || cu->language == language_d
10742           || cu->language == language_rust))
10743     {
10744       if (die_needs_namespace (die, cu))
10745         {
10746           const char *prefix;
10747           const char *canonical_name = NULL;
10748
10749           string_file buf;
10750
10751           prefix = determine_prefix (die, cu);
10752           if (*prefix != '\0')
10753             {
10754               char *prefixed_name = typename_concat (NULL, prefix, name,
10755                                                      physname, cu);
10756
10757               buf.puts (prefixed_name);
10758               xfree (prefixed_name);
10759             }
10760           else
10761             buf.puts (name);
10762
10763           /* Template parameters may be specified in the DIE's DW_AT_name, or
10764              as children with DW_TAG_template_type_param or
10765              DW_TAG_value_type_param.  If the latter, add them to the name
10766              here.  If the name already has template parameters, then
10767              skip this step; some versions of GCC emit both, and
10768              it is more efficient to use the pre-computed name.
10769
10770              Something to keep in mind about this process: it is very
10771              unlikely, or in some cases downright impossible, to produce
10772              something that will match the mangled name of a function.
10773              If the definition of the function has the same debug info,
10774              we should be able to match up with it anyway.  But fallbacks
10775              using the minimal symbol, for instance to find a method
10776              implemented in a stripped copy of libstdc++, will not work.
10777              If we do not have debug info for the definition, we will have to
10778              match them up some other way.
10779
10780              When we do name matching there is a related problem with function
10781              templates; two instantiated function templates are allowed to
10782              differ only by their return types, which we do not add here.  */
10783
10784           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10785             {
10786               struct attribute *attr;
10787               struct die_info *child;
10788               int first = 1;
10789
10790               die->building_fullname = 1;
10791
10792               for (child = die->child; child != NULL; child = child->sibling)
10793                 {
10794                   struct type *type;
10795                   LONGEST value;
10796                   const gdb_byte *bytes;
10797                   struct dwarf2_locexpr_baton *baton;
10798                   struct value *v;
10799
10800                   if (child->tag != DW_TAG_template_type_param
10801                       && child->tag != DW_TAG_template_value_param)
10802                     continue;
10803
10804                   if (first)
10805                     {
10806                       buf.puts ("<");
10807                       first = 0;
10808                     }
10809                   else
10810                     buf.puts (", ");
10811
10812                   attr = dwarf2_attr (child, DW_AT_type, cu);
10813                   if (attr == NULL)
10814                     {
10815                       complaint (_("template parameter missing DW_AT_type"));
10816                       buf.puts ("UNKNOWN_TYPE");
10817                       continue;
10818                     }
10819                   type = die_type (child, cu);
10820
10821                   if (child->tag == DW_TAG_template_type_param)
10822                     {
10823                       c_print_type (type, "", &buf, -1, 0, cu->language,
10824                                     &type_print_raw_options);
10825                       continue;
10826                     }
10827
10828                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10829                   if (attr == NULL)
10830                     {
10831                       complaint (_("template parameter missing "
10832                                    "DW_AT_const_value"));
10833                       buf.puts ("UNKNOWN_VALUE");
10834                       continue;
10835                     }
10836
10837                   dwarf2_const_value_attr (attr, type, name,
10838                                            &cu->comp_unit_obstack, cu,
10839                                            &value, &bytes, &baton);
10840
10841                   if (TYPE_NOSIGN (type))
10842                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10843                        changed, this can use value_print instead.  */
10844                     c_printchar (value, type, &buf);
10845                   else
10846                     {
10847                       struct value_print_options opts;
10848
10849                       if (baton != NULL)
10850                         v = dwarf2_evaluate_loc_desc (type, NULL,
10851                                                       baton->data,
10852                                                       baton->size,
10853                                                       baton->per_cu);
10854                       else if (bytes != NULL)
10855                         {
10856                           v = allocate_value (type);
10857                           memcpy (value_contents_writeable (v), bytes,
10858                                   TYPE_LENGTH (type));
10859                         }
10860                       else
10861                         v = value_from_longest (type, value);
10862
10863                       /* Specify decimal so that we do not depend on
10864                          the radix.  */
10865                       get_formatted_print_options (&opts, 'd');
10866                       opts.raw = 1;
10867                       value_print (v, &buf, &opts);
10868                       release_value (v);
10869                     }
10870                 }
10871
10872               die->building_fullname = 0;
10873
10874               if (!first)
10875                 {
10876                   /* Close the argument list, with a space if necessary
10877                      (nested templates).  */
10878                   if (!buf.empty () && buf.string ().back () == '>')
10879                     buf.puts (" >");
10880                   else
10881                     buf.puts (">");
10882                 }
10883             }
10884
10885           /* For C++ methods, append formal parameter type
10886              information, if PHYSNAME.  */
10887
10888           if (physname && die->tag == DW_TAG_subprogram
10889               && cu->language == language_cplus)
10890             {
10891               struct type *type = read_type_die (die, cu);
10892
10893               c_type_print_args (type, &buf, 1, cu->language,
10894                                  &type_print_raw_options);
10895
10896               if (cu->language == language_cplus)
10897                 {
10898                   /* Assume that an artificial first parameter is
10899                      "this", but do not crash if it is not.  RealView
10900                      marks unnamed (and thus unused) parameters as
10901                      artificial; there is no way to differentiate
10902                      the two cases.  */
10903                   if (TYPE_NFIELDS (type) > 0
10904                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10905                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10906                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10907                                                                         0))))
10908                     buf.puts (" const");
10909                 }
10910             }
10911
10912           const std::string &intermediate_name = buf.string ();
10913
10914           if (cu->language == language_cplus)
10915             canonical_name
10916               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10917                                           &objfile->per_bfd->storage_obstack);
10918
10919           /* If we only computed INTERMEDIATE_NAME, or if
10920              INTERMEDIATE_NAME is already canonical, then we need to
10921              copy it to the appropriate obstack.  */
10922           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10923             name = ((const char *)
10924                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10925                                    intermediate_name.c_str (),
10926                                    intermediate_name.length ()));
10927           else
10928             name = canonical_name;
10929         }
10930     }
10931
10932   return name;
10933 }
10934
10935 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10936    If scope qualifiers are appropriate they will be added.  The result
10937    will be allocated on the storage_obstack, or NULL if the DIE does
10938    not have a name.  NAME may either be from a previous call to
10939    dwarf2_name or NULL.
10940
10941    The output string will be canonicalized (if C++).  */
10942
10943 static const char *
10944 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10945 {
10946   return dwarf2_compute_name (name, die, cu, 0);
10947 }
10948
10949 /* Construct a physname for the given DIE in CU.  NAME may either be
10950    from a previous call to dwarf2_name or NULL.  The result will be
10951    allocated on the objfile_objstack or NULL if the DIE does not have a
10952    name.
10953
10954    The output string will be canonicalized (if C++).  */
10955
10956 static const char *
10957 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10958 {
10959   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10960   const char *retval, *mangled = NULL, *canon = NULL;
10961   int need_copy = 1;
10962
10963   /* In this case dwarf2_compute_name is just a shortcut not building anything
10964      on its own.  */
10965   if (!die_needs_namespace (die, cu))
10966     return dwarf2_compute_name (name, die, cu, 1);
10967
10968   mangled = dw2_linkage_name (die, cu);
10969
10970   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10971      See https://github.com/rust-lang/rust/issues/32925.  */
10972   if (cu->language == language_rust && mangled != NULL
10973       && strchr (mangled, '{') != NULL)
10974     mangled = NULL;
10975
10976   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10977      has computed.  */
10978   gdb::unique_xmalloc_ptr<char> demangled;
10979   if (mangled != NULL)
10980     {
10981
10982       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
10983         {
10984           /* Do nothing (do not demangle the symbol name).  */
10985         }
10986       else if (cu->language == language_go)
10987         {
10988           /* This is a lie, but we already lie to the caller new_symbol.
10989              new_symbol assumes we return the mangled name.
10990              This just undoes that lie until things are cleaned up.  */
10991         }
10992       else
10993         {
10994           /* Use DMGL_RET_DROP for C++ template functions to suppress
10995              their return type.  It is easier for GDB users to search
10996              for such functions as `name(params)' than `long name(params)'.
10997              In such case the minimal symbol names do not match the full
10998              symbol names but for template functions there is never a need
10999              to look up their definition from their declaration so
11000              the only disadvantage remains the minimal symbol variant
11001              `long name(params)' does not have the proper inferior type.  */
11002           demangled.reset (gdb_demangle (mangled,
11003                                          (DMGL_PARAMS | DMGL_ANSI
11004                                           | DMGL_RET_DROP)));
11005         }
11006       if (demangled)
11007         canon = demangled.get ();
11008       else
11009         {
11010           canon = mangled;
11011           need_copy = 0;
11012         }
11013     }
11014
11015   if (canon == NULL || check_physname)
11016     {
11017       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11018
11019       if (canon != NULL && strcmp (physname, canon) != 0)
11020         {
11021           /* It may not mean a bug in GDB.  The compiler could also
11022              compute DW_AT_linkage_name incorrectly.  But in such case
11023              GDB would need to be bug-to-bug compatible.  */
11024
11025           complaint (_("Computed physname <%s> does not match demangled <%s> "
11026                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11027                      physname, canon, mangled, sect_offset_str (die->sect_off),
11028                      objfile_name (objfile));
11029
11030           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11031              is available here - over computed PHYSNAME.  It is safer
11032              against both buggy GDB and buggy compilers.  */
11033
11034           retval = canon;
11035         }
11036       else
11037         {
11038           retval = physname;
11039           need_copy = 0;
11040         }
11041     }
11042   else
11043     retval = canon;
11044
11045   if (need_copy)
11046     retval = ((const char *)
11047               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11048                              retval, strlen (retval)));
11049
11050   return retval;
11051 }
11052
11053 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11054    a new symbol for it.
11055
11056    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11057
11058 static int
11059 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11060 {
11061   struct attribute *attr;
11062
11063   /* If the die does not have a name, this is not a namespace
11064      alias.  */
11065   attr = dwarf2_attr (die, DW_AT_name, cu);
11066   if (attr != NULL)
11067     {
11068       int num;
11069       struct die_info *d = die;
11070       struct dwarf2_cu *imported_cu = cu;
11071
11072       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11073          keep inspecting DIEs until we hit the underlying import.  */
11074 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11075       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11076         {
11077           attr = dwarf2_attr (d, DW_AT_import, cu);
11078           if (attr == NULL)
11079             break;
11080
11081           d = follow_die_ref (d, attr, &imported_cu);
11082           if (d->tag != DW_TAG_imported_declaration)
11083             break;
11084         }
11085
11086       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11087         {
11088           complaint (_("DIE at %s has too many recursively imported "
11089                        "declarations"), sect_offset_str (d->sect_off));
11090           return 0;
11091         }
11092
11093       if (attr != NULL)
11094         {
11095           struct type *type;
11096           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11097
11098           type = get_die_type_at_offset (sect_off, cu->per_cu);
11099           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11100             {
11101               /* This declaration is a global namespace alias.  Add
11102                  a symbol for it whose type is the aliased namespace.  */
11103               new_symbol (die, type, cu);
11104               return 1;
11105             }
11106         }
11107     }
11108
11109   return 0;
11110 }
11111
11112 /* Return the using directives repository (global or local?) to use in the
11113    current context for CU.
11114
11115    For Ada, imported declarations can materialize renamings, which *may* be
11116    global.  However it is impossible (for now?) in DWARF to distinguish
11117    "external" imported declarations and "static" ones.  As all imported
11118    declarations seem to be static in all other languages, make them all CU-wide
11119    global only in Ada.  */
11120
11121 static struct using_direct **
11122 using_directives (struct dwarf2_cu *cu)
11123 {
11124   if (cu->language == language_ada && cu->builder->outermost_context_p ())
11125     return cu->builder->get_global_using_directives ();
11126   else
11127     return cu->builder->get_local_using_directives ();
11128 }
11129
11130 /* Read the import statement specified by the given die and record it.  */
11131
11132 static void
11133 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11134 {
11135   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11136   struct attribute *import_attr;
11137   struct die_info *imported_die, *child_die;
11138   struct dwarf2_cu *imported_cu;
11139   const char *imported_name;
11140   const char *imported_name_prefix;
11141   const char *canonical_name;
11142   const char *import_alias;
11143   const char *imported_declaration = NULL;
11144   const char *import_prefix;
11145   std::vector<const char *> excludes;
11146
11147   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11148   if (import_attr == NULL)
11149     {
11150       complaint (_("Tag '%s' has no DW_AT_import"),
11151                  dwarf_tag_name (die->tag));
11152       return;
11153     }
11154
11155   imported_cu = cu;
11156   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11157   imported_name = dwarf2_name (imported_die, imported_cu);
11158   if (imported_name == NULL)
11159     {
11160       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11161
11162         The import in the following code:
11163         namespace A
11164           {
11165             typedef int B;
11166           }
11167
11168         int main ()
11169           {
11170             using A::B;
11171             B b;
11172             return b;
11173           }
11174
11175         ...
11176          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11177             <52>   DW_AT_decl_file   : 1
11178             <53>   DW_AT_decl_line   : 6
11179             <54>   DW_AT_import      : <0x75>
11180          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11181             <59>   DW_AT_name        : B
11182             <5b>   DW_AT_decl_file   : 1
11183             <5c>   DW_AT_decl_line   : 2
11184             <5d>   DW_AT_type        : <0x6e>
11185         ...
11186          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11187             <76>   DW_AT_byte_size   : 4
11188             <77>   DW_AT_encoding    : 5        (signed)
11189
11190         imports the wrong die ( 0x75 instead of 0x58 ).
11191         This case will be ignored until the gcc bug is fixed.  */
11192       return;
11193     }
11194
11195   /* Figure out the local name after import.  */
11196   import_alias = dwarf2_name (die, cu);
11197
11198   /* Figure out where the statement is being imported to.  */
11199   import_prefix = determine_prefix (die, cu);
11200
11201   /* Figure out what the scope of the imported die is and prepend it
11202      to the name of the imported die.  */
11203   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11204
11205   if (imported_die->tag != DW_TAG_namespace
11206       && imported_die->tag != DW_TAG_module)
11207     {
11208       imported_declaration = imported_name;
11209       canonical_name = imported_name_prefix;
11210     }
11211   else if (strlen (imported_name_prefix) > 0)
11212     canonical_name = obconcat (&objfile->objfile_obstack,
11213                                imported_name_prefix,
11214                                (cu->language == language_d ? "." : "::"),
11215                                imported_name, (char *) NULL);
11216   else
11217     canonical_name = imported_name;
11218
11219   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11220     for (child_die = die->child; child_die && child_die->tag;
11221          child_die = sibling_die (child_die))
11222       {
11223         /* DWARF-4: A Fortran use statement with a “rename list” may be
11224            represented by an imported module entry with an import attribute
11225            referring to the module and owned entries corresponding to those
11226            entities that are renamed as part of being imported.  */
11227
11228         if (child_die->tag != DW_TAG_imported_declaration)
11229           {
11230             complaint (_("child DW_TAG_imported_declaration expected "
11231                          "- DIE at %s [in module %s]"),
11232                        sect_offset_str (child_die->sect_off),
11233                        objfile_name (objfile));
11234             continue;
11235           }
11236
11237         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11238         if (import_attr == NULL)
11239           {
11240             complaint (_("Tag '%s' has no DW_AT_import"),
11241                        dwarf_tag_name (child_die->tag));
11242             continue;
11243           }
11244
11245         imported_cu = cu;
11246         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11247                                               &imported_cu);
11248         imported_name = dwarf2_name (imported_die, imported_cu);
11249         if (imported_name == NULL)
11250           {
11251             complaint (_("child DW_TAG_imported_declaration has unknown "
11252                          "imported name - DIE at %s [in module %s]"),
11253                        sect_offset_str (child_die->sect_off),
11254                        objfile_name (objfile));
11255             continue;
11256           }
11257
11258         excludes.push_back (imported_name);
11259
11260         process_die (child_die, cu);
11261       }
11262
11263   add_using_directive (using_directives (cu),
11264                        import_prefix,
11265                        canonical_name,
11266                        import_alias,
11267                        imported_declaration,
11268                        excludes,
11269                        0,
11270                        &objfile->objfile_obstack);
11271 }
11272
11273 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11274    types, but gives them a size of zero.  Starting with version 14,
11275    ICC is compatible with GCC.  */
11276
11277 static int
11278 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11279 {
11280   if (!cu->checked_producer)
11281     check_producer (cu);
11282
11283   return cu->producer_is_icc_lt_14;
11284 }
11285
11286 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11287    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11288    this, it was first present in GCC release 4.3.0.  */
11289
11290 static int
11291 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11292 {
11293   if (!cu->checked_producer)
11294     check_producer (cu);
11295
11296   return cu->producer_is_gcc_lt_4_3;
11297 }
11298
11299 static file_and_directory
11300 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11301 {
11302   file_and_directory res;
11303
11304   /* Find the filename.  Do not use dwarf2_name here, since the filename
11305      is not a source language identifier.  */
11306   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11307   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11308
11309   if (res.comp_dir == NULL
11310       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11311       && IS_ABSOLUTE_PATH (res.name))
11312     {
11313       res.comp_dir_storage = ldirname (res.name);
11314       if (!res.comp_dir_storage.empty ())
11315         res.comp_dir = res.comp_dir_storage.c_str ();
11316     }
11317   if (res.comp_dir != NULL)
11318     {
11319       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11320          directory, get rid of it.  */
11321       const char *cp = strchr (res.comp_dir, ':');
11322
11323       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11324         res.comp_dir = cp + 1;
11325     }
11326
11327   if (res.name == NULL)
11328     res.name = "<unknown>";
11329
11330   return res;
11331 }
11332
11333 /* Handle DW_AT_stmt_list for a compilation unit.
11334    DIE is the DW_TAG_compile_unit die for CU.
11335    COMP_DIR is the compilation directory.  LOWPC is passed to
11336    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11337
11338 static void
11339 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11340                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11341 {
11342   struct dwarf2_per_objfile *dwarf2_per_objfile
11343     = cu->per_cu->dwarf2_per_objfile;
11344   struct objfile *objfile = dwarf2_per_objfile->objfile;
11345   struct attribute *attr;
11346   struct line_header line_header_local;
11347   hashval_t line_header_local_hash;
11348   void **slot;
11349   int decode_mapping;
11350
11351   gdb_assert (! cu->per_cu->is_debug_types);
11352
11353   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11354   if (attr == NULL)
11355     return;
11356
11357   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11358
11359   /* The line header hash table is only created if needed (it exists to
11360      prevent redundant reading of the line table for partial_units).
11361      If we're given a partial_unit, we'll need it.  If we're given a
11362      compile_unit, then use the line header hash table if it's already
11363      created, but don't create one just yet.  */
11364
11365   if (dwarf2_per_objfile->line_header_hash == NULL
11366       && die->tag == DW_TAG_partial_unit)
11367     {
11368       dwarf2_per_objfile->line_header_hash
11369         = htab_create_alloc_ex (127, line_header_hash_voidp,
11370                                 line_header_eq_voidp,
11371                                 free_line_header_voidp,
11372                                 &objfile->objfile_obstack,
11373                                 hashtab_obstack_allocate,
11374                                 dummy_obstack_deallocate);
11375     }
11376
11377   line_header_local.sect_off = line_offset;
11378   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11379   line_header_local_hash = line_header_hash (&line_header_local);
11380   if (dwarf2_per_objfile->line_header_hash != NULL)
11381     {
11382       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11383                                        &line_header_local,
11384                                        line_header_local_hash, NO_INSERT);
11385
11386       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11387          is not present in *SLOT (since if there is something in *SLOT then
11388          it will be for a partial_unit).  */
11389       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11390         {
11391           gdb_assert (*slot != NULL);
11392           cu->line_header = (struct line_header *) *slot;
11393           return;
11394         }
11395     }
11396
11397   /* dwarf_decode_line_header does not yet provide sufficient information.
11398      We always have to call also dwarf_decode_lines for it.  */
11399   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11400   if (lh == NULL)
11401     return;
11402
11403   cu->line_header = lh.release ();
11404   cu->line_header_die_owner = die;
11405
11406   if (dwarf2_per_objfile->line_header_hash == NULL)
11407     slot = NULL;
11408   else
11409     {
11410       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11411                                        &line_header_local,
11412                                        line_header_local_hash, INSERT);
11413       gdb_assert (slot != NULL);
11414     }
11415   if (slot != NULL && *slot == NULL)
11416     {
11417       /* This newly decoded line number information unit will be owned
11418          by line_header_hash hash table.  */
11419       *slot = cu->line_header;
11420       cu->line_header_die_owner = NULL;
11421     }
11422   else
11423     {
11424       /* We cannot free any current entry in (*slot) as that struct line_header
11425          may be already used by multiple CUs.  Create only temporary decoded
11426          line_header for this CU - it may happen at most once for each line
11427          number information unit.  And if we're not using line_header_hash
11428          then this is what we want as well.  */
11429       gdb_assert (die->tag != DW_TAG_partial_unit);
11430     }
11431   decode_mapping = (die->tag != DW_TAG_partial_unit);
11432   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11433                       decode_mapping);
11434
11435 }
11436
11437 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11438
11439 static void
11440 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11441 {
11442   struct dwarf2_per_objfile *dwarf2_per_objfile
11443     = cu->per_cu->dwarf2_per_objfile;
11444   struct objfile *objfile = dwarf2_per_objfile->objfile;
11445   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11446   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11447   CORE_ADDR highpc = ((CORE_ADDR) 0);
11448   struct attribute *attr;
11449   struct die_info *child_die;
11450   CORE_ADDR baseaddr;
11451
11452   prepare_one_comp_unit (cu, die, cu->language);
11453   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11454
11455   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11456
11457   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11458      from finish_block.  */
11459   if (lowpc == ((CORE_ADDR) -1))
11460     lowpc = highpc;
11461   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11462
11463   file_and_directory fnd = find_file_and_directory (die, cu);
11464
11465   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11466      standardised yet.  As a workaround for the language detection we fall
11467      back to the DW_AT_producer string.  */
11468   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11469     cu->language = language_opencl;
11470
11471   /* Similar hack for Go.  */
11472   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11473     set_cu_language (DW_LANG_Go, cu);
11474
11475   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11476
11477   /* Decode line number information if present.  We do this before
11478      processing child DIEs, so that the line header table is available
11479      for DW_AT_decl_file.  */
11480   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11481
11482   /* Process all dies in compilation unit.  */
11483   if (die->child != NULL)
11484     {
11485       child_die = die->child;
11486       while (child_die && child_die->tag)
11487         {
11488           process_die (child_die, cu);
11489           child_die = sibling_die (child_die);
11490         }
11491     }
11492
11493   /* Decode macro information, if present.  Dwarf 2 macro information
11494      refers to information in the line number info statement program
11495      header, so we can only read it if we've read the header
11496      successfully.  */
11497   attr = dwarf2_attr (die, DW_AT_macros, cu);
11498   if (attr == NULL)
11499     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11500   if (attr && cu->line_header)
11501     {
11502       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11503         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11504
11505       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11506     }
11507   else
11508     {
11509       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11510       if (attr && cu->line_header)
11511         {
11512           unsigned int macro_offset = DW_UNSND (attr);
11513
11514           dwarf_decode_macros (cu, macro_offset, 0);
11515         }
11516     }
11517 }
11518
11519 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11520    Create the set of symtabs used by this TU, or if this TU is sharing
11521    symtabs with another TU and the symtabs have already been created
11522    then restore those symtabs in the line header.
11523    We don't need the pc/line-number mapping for type units.  */
11524
11525 static void
11526 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11527 {
11528   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11529   struct type_unit_group *tu_group;
11530   int first_time;
11531   struct attribute *attr;
11532   unsigned int i;
11533   struct signatured_type *sig_type;
11534
11535   gdb_assert (per_cu->is_debug_types);
11536   sig_type = (struct signatured_type *) per_cu;
11537
11538   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11539
11540   /* If we're using .gdb_index (includes -readnow) then
11541      per_cu->type_unit_group may not have been set up yet.  */
11542   if (sig_type->type_unit_group == NULL)
11543     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11544   tu_group = sig_type->type_unit_group;
11545
11546   /* If we've already processed this stmt_list there's no real need to
11547      do it again, we could fake it and just recreate the part we need
11548      (file name,index -> symtab mapping).  If data shows this optimization
11549      is useful we can do it then.  */
11550   first_time = tu_group->compunit_symtab == NULL;
11551
11552   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11553      debug info.  */
11554   line_header_up lh;
11555   if (attr != NULL)
11556     {
11557       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11558       lh = dwarf_decode_line_header (line_offset, cu);
11559     }
11560   if (lh == NULL)
11561     {
11562       if (first_time)
11563         dwarf2_start_symtab (cu, "", NULL, 0);
11564       else
11565         {
11566           gdb_assert (tu_group->symtabs == NULL);
11567           gdb_assert (cu->builder == nullptr);
11568           struct compunit_symtab *cust = tu_group->compunit_symtab;
11569           cu->builder.reset (new struct buildsym_compunit
11570                              (COMPUNIT_OBJFILE (cust), "",
11571                               COMPUNIT_DIRNAME (cust),
11572                               compunit_language (cust),
11573                               0, cust));
11574         }
11575       return;
11576     }
11577
11578   cu->line_header = lh.release ();
11579   cu->line_header_die_owner = die;
11580
11581   if (first_time)
11582     {
11583       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11584
11585       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11586          still initializing it, and our caller (a few levels up)
11587          process_full_type_unit still needs to know if this is the first
11588          time.  */
11589
11590       tu_group->num_symtabs = cu->line_header->file_names.size ();
11591       tu_group->symtabs = XNEWVEC (struct symtab *,
11592                                    cu->line_header->file_names.size ());
11593
11594       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11595         {
11596           file_entry &fe = cu->line_header->file_names[i];
11597
11598           dwarf2_start_subfile (cu, fe.name, fe.include_dir (cu->line_header));
11599
11600           if (cu->builder->get_current_subfile ()->symtab == NULL)
11601             {
11602               /* NOTE: start_subfile will recognize when it's been
11603                  passed a file it has already seen.  So we can't
11604                  assume there's a simple mapping from
11605                  cu->line_header->file_names to subfiles, plus
11606                  cu->line_header->file_names may contain dups.  */
11607               cu->builder->get_current_subfile ()->symtab
11608                 = allocate_symtab (cust,
11609                                    cu->builder->get_current_subfile ()->name);
11610             }
11611
11612           fe.symtab = cu->builder->get_current_subfile ()->symtab;
11613           tu_group->symtabs[i] = fe.symtab;
11614         }
11615     }
11616   else
11617     {
11618       gdb_assert (cu->builder == nullptr);
11619       struct compunit_symtab *cust = tu_group->compunit_symtab;
11620       cu->builder.reset (new struct buildsym_compunit
11621                          (COMPUNIT_OBJFILE (cust), "",
11622                           COMPUNIT_DIRNAME (cust),
11623                           compunit_language (cust),
11624                           0, cust));
11625
11626       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11627         {
11628           file_entry &fe = cu->line_header->file_names[i];
11629
11630           fe.symtab = tu_group->symtabs[i];
11631         }
11632     }
11633
11634   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11635      so they don't have a "real" (so to speak) symtab anyway.
11636      There is later code that will assign the main symtab to all symbols
11637      that don't have one.  We need to handle the case of a symbol with a
11638      missing symtab (DW_AT_decl_file) anyway.  */
11639 }
11640
11641 /* Process DW_TAG_type_unit.
11642    For TUs we want to skip the first top level sibling if it's not the
11643    actual type being defined by this TU.  In this case the first top
11644    level sibling is there to provide context only.  */
11645
11646 static void
11647 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11648 {
11649   struct die_info *child_die;
11650
11651   prepare_one_comp_unit (cu, die, language_minimal);
11652
11653   /* Initialize (or reinitialize) the machinery for building symtabs.
11654      We do this before processing child DIEs, so that the line header table
11655      is available for DW_AT_decl_file.  */
11656   setup_type_unit_groups (die, cu);
11657
11658   if (die->child != NULL)
11659     {
11660       child_die = die->child;
11661       while (child_die && child_die->tag)
11662         {
11663           process_die (child_die, cu);
11664           child_die = sibling_die (child_die);
11665         }
11666     }
11667 }
11668 \f
11669 /* DWO/DWP files.
11670
11671    http://gcc.gnu.org/wiki/DebugFission
11672    http://gcc.gnu.org/wiki/DebugFissionDWP
11673
11674    To simplify handling of both DWO files ("object" files with the DWARF info)
11675    and DWP files (a file with the DWOs packaged up into one file), we treat
11676    DWP files as having a collection of virtual DWO files.  */
11677
11678 static hashval_t
11679 hash_dwo_file (const void *item)
11680 {
11681   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11682   hashval_t hash;
11683
11684   hash = htab_hash_string (dwo_file->dwo_name);
11685   if (dwo_file->comp_dir != NULL)
11686     hash += htab_hash_string (dwo_file->comp_dir);
11687   return hash;
11688 }
11689
11690 static int
11691 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11692 {
11693   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11694   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11695
11696   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11697     return 0;
11698   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11699     return lhs->comp_dir == rhs->comp_dir;
11700   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11701 }
11702
11703 /* Allocate a hash table for DWO files.  */
11704
11705 static htab_t
11706 allocate_dwo_file_hash_table (struct objfile *objfile)
11707 {
11708   return htab_create_alloc_ex (41,
11709                                hash_dwo_file,
11710                                eq_dwo_file,
11711                                NULL,
11712                                &objfile->objfile_obstack,
11713                                hashtab_obstack_allocate,
11714                                dummy_obstack_deallocate);
11715 }
11716
11717 /* Lookup DWO file DWO_NAME.  */
11718
11719 static void **
11720 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11721                       const char *dwo_name,
11722                       const char *comp_dir)
11723 {
11724   struct dwo_file find_entry;
11725   void **slot;
11726
11727   if (dwarf2_per_objfile->dwo_files == NULL)
11728     dwarf2_per_objfile->dwo_files
11729       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11730
11731   memset (&find_entry, 0, sizeof (find_entry));
11732   find_entry.dwo_name = dwo_name;
11733   find_entry.comp_dir = comp_dir;
11734   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11735
11736   return slot;
11737 }
11738
11739 static hashval_t
11740 hash_dwo_unit (const void *item)
11741 {
11742   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11743
11744   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11745   return dwo_unit->signature;
11746 }
11747
11748 static int
11749 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11750 {
11751   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11752   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11753
11754   /* The signature is assumed to be unique within the DWO file.
11755      So while object file CU dwo_id's always have the value zero,
11756      that's OK, assuming each object file DWO file has only one CU,
11757      and that's the rule for now.  */
11758   return lhs->signature == rhs->signature;
11759 }
11760
11761 /* Allocate a hash table for DWO CUs,TUs.
11762    There is one of these tables for each of CUs,TUs for each DWO file.  */
11763
11764 static htab_t
11765 allocate_dwo_unit_table (struct objfile *objfile)
11766 {
11767   /* Start out with a pretty small number.
11768      Generally DWO files contain only one CU and maybe some TUs.  */
11769   return htab_create_alloc_ex (3,
11770                                hash_dwo_unit,
11771                                eq_dwo_unit,
11772                                NULL,
11773                                &objfile->objfile_obstack,
11774                                hashtab_obstack_allocate,
11775                                dummy_obstack_deallocate);
11776 }
11777
11778 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11779
11780 struct create_dwo_cu_data
11781 {
11782   struct dwo_file *dwo_file;
11783   struct dwo_unit dwo_unit;
11784 };
11785
11786 /* die_reader_func for create_dwo_cu.  */
11787
11788 static void
11789 create_dwo_cu_reader (const struct die_reader_specs *reader,
11790                       const gdb_byte *info_ptr,
11791                       struct die_info *comp_unit_die,
11792                       int has_children,
11793                       void *datap)
11794 {
11795   struct dwarf2_cu *cu = reader->cu;
11796   sect_offset sect_off = cu->per_cu->sect_off;
11797   struct dwarf2_section_info *section = cu->per_cu->section;
11798   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11799   struct dwo_file *dwo_file = data->dwo_file;
11800   struct dwo_unit *dwo_unit = &data->dwo_unit;
11801   struct attribute *attr;
11802
11803   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11804   if (attr == NULL)
11805     {
11806       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11807                    " its dwo_id [in module %s]"),
11808                  sect_offset_str (sect_off), dwo_file->dwo_name);
11809       return;
11810     }
11811
11812   dwo_unit->dwo_file = dwo_file;
11813   dwo_unit->signature = DW_UNSND (attr);
11814   dwo_unit->section = section;
11815   dwo_unit->sect_off = sect_off;
11816   dwo_unit->length = cu->per_cu->length;
11817
11818   if (dwarf_read_debug)
11819     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11820                         sect_offset_str (sect_off),
11821                         hex_string (dwo_unit->signature));
11822 }
11823
11824 /* Create the dwo_units for the CUs in a DWO_FILE.
11825    Note: This function processes DWO files only, not DWP files.  */
11826
11827 static void
11828 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11829                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11830                        htab_t &cus_htab)
11831 {
11832   struct objfile *objfile = dwarf2_per_objfile->objfile;
11833   const gdb_byte *info_ptr, *end_ptr;
11834
11835   dwarf2_read_section (objfile, &section);
11836   info_ptr = section.buffer;
11837
11838   if (info_ptr == NULL)
11839     return;
11840
11841   if (dwarf_read_debug)
11842     {
11843       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11844                           get_section_name (&section),
11845                           get_section_file_name (&section));
11846     }
11847
11848   end_ptr = info_ptr + section.size;
11849   while (info_ptr < end_ptr)
11850     {
11851       struct dwarf2_per_cu_data per_cu;
11852       struct create_dwo_cu_data create_dwo_cu_data;
11853       struct dwo_unit *dwo_unit;
11854       void **slot;
11855       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11856
11857       memset (&create_dwo_cu_data.dwo_unit, 0,
11858               sizeof (create_dwo_cu_data.dwo_unit));
11859       memset (&per_cu, 0, sizeof (per_cu));
11860       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11861       per_cu.is_debug_types = 0;
11862       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11863       per_cu.section = &section;
11864       create_dwo_cu_data.dwo_file = &dwo_file;
11865
11866       init_cutu_and_read_dies_no_follow (
11867           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11868       info_ptr += per_cu.length;
11869
11870       // If the unit could not be parsed, skip it.
11871       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11872         continue;
11873
11874       if (cus_htab == NULL)
11875         cus_htab = allocate_dwo_unit_table (objfile);
11876
11877       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11878       *dwo_unit = create_dwo_cu_data.dwo_unit;
11879       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11880       gdb_assert (slot != NULL);
11881       if (*slot != NULL)
11882         {
11883           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11884           sect_offset dup_sect_off = dup_cu->sect_off;
11885
11886           complaint (_("debug cu entry at offset %s is duplicate to"
11887                        " the entry at offset %s, signature %s"),
11888                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11889                      hex_string (dwo_unit->signature));
11890         }
11891       *slot = (void *)dwo_unit;
11892     }
11893 }
11894
11895 /* DWP file .debug_{cu,tu}_index section format:
11896    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11897
11898    DWP Version 1:
11899
11900    Both index sections have the same format, and serve to map a 64-bit
11901    signature to a set of section numbers.  Each section begins with a header,
11902    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11903    indexes, and a pool of 32-bit section numbers.  The index sections will be
11904    aligned at 8-byte boundaries in the file.
11905
11906    The index section header consists of:
11907
11908     V, 32 bit version number
11909     -, 32 bits unused
11910     N, 32 bit number of compilation units or type units in the index
11911     M, 32 bit number of slots in the hash table
11912
11913    Numbers are recorded using the byte order of the application binary.
11914
11915    The hash table begins at offset 16 in the section, and consists of an array
11916    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11917    order of the application binary).  Unused slots in the hash table are 0.
11918    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11919
11920    The parallel table begins immediately after the hash table
11921    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11922    array of 32-bit indexes (using the byte order of the application binary),
11923    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11924    table contains a 32-bit index into the pool of section numbers.  For unused
11925    hash table slots, the corresponding entry in the parallel table will be 0.
11926
11927    The pool of section numbers begins immediately following the hash table
11928    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11929    section numbers consists of an array of 32-bit words (using the byte order
11930    of the application binary).  Each item in the array is indexed starting
11931    from 0.  The hash table entry provides the index of the first section
11932    number in the set.  Additional section numbers in the set follow, and the
11933    set is terminated by a 0 entry (section number 0 is not used in ELF).
11934
11935    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11936    section must be the first entry in the set, and the .debug_abbrev.dwo must
11937    be the second entry. Other members of the set may follow in any order.
11938
11939    ---
11940
11941    DWP Version 2:
11942
11943    DWP Version 2 combines all the .debug_info, etc. sections into one,
11944    and the entries in the index tables are now offsets into these sections.
11945    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11946    section.
11947
11948    Index Section Contents:
11949     Header
11950     Hash Table of Signatures   dwp_hash_table.hash_table
11951     Parallel Table of Indices  dwp_hash_table.unit_table
11952     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11953     Table of Section Sizes     dwp_hash_table.v2.sizes
11954
11955    The index section header consists of:
11956
11957     V, 32 bit version number
11958     L, 32 bit number of columns in the table of section offsets
11959     N, 32 bit number of compilation units or type units in the index
11960     M, 32 bit number of slots in the hash table
11961
11962    Numbers are recorded using the byte order of the application binary.
11963
11964    The hash table has the same format as version 1.
11965    The parallel table of indices has the same format as version 1,
11966    except that the entries are origin-1 indices into the table of sections
11967    offsets and the table of section sizes.
11968
11969    The table of offsets begins immediately following the parallel table
11970    (at offset 16 + 12 * M from the beginning of the section).  The table is
11971    a two-dimensional array of 32-bit words (using the byte order of the
11972    application binary), with L columns and N+1 rows, in row-major order.
11973    Each row in the array is indexed starting from 0.  The first row provides
11974    a key to the remaining rows: each column in this row provides an identifier
11975    for a debug section, and the offsets in the same column of subsequent rows
11976    refer to that section.  The section identifiers are:
11977
11978     DW_SECT_INFO         1  .debug_info.dwo
11979     DW_SECT_TYPES        2  .debug_types.dwo
11980     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11981     DW_SECT_LINE         4  .debug_line.dwo
11982     DW_SECT_LOC          5  .debug_loc.dwo
11983     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11984     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11985     DW_SECT_MACRO        8  .debug_macro.dwo
11986
11987    The offsets provided by the CU and TU index sections are the base offsets
11988    for the contributions made by each CU or TU to the corresponding section
11989    in the package file.  Each CU and TU header contains an abbrev_offset
11990    field, used to find the abbreviations table for that CU or TU within the
11991    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11992    be interpreted as relative to the base offset given in the index section.
11993    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11994    should be interpreted as relative to the base offset for .debug_line.dwo,
11995    and offsets into other debug sections obtained from DWARF attributes should
11996    also be interpreted as relative to the corresponding base offset.
11997
11998    The table of sizes begins immediately following the table of offsets.
11999    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12000    with L columns and N rows, in row-major order.  Each row in the array is
12001    indexed starting from 1 (row 0 is shared by the two tables).
12002
12003    ---
12004
12005    Hash table lookup is handled the same in version 1 and 2:
12006
12007    We assume that N and M will not exceed 2^32 - 1.
12008    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12009
12010    Given a 64-bit compilation unit signature or a type signature S, an entry
12011    in the hash table is located as follows:
12012
12013    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12014       the low-order k bits all set to 1.
12015
12016    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12017
12018    3) If the hash table entry at index H matches the signature, use that
12019       entry.  If the hash table entry at index H is unused (all zeroes),
12020       terminate the search: the signature is not present in the table.
12021
12022    4) Let H = (H + H') modulo M. Repeat at Step 3.
12023
12024    Because M > N and H' and M are relatively prime, the search is guaranteed
12025    to stop at an unused slot or find the match.  */
12026
12027 /* Create a hash table to map DWO IDs to their CU/TU entry in
12028    .debug_{info,types}.dwo in DWP_FILE.
12029    Returns NULL if there isn't one.
12030    Note: This function processes DWP files only, not DWO files.  */
12031
12032 static struct dwp_hash_table *
12033 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12034                        struct dwp_file *dwp_file, int is_debug_types)
12035 {
12036   struct objfile *objfile = dwarf2_per_objfile->objfile;
12037   bfd *dbfd = dwp_file->dbfd.get ();
12038   const gdb_byte *index_ptr, *index_end;
12039   struct dwarf2_section_info *index;
12040   uint32_t version, nr_columns, nr_units, nr_slots;
12041   struct dwp_hash_table *htab;
12042
12043   if (is_debug_types)
12044     index = &dwp_file->sections.tu_index;
12045   else
12046     index = &dwp_file->sections.cu_index;
12047
12048   if (dwarf2_section_empty_p (index))
12049     return NULL;
12050   dwarf2_read_section (objfile, index);
12051
12052   index_ptr = index->buffer;
12053   index_end = index_ptr + index->size;
12054
12055   version = read_4_bytes (dbfd, index_ptr);
12056   index_ptr += 4;
12057   if (version == 2)
12058     nr_columns = read_4_bytes (dbfd, index_ptr);
12059   else
12060     nr_columns = 0;
12061   index_ptr += 4;
12062   nr_units = read_4_bytes (dbfd, index_ptr);
12063   index_ptr += 4;
12064   nr_slots = read_4_bytes (dbfd, index_ptr);
12065   index_ptr += 4;
12066
12067   if (version != 1 && version != 2)
12068     {
12069       error (_("Dwarf Error: unsupported DWP file version (%s)"
12070                " [in module %s]"),
12071              pulongest (version), dwp_file->name);
12072     }
12073   if (nr_slots != (nr_slots & -nr_slots))
12074     {
12075       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12076                " is not power of 2 [in module %s]"),
12077              pulongest (nr_slots), dwp_file->name);
12078     }
12079
12080   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12081   htab->version = version;
12082   htab->nr_columns = nr_columns;
12083   htab->nr_units = nr_units;
12084   htab->nr_slots = nr_slots;
12085   htab->hash_table = index_ptr;
12086   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12087
12088   /* Exit early if the table is empty.  */
12089   if (nr_slots == 0 || nr_units == 0
12090       || (version == 2 && nr_columns == 0))
12091     {
12092       /* All must be zero.  */
12093       if (nr_slots != 0 || nr_units != 0
12094           || (version == 2 && nr_columns != 0))
12095         {
12096           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12097                        " all zero [in modules %s]"),
12098                      dwp_file->name);
12099         }
12100       return htab;
12101     }
12102
12103   if (version == 1)
12104     {
12105       htab->section_pool.v1.indices =
12106         htab->unit_table + sizeof (uint32_t) * nr_slots;
12107       /* It's harder to decide whether the section is too small in v1.
12108          V1 is deprecated anyway so we punt.  */
12109     }
12110   else
12111     {
12112       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12113       int *ids = htab->section_pool.v2.section_ids;
12114       /* Reverse map for error checking.  */
12115       int ids_seen[DW_SECT_MAX + 1];
12116       int i;
12117
12118       if (nr_columns < 2)
12119         {
12120           error (_("Dwarf Error: bad DWP hash table, too few columns"
12121                    " in section table [in module %s]"),
12122                  dwp_file->name);
12123         }
12124       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12125         {
12126           error (_("Dwarf Error: bad DWP hash table, too many columns"
12127                    " in section table [in module %s]"),
12128                  dwp_file->name);
12129         }
12130       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12131       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12132       for (i = 0; i < nr_columns; ++i)
12133         {
12134           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12135
12136           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12137             {
12138               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12139                        " in section table [in module %s]"),
12140                      id, dwp_file->name);
12141             }
12142           if (ids_seen[id] != -1)
12143             {
12144               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12145                        " id %d in section table [in module %s]"),
12146                      id, dwp_file->name);
12147             }
12148           ids_seen[id] = i;
12149           ids[i] = id;
12150         }
12151       /* Must have exactly one info or types section.  */
12152       if (((ids_seen[DW_SECT_INFO] != -1)
12153            + (ids_seen[DW_SECT_TYPES] != -1))
12154           != 1)
12155         {
12156           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12157                    " DWO info/types section [in module %s]"),
12158                  dwp_file->name);
12159         }
12160       /* Must have an abbrev section.  */
12161       if (ids_seen[DW_SECT_ABBREV] == -1)
12162         {
12163           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12164                    " section [in module %s]"),
12165                  dwp_file->name);
12166         }
12167       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12168       htab->section_pool.v2.sizes =
12169         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12170                                          * nr_units * nr_columns);
12171       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12172                                           * nr_units * nr_columns))
12173           > index_end)
12174         {
12175           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12176                    " [in module %s]"),
12177                  dwp_file->name);
12178         }
12179     }
12180
12181   return htab;
12182 }
12183
12184 /* Update SECTIONS with the data from SECTP.
12185
12186    This function is like the other "locate" section routines that are
12187    passed to bfd_map_over_sections, but in this context the sections to
12188    read comes from the DWP V1 hash table, not the full ELF section table.
12189
12190    The result is non-zero for success, or zero if an error was found.  */
12191
12192 static int
12193 locate_v1_virtual_dwo_sections (asection *sectp,
12194                                 struct virtual_v1_dwo_sections *sections)
12195 {
12196   const struct dwop_section_names *names = &dwop_section_names;
12197
12198   if (section_is_p (sectp->name, &names->abbrev_dwo))
12199     {
12200       /* There can be only one.  */
12201       if (sections->abbrev.s.section != NULL)
12202         return 0;
12203       sections->abbrev.s.section = sectp;
12204       sections->abbrev.size = bfd_get_section_size (sectp);
12205     }
12206   else if (section_is_p (sectp->name, &names->info_dwo)
12207            || section_is_p (sectp->name, &names->types_dwo))
12208     {
12209       /* There can be only one.  */
12210       if (sections->info_or_types.s.section != NULL)
12211         return 0;
12212       sections->info_or_types.s.section = sectp;
12213       sections->info_or_types.size = bfd_get_section_size (sectp);
12214     }
12215   else if (section_is_p (sectp->name, &names->line_dwo))
12216     {
12217       /* There can be only one.  */
12218       if (sections->line.s.section != NULL)
12219         return 0;
12220       sections->line.s.section = sectp;
12221       sections->line.size = bfd_get_section_size (sectp);
12222     }
12223   else if (section_is_p (sectp->name, &names->loc_dwo))
12224     {
12225       /* There can be only one.  */
12226       if (sections->loc.s.section != NULL)
12227         return 0;
12228       sections->loc.s.section = sectp;
12229       sections->loc.size = bfd_get_section_size (sectp);
12230     }
12231   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12232     {
12233       /* There can be only one.  */
12234       if (sections->macinfo.s.section != NULL)
12235         return 0;
12236       sections->macinfo.s.section = sectp;
12237       sections->macinfo.size = bfd_get_section_size (sectp);
12238     }
12239   else if (section_is_p (sectp->name, &names->macro_dwo))
12240     {
12241       /* There can be only one.  */
12242       if (sections->macro.s.section != NULL)
12243         return 0;
12244       sections->macro.s.section = sectp;
12245       sections->macro.size = bfd_get_section_size (sectp);
12246     }
12247   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12248     {
12249       /* There can be only one.  */
12250       if (sections->str_offsets.s.section != NULL)
12251         return 0;
12252       sections->str_offsets.s.section = sectp;
12253       sections->str_offsets.size = bfd_get_section_size (sectp);
12254     }
12255   else
12256     {
12257       /* No other kind of section is valid.  */
12258       return 0;
12259     }
12260
12261   return 1;
12262 }
12263
12264 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12265    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12266    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12267    This is for DWP version 1 files.  */
12268
12269 static struct dwo_unit *
12270 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12271                            struct dwp_file *dwp_file,
12272                            uint32_t unit_index,
12273                            const char *comp_dir,
12274                            ULONGEST signature, int is_debug_types)
12275 {
12276   struct objfile *objfile = dwarf2_per_objfile->objfile;
12277   const struct dwp_hash_table *dwp_htab =
12278     is_debug_types ? dwp_file->tus : dwp_file->cus;
12279   bfd *dbfd = dwp_file->dbfd.get ();
12280   const char *kind = is_debug_types ? "TU" : "CU";
12281   struct dwo_file *dwo_file;
12282   struct dwo_unit *dwo_unit;
12283   struct virtual_v1_dwo_sections sections;
12284   void **dwo_file_slot;
12285   int i;
12286
12287   gdb_assert (dwp_file->version == 1);
12288
12289   if (dwarf_read_debug)
12290     {
12291       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12292                           kind,
12293                           pulongest (unit_index), hex_string (signature),
12294                           dwp_file->name);
12295     }
12296
12297   /* Fetch the sections of this DWO unit.
12298      Put a limit on the number of sections we look for so that bad data
12299      doesn't cause us to loop forever.  */
12300
12301 #define MAX_NR_V1_DWO_SECTIONS \
12302   (1 /* .debug_info or .debug_types */ \
12303    + 1 /* .debug_abbrev */ \
12304    + 1 /* .debug_line */ \
12305    + 1 /* .debug_loc */ \
12306    + 1 /* .debug_str_offsets */ \
12307    + 1 /* .debug_macro or .debug_macinfo */ \
12308    + 1 /* trailing zero */)
12309
12310   memset (&sections, 0, sizeof (sections));
12311
12312   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12313     {
12314       asection *sectp;
12315       uint32_t section_nr =
12316         read_4_bytes (dbfd,
12317                       dwp_htab->section_pool.v1.indices
12318                       + (unit_index + i) * sizeof (uint32_t));
12319
12320       if (section_nr == 0)
12321         break;
12322       if (section_nr >= dwp_file->num_sections)
12323         {
12324           error (_("Dwarf Error: bad DWP hash table, section number too large"
12325                    " [in module %s]"),
12326                  dwp_file->name);
12327         }
12328
12329       sectp = dwp_file->elf_sections[section_nr];
12330       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12331         {
12332           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12333                    " [in module %s]"),
12334                  dwp_file->name);
12335         }
12336     }
12337
12338   if (i < 2
12339       || dwarf2_section_empty_p (&sections.info_or_types)
12340       || dwarf2_section_empty_p (&sections.abbrev))
12341     {
12342       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12343                " [in module %s]"),
12344              dwp_file->name);
12345     }
12346   if (i == MAX_NR_V1_DWO_SECTIONS)
12347     {
12348       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12349                " [in module %s]"),
12350              dwp_file->name);
12351     }
12352
12353   /* It's easier for the rest of the code if we fake a struct dwo_file and
12354      have dwo_unit "live" in that.  At least for now.
12355
12356      The DWP file can be made up of a random collection of CUs and TUs.
12357      However, for each CU + set of TUs that came from the same original DWO
12358      file, we can combine them back into a virtual DWO file to save space
12359      (fewer struct dwo_file objects to allocate).  Remember that for really
12360      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12361
12362   std::string virtual_dwo_name =
12363     string_printf ("virtual-dwo/%d-%d-%d-%d",
12364                    get_section_id (&sections.abbrev),
12365                    get_section_id (&sections.line),
12366                    get_section_id (&sections.loc),
12367                    get_section_id (&sections.str_offsets));
12368   /* Can we use an existing virtual DWO file?  */
12369   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12370                                         virtual_dwo_name.c_str (),
12371                                         comp_dir);
12372   /* Create one if necessary.  */
12373   if (*dwo_file_slot == NULL)
12374     {
12375       if (dwarf_read_debug)
12376         {
12377           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12378                               virtual_dwo_name.c_str ());
12379         }
12380       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12381       dwo_file->dwo_name
12382         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12383                                         virtual_dwo_name.c_str (),
12384                                         virtual_dwo_name.size ());
12385       dwo_file->comp_dir = comp_dir;
12386       dwo_file->sections.abbrev = sections.abbrev;
12387       dwo_file->sections.line = sections.line;
12388       dwo_file->sections.loc = sections.loc;
12389       dwo_file->sections.macinfo = sections.macinfo;
12390       dwo_file->sections.macro = sections.macro;
12391       dwo_file->sections.str_offsets = sections.str_offsets;
12392       /* The "str" section is global to the entire DWP file.  */
12393       dwo_file->sections.str = dwp_file->sections.str;
12394       /* The info or types section is assigned below to dwo_unit,
12395          there's no need to record it in dwo_file.
12396          Also, we can't simply record type sections in dwo_file because
12397          we record a pointer into the vector in dwo_unit.  As we collect more
12398          types we'll grow the vector and eventually have to reallocate space
12399          for it, invalidating all copies of pointers into the previous
12400          contents.  */
12401       *dwo_file_slot = dwo_file;
12402     }
12403   else
12404     {
12405       if (dwarf_read_debug)
12406         {
12407           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12408                               virtual_dwo_name.c_str ());
12409         }
12410       dwo_file = (struct dwo_file *) *dwo_file_slot;
12411     }
12412
12413   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12414   dwo_unit->dwo_file = dwo_file;
12415   dwo_unit->signature = signature;
12416   dwo_unit->section =
12417     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12418   *dwo_unit->section = sections.info_or_types;
12419   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12420
12421   return dwo_unit;
12422 }
12423
12424 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12425    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12426    piece within that section used by a TU/CU, return a virtual section
12427    of just that piece.  */
12428
12429 static struct dwarf2_section_info
12430 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12431                        struct dwarf2_section_info *section,
12432                        bfd_size_type offset, bfd_size_type size)
12433 {
12434   struct dwarf2_section_info result;
12435   asection *sectp;
12436
12437   gdb_assert (section != NULL);
12438   gdb_assert (!section->is_virtual);
12439
12440   memset (&result, 0, sizeof (result));
12441   result.s.containing_section = section;
12442   result.is_virtual = 1;
12443
12444   if (size == 0)
12445     return result;
12446
12447   sectp = get_section_bfd_section (section);
12448
12449   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12450      bounds of the real section.  This is a pretty-rare event, so just
12451      flag an error (easier) instead of a warning and trying to cope.  */
12452   if (sectp == NULL
12453       || offset + size > bfd_get_section_size (sectp))
12454     {
12455       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12456                " in section %s [in module %s]"),
12457              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12458              objfile_name (dwarf2_per_objfile->objfile));
12459     }
12460
12461   result.virtual_offset = offset;
12462   result.size = size;
12463   return result;
12464 }
12465
12466 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12467    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12468    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12469    This is for DWP version 2 files.  */
12470
12471 static struct dwo_unit *
12472 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12473                            struct dwp_file *dwp_file,
12474                            uint32_t unit_index,
12475                            const char *comp_dir,
12476                            ULONGEST signature, int is_debug_types)
12477 {
12478   struct objfile *objfile = dwarf2_per_objfile->objfile;
12479   const struct dwp_hash_table *dwp_htab =
12480     is_debug_types ? dwp_file->tus : dwp_file->cus;
12481   bfd *dbfd = dwp_file->dbfd.get ();
12482   const char *kind = is_debug_types ? "TU" : "CU";
12483   struct dwo_file *dwo_file;
12484   struct dwo_unit *dwo_unit;
12485   struct virtual_v2_dwo_sections sections;
12486   void **dwo_file_slot;
12487   int i;
12488
12489   gdb_assert (dwp_file->version == 2);
12490
12491   if (dwarf_read_debug)
12492     {
12493       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12494                           kind,
12495                           pulongest (unit_index), hex_string (signature),
12496                           dwp_file->name);
12497     }
12498
12499   /* Fetch the section offsets of this DWO unit.  */
12500
12501   memset (&sections, 0, sizeof (sections));
12502
12503   for (i = 0; i < dwp_htab->nr_columns; ++i)
12504     {
12505       uint32_t offset = read_4_bytes (dbfd,
12506                                       dwp_htab->section_pool.v2.offsets
12507                                       + (((unit_index - 1) * dwp_htab->nr_columns
12508                                           + i)
12509                                          * sizeof (uint32_t)));
12510       uint32_t size = read_4_bytes (dbfd,
12511                                     dwp_htab->section_pool.v2.sizes
12512                                     + (((unit_index - 1) * dwp_htab->nr_columns
12513                                         + i)
12514                                        * sizeof (uint32_t)));
12515
12516       switch (dwp_htab->section_pool.v2.section_ids[i])
12517         {
12518         case DW_SECT_INFO:
12519         case DW_SECT_TYPES:
12520           sections.info_or_types_offset = offset;
12521           sections.info_or_types_size = size;
12522           break;
12523         case DW_SECT_ABBREV:
12524           sections.abbrev_offset = offset;
12525           sections.abbrev_size = size;
12526           break;
12527         case DW_SECT_LINE:
12528           sections.line_offset = offset;
12529           sections.line_size = size;
12530           break;
12531         case DW_SECT_LOC:
12532           sections.loc_offset = offset;
12533           sections.loc_size = size;
12534           break;
12535         case DW_SECT_STR_OFFSETS:
12536           sections.str_offsets_offset = offset;
12537           sections.str_offsets_size = size;
12538           break;
12539         case DW_SECT_MACINFO:
12540           sections.macinfo_offset = offset;
12541           sections.macinfo_size = size;
12542           break;
12543         case DW_SECT_MACRO:
12544           sections.macro_offset = offset;
12545           sections.macro_size = size;
12546           break;
12547         }
12548     }
12549
12550   /* It's easier for the rest of the code if we fake a struct dwo_file and
12551      have dwo_unit "live" in that.  At least for now.
12552
12553      The DWP file can be made up of a random collection of CUs and TUs.
12554      However, for each CU + set of TUs that came from the same original DWO
12555      file, we can combine them back into a virtual DWO file to save space
12556      (fewer struct dwo_file objects to allocate).  Remember that for really
12557      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12558
12559   std::string virtual_dwo_name =
12560     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12561                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12562                    (long) (sections.line_size ? sections.line_offset : 0),
12563                    (long) (sections.loc_size ? sections.loc_offset : 0),
12564                    (long) (sections.str_offsets_size
12565                            ? sections.str_offsets_offset : 0));
12566   /* Can we use an existing virtual DWO file?  */
12567   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12568                                         virtual_dwo_name.c_str (),
12569                                         comp_dir);
12570   /* Create one if necessary.  */
12571   if (*dwo_file_slot == NULL)
12572     {
12573       if (dwarf_read_debug)
12574         {
12575           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12576                               virtual_dwo_name.c_str ());
12577         }
12578       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12579       dwo_file->dwo_name
12580         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12581                                         virtual_dwo_name.c_str (),
12582                                         virtual_dwo_name.size ());
12583       dwo_file->comp_dir = comp_dir;
12584       dwo_file->sections.abbrev =
12585         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12586                                sections.abbrev_offset, sections.abbrev_size);
12587       dwo_file->sections.line =
12588         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12589                                sections.line_offset, sections.line_size);
12590       dwo_file->sections.loc =
12591         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12592                                sections.loc_offset, sections.loc_size);
12593       dwo_file->sections.macinfo =
12594         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12595                                sections.macinfo_offset, sections.macinfo_size);
12596       dwo_file->sections.macro =
12597         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12598                                sections.macro_offset, sections.macro_size);
12599       dwo_file->sections.str_offsets =
12600         create_dwp_v2_section (dwarf2_per_objfile,
12601                                &dwp_file->sections.str_offsets,
12602                                sections.str_offsets_offset,
12603                                sections.str_offsets_size);
12604       /* The "str" section is global to the entire DWP file.  */
12605       dwo_file->sections.str = dwp_file->sections.str;
12606       /* The info or types section is assigned below to dwo_unit,
12607          there's no need to record it in dwo_file.
12608          Also, we can't simply record type sections in dwo_file because
12609          we record a pointer into the vector in dwo_unit.  As we collect more
12610          types we'll grow the vector and eventually have to reallocate space
12611          for it, invalidating all copies of pointers into the previous
12612          contents.  */
12613       *dwo_file_slot = dwo_file;
12614     }
12615   else
12616     {
12617       if (dwarf_read_debug)
12618         {
12619           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12620                               virtual_dwo_name.c_str ());
12621         }
12622       dwo_file = (struct dwo_file *) *dwo_file_slot;
12623     }
12624
12625   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12626   dwo_unit->dwo_file = dwo_file;
12627   dwo_unit->signature = signature;
12628   dwo_unit->section =
12629     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12630   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12631                                               is_debug_types
12632                                               ? &dwp_file->sections.types
12633                                               : &dwp_file->sections.info,
12634                                               sections.info_or_types_offset,
12635                                               sections.info_or_types_size);
12636   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12637
12638   return dwo_unit;
12639 }
12640
12641 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12642    Returns NULL if the signature isn't found.  */
12643
12644 static struct dwo_unit *
12645 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12646                         struct dwp_file *dwp_file, const char *comp_dir,
12647                         ULONGEST signature, int is_debug_types)
12648 {
12649   const struct dwp_hash_table *dwp_htab =
12650     is_debug_types ? dwp_file->tus : dwp_file->cus;
12651   bfd *dbfd = dwp_file->dbfd.get ();
12652   uint32_t mask = dwp_htab->nr_slots - 1;
12653   uint32_t hash = signature & mask;
12654   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12655   unsigned int i;
12656   void **slot;
12657   struct dwo_unit find_dwo_cu;
12658
12659   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12660   find_dwo_cu.signature = signature;
12661   slot = htab_find_slot (is_debug_types
12662                          ? dwp_file->loaded_tus
12663                          : dwp_file->loaded_cus,
12664                          &find_dwo_cu, INSERT);
12665
12666   if (*slot != NULL)
12667     return (struct dwo_unit *) *slot;
12668
12669   /* Use a for loop so that we don't loop forever on bad debug info.  */
12670   for (i = 0; i < dwp_htab->nr_slots; ++i)
12671     {
12672       ULONGEST signature_in_table;
12673
12674       signature_in_table =
12675         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12676       if (signature_in_table == signature)
12677         {
12678           uint32_t unit_index =
12679             read_4_bytes (dbfd,
12680                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12681
12682           if (dwp_file->version == 1)
12683             {
12684               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12685                                                  dwp_file, unit_index,
12686                                                  comp_dir, signature,
12687                                                  is_debug_types);
12688             }
12689           else
12690             {
12691               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12692                                                  dwp_file, unit_index,
12693                                                  comp_dir, signature,
12694                                                  is_debug_types);
12695             }
12696           return (struct dwo_unit *) *slot;
12697         }
12698       if (signature_in_table == 0)
12699         return NULL;
12700       hash = (hash + hash2) & mask;
12701     }
12702
12703   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12704            " [in module %s]"),
12705          dwp_file->name);
12706 }
12707
12708 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12709    Open the file specified by FILE_NAME and hand it off to BFD for
12710    preliminary analysis.  Return a newly initialized bfd *, which
12711    includes a canonicalized copy of FILE_NAME.
12712    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12713    SEARCH_CWD is true if the current directory is to be searched.
12714    It will be searched before debug-file-directory.
12715    If successful, the file is added to the bfd include table of the
12716    objfile's bfd (see gdb_bfd_record_inclusion).
12717    If unable to find/open the file, return NULL.
12718    NOTE: This function is derived from symfile_bfd_open.  */
12719
12720 static gdb_bfd_ref_ptr
12721 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12722                     const char *file_name, int is_dwp, int search_cwd)
12723 {
12724   int desc;
12725   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12726      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12727      to debug_file_directory.  */
12728   const char *search_path;
12729   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12730
12731   gdb::unique_xmalloc_ptr<char> search_path_holder;
12732   if (search_cwd)
12733     {
12734       if (*debug_file_directory != '\0')
12735         {
12736           search_path_holder.reset (concat (".", dirname_separator_string,
12737                                             debug_file_directory,
12738                                             (char *) NULL));
12739           search_path = search_path_holder.get ();
12740         }
12741       else
12742         search_path = ".";
12743     }
12744   else
12745     search_path = debug_file_directory;
12746
12747   openp_flags flags = OPF_RETURN_REALPATH;
12748   if (is_dwp)
12749     flags |= OPF_SEARCH_IN_PATH;
12750
12751   gdb::unique_xmalloc_ptr<char> absolute_name;
12752   desc = openp (search_path, flags, file_name,
12753                 O_RDONLY | O_BINARY, &absolute_name);
12754   if (desc < 0)
12755     return NULL;
12756
12757   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12758                                          gnutarget, desc));
12759   if (sym_bfd == NULL)
12760     return NULL;
12761   bfd_set_cacheable (sym_bfd.get (), 1);
12762
12763   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12764     return NULL;
12765
12766   /* Success.  Record the bfd as having been included by the objfile's bfd.
12767      This is important because things like demangled_names_hash lives in the
12768      objfile's per_bfd space and may have references to things like symbol
12769      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12770   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12771
12772   return sym_bfd;
12773 }
12774
12775 /* Try to open DWO file FILE_NAME.
12776    COMP_DIR is the DW_AT_comp_dir attribute.
12777    The result is the bfd handle of the file.
12778    If there is a problem finding or opening the file, return NULL.
12779    Upon success, the canonicalized path of the file is stored in the bfd,
12780    same as symfile_bfd_open.  */
12781
12782 static gdb_bfd_ref_ptr
12783 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12784                const char *file_name, const char *comp_dir)
12785 {
12786   if (IS_ABSOLUTE_PATH (file_name))
12787     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12788                                0 /*is_dwp*/, 0 /*search_cwd*/);
12789
12790   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12791
12792   if (comp_dir != NULL)
12793     {
12794       char *path_to_try = concat (comp_dir, SLASH_STRING,
12795                                   file_name, (char *) NULL);
12796
12797       /* NOTE: If comp_dir is a relative path, this will also try the
12798          search path, which seems useful.  */
12799       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12800                                                 path_to_try,
12801                                                 0 /*is_dwp*/,
12802                                                 1 /*search_cwd*/));
12803       xfree (path_to_try);
12804       if (abfd != NULL)
12805         return abfd;
12806     }
12807
12808   /* That didn't work, try debug-file-directory, which, despite its name,
12809      is a list of paths.  */
12810
12811   if (*debug_file_directory == '\0')
12812     return NULL;
12813
12814   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12815                              0 /*is_dwp*/, 1 /*search_cwd*/);
12816 }
12817
12818 /* This function is mapped across the sections and remembers the offset and
12819    size of each of the DWO debugging sections we are interested in.  */
12820
12821 static void
12822 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12823 {
12824   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12825   const struct dwop_section_names *names = &dwop_section_names;
12826
12827   if (section_is_p (sectp->name, &names->abbrev_dwo))
12828     {
12829       dwo_sections->abbrev.s.section = sectp;
12830       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12831     }
12832   else if (section_is_p (sectp->name, &names->info_dwo))
12833     {
12834       dwo_sections->info.s.section = sectp;
12835       dwo_sections->info.size = bfd_get_section_size (sectp);
12836     }
12837   else if (section_is_p (sectp->name, &names->line_dwo))
12838     {
12839       dwo_sections->line.s.section = sectp;
12840       dwo_sections->line.size = bfd_get_section_size (sectp);
12841     }
12842   else if (section_is_p (sectp->name, &names->loc_dwo))
12843     {
12844       dwo_sections->loc.s.section = sectp;
12845       dwo_sections->loc.size = bfd_get_section_size (sectp);
12846     }
12847   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12848     {
12849       dwo_sections->macinfo.s.section = sectp;
12850       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12851     }
12852   else if (section_is_p (sectp->name, &names->macro_dwo))
12853     {
12854       dwo_sections->macro.s.section = sectp;
12855       dwo_sections->macro.size = bfd_get_section_size (sectp);
12856     }
12857   else if (section_is_p (sectp->name, &names->str_dwo))
12858     {
12859       dwo_sections->str.s.section = sectp;
12860       dwo_sections->str.size = bfd_get_section_size (sectp);
12861     }
12862   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12863     {
12864       dwo_sections->str_offsets.s.section = sectp;
12865       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12866     }
12867   else if (section_is_p (sectp->name, &names->types_dwo))
12868     {
12869       struct dwarf2_section_info type_section;
12870
12871       memset (&type_section, 0, sizeof (type_section));
12872       type_section.s.section = sectp;
12873       type_section.size = bfd_get_section_size (sectp);
12874       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12875                      &type_section);
12876     }
12877 }
12878
12879 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12880    by PER_CU.  This is for the non-DWP case.
12881    The result is NULL if DWO_NAME can't be found.  */
12882
12883 static struct dwo_file *
12884 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12885                         const char *dwo_name, const char *comp_dir)
12886 {
12887   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12888   struct objfile *objfile = dwarf2_per_objfile->objfile;
12889
12890   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12891   if (dbfd == NULL)
12892     {
12893       if (dwarf_read_debug)
12894         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12895       return NULL;
12896     }
12897
12898   /* We use a unique pointer here, despite the obstack allocation,
12899      because a dwo_file needs some cleanup if it is abandoned.  */
12900   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12901                                         struct dwo_file));
12902   dwo_file->dwo_name = dwo_name;
12903   dwo_file->comp_dir = comp_dir;
12904   dwo_file->dbfd = dbfd.release ();
12905
12906   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12907                          &dwo_file->sections);
12908
12909   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12910                          dwo_file->cus);
12911
12912   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12913                                  dwo_file->sections.types, dwo_file->tus);
12914
12915   if (dwarf_read_debug)
12916     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12917
12918   return dwo_file.release ();
12919 }
12920
12921 /* This function is mapped across the sections and remembers the offset and
12922    size of each of the DWP debugging sections common to version 1 and 2 that
12923    we are interested in.  */
12924
12925 static void
12926 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12927                                    void *dwp_file_ptr)
12928 {
12929   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12930   const struct dwop_section_names *names = &dwop_section_names;
12931   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12932
12933   /* Record the ELF section number for later lookup: this is what the
12934      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12935   gdb_assert (elf_section_nr < dwp_file->num_sections);
12936   dwp_file->elf_sections[elf_section_nr] = sectp;
12937
12938   /* Look for specific sections that we need.  */
12939   if (section_is_p (sectp->name, &names->str_dwo))
12940     {
12941       dwp_file->sections.str.s.section = sectp;
12942       dwp_file->sections.str.size = bfd_get_section_size (sectp);
12943     }
12944   else if (section_is_p (sectp->name, &names->cu_index))
12945     {
12946       dwp_file->sections.cu_index.s.section = sectp;
12947       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
12948     }
12949   else if (section_is_p (sectp->name, &names->tu_index))
12950     {
12951       dwp_file->sections.tu_index.s.section = sectp;
12952       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
12953     }
12954 }
12955
12956 /* This function is mapped across the sections and remembers the offset and
12957    size of each of the DWP version 2 debugging sections that we are interested
12958    in.  This is split into a separate function because we don't know if we
12959    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12960
12961 static void
12962 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12963 {
12964   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12965   const struct dwop_section_names *names = &dwop_section_names;
12966   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12967
12968   /* Record the ELF section number for later lookup: this is what the
12969      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12970   gdb_assert (elf_section_nr < dwp_file->num_sections);
12971   dwp_file->elf_sections[elf_section_nr] = sectp;
12972
12973   /* Look for specific sections that we need.  */
12974   if (section_is_p (sectp->name, &names->abbrev_dwo))
12975     {
12976       dwp_file->sections.abbrev.s.section = sectp;
12977       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
12978     }
12979   else if (section_is_p (sectp->name, &names->info_dwo))
12980     {
12981       dwp_file->sections.info.s.section = sectp;
12982       dwp_file->sections.info.size = bfd_get_section_size (sectp);
12983     }
12984   else if (section_is_p (sectp->name, &names->line_dwo))
12985     {
12986       dwp_file->sections.line.s.section = sectp;
12987       dwp_file->sections.line.size = bfd_get_section_size (sectp);
12988     }
12989   else if (section_is_p (sectp->name, &names->loc_dwo))
12990     {
12991       dwp_file->sections.loc.s.section = sectp;
12992       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
12993     }
12994   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12995     {
12996       dwp_file->sections.macinfo.s.section = sectp;
12997       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
12998     }
12999   else if (section_is_p (sectp->name, &names->macro_dwo))
13000     {
13001       dwp_file->sections.macro.s.section = sectp;
13002       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13003     }
13004   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13005     {
13006       dwp_file->sections.str_offsets.s.section = sectp;
13007       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13008     }
13009   else if (section_is_p (sectp->name, &names->types_dwo))
13010     {
13011       dwp_file->sections.types.s.section = sectp;
13012       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13013     }
13014 }
13015
13016 /* Hash function for dwp_file loaded CUs/TUs.  */
13017
13018 static hashval_t
13019 hash_dwp_loaded_cutus (const void *item)
13020 {
13021   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13022
13023   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13024   return dwo_unit->signature;
13025 }
13026
13027 /* Equality function for dwp_file loaded CUs/TUs.  */
13028
13029 static int
13030 eq_dwp_loaded_cutus (const void *a, const void *b)
13031 {
13032   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13033   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13034
13035   return dua->signature == dub->signature;
13036 }
13037
13038 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13039
13040 static htab_t
13041 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13042 {
13043   return htab_create_alloc_ex (3,
13044                                hash_dwp_loaded_cutus,
13045                                eq_dwp_loaded_cutus,
13046                                NULL,
13047                                &objfile->objfile_obstack,
13048                                hashtab_obstack_allocate,
13049                                dummy_obstack_deallocate);
13050 }
13051
13052 /* Try to open DWP file FILE_NAME.
13053    The result is the bfd handle of the file.
13054    If there is a problem finding or opening the file, return NULL.
13055    Upon success, the canonicalized path of the file is stored in the bfd,
13056    same as symfile_bfd_open.  */
13057
13058 static gdb_bfd_ref_ptr
13059 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13060                const char *file_name)
13061 {
13062   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13063                                             1 /*is_dwp*/,
13064                                             1 /*search_cwd*/));
13065   if (abfd != NULL)
13066     return abfd;
13067
13068   /* Work around upstream bug 15652.
13069      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13070      [Whether that's a "bug" is debatable, but it is getting in our way.]
13071      We have no real idea where the dwp file is, because gdb's realpath-ing
13072      of the executable's path may have discarded the needed info.
13073      [IWBN if the dwp file name was recorded in the executable, akin to
13074      .gnu_debuglink, but that doesn't exist yet.]
13075      Strip the directory from FILE_NAME and search again.  */
13076   if (*debug_file_directory != '\0')
13077     {
13078       /* Don't implicitly search the current directory here.
13079          If the user wants to search "." to handle this case,
13080          it must be added to debug-file-directory.  */
13081       return try_open_dwop_file (dwarf2_per_objfile,
13082                                  lbasename (file_name), 1 /*is_dwp*/,
13083                                  0 /*search_cwd*/);
13084     }
13085
13086   return NULL;
13087 }
13088
13089 /* Initialize the use of the DWP file for the current objfile.
13090    By convention the name of the DWP file is ${objfile}.dwp.
13091    The result is NULL if it can't be found.  */
13092
13093 static std::unique_ptr<struct dwp_file>
13094 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13095 {
13096   struct objfile *objfile = dwarf2_per_objfile->objfile;
13097
13098   /* Try to find first .dwp for the binary file before any symbolic links
13099      resolving.  */
13100
13101   /* If the objfile is a debug file, find the name of the real binary
13102      file and get the name of dwp file from there.  */
13103   std::string dwp_name;
13104   if (objfile->separate_debug_objfile_backlink != NULL)
13105     {
13106       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13107       const char *backlink_basename = lbasename (backlink->original_name);
13108
13109       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13110     }
13111   else
13112     dwp_name = objfile->original_name;
13113
13114   dwp_name += ".dwp";
13115
13116   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13117   if (dbfd == NULL
13118       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13119     {
13120       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13121       dwp_name = objfile_name (objfile);
13122       dwp_name += ".dwp";
13123       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13124     }
13125
13126   if (dbfd == NULL)
13127     {
13128       if (dwarf_read_debug)
13129         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13130       return std::unique_ptr<dwp_file> ();
13131     }
13132
13133   const char *name = bfd_get_filename (dbfd.get ());
13134   std::unique_ptr<struct dwp_file> dwp_file
13135     (new struct dwp_file (name, std::move (dbfd)));
13136
13137   /* +1: section 0 is unused */
13138   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13139   dwp_file->elf_sections =
13140     OBSTACK_CALLOC (&objfile->objfile_obstack,
13141                     dwp_file->num_sections, asection *);
13142
13143   bfd_map_over_sections (dwp_file->dbfd.get (),
13144                          dwarf2_locate_common_dwp_sections,
13145                          dwp_file.get ());
13146
13147   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13148                                          0);
13149
13150   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13151                                          1);
13152
13153   /* The DWP file version is stored in the hash table.  Oh well.  */
13154   if (dwp_file->cus && dwp_file->tus
13155       && dwp_file->cus->version != dwp_file->tus->version)
13156     {
13157       /* Technically speaking, we should try to limp along, but this is
13158          pretty bizarre.  We use pulongest here because that's the established
13159          portability solution (e.g, we cannot use %u for uint32_t).  */
13160       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13161                " TU version %s [in DWP file %s]"),
13162              pulongest (dwp_file->cus->version),
13163              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13164     }
13165
13166   if (dwp_file->cus)
13167     dwp_file->version = dwp_file->cus->version;
13168   else if (dwp_file->tus)
13169     dwp_file->version = dwp_file->tus->version;
13170   else
13171     dwp_file->version = 2;
13172
13173   if (dwp_file->version == 2)
13174     bfd_map_over_sections (dwp_file->dbfd.get (),
13175                            dwarf2_locate_v2_dwp_sections,
13176                            dwp_file.get ());
13177
13178   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13179   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13180
13181   if (dwarf_read_debug)
13182     {
13183       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13184       fprintf_unfiltered (gdb_stdlog,
13185                           "    %s CUs, %s TUs\n",
13186                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13187                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13188     }
13189
13190   return dwp_file;
13191 }
13192
13193 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13194
13195 static struct dwp_file *
13196 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13197 {
13198   if (! dwarf2_per_objfile->dwp_checked)
13199     {
13200       dwarf2_per_objfile->dwp_file
13201         = open_and_init_dwp_file (dwarf2_per_objfile);
13202       dwarf2_per_objfile->dwp_checked = 1;
13203     }
13204   return dwarf2_per_objfile->dwp_file.get ();
13205 }
13206
13207 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13208    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13209    or in the DWP file for the objfile, referenced by THIS_UNIT.
13210    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13211    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13212
13213    This is called, for example, when wanting to read a variable with a
13214    complex location.  Therefore we don't want to do file i/o for every call.
13215    Therefore we don't want to look for a DWO file on every call.
13216    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13217    then we check if we've already seen DWO_NAME, and only THEN do we check
13218    for a DWO file.
13219
13220    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13221    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13222
13223 static struct dwo_unit *
13224 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13225                  const char *dwo_name, const char *comp_dir,
13226                  ULONGEST signature, int is_debug_types)
13227 {
13228   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13229   struct objfile *objfile = dwarf2_per_objfile->objfile;
13230   const char *kind = is_debug_types ? "TU" : "CU";
13231   void **dwo_file_slot;
13232   struct dwo_file *dwo_file;
13233   struct dwp_file *dwp_file;
13234
13235   /* First see if there's a DWP file.
13236      If we have a DWP file but didn't find the DWO inside it, don't
13237      look for the original DWO file.  It makes gdb behave differently
13238      depending on whether one is debugging in the build tree.  */
13239
13240   dwp_file = get_dwp_file (dwarf2_per_objfile);
13241   if (dwp_file != NULL)
13242     {
13243       const struct dwp_hash_table *dwp_htab =
13244         is_debug_types ? dwp_file->tus : dwp_file->cus;
13245
13246       if (dwp_htab != NULL)
13247         {
13248           struct dwo_unit *dwo_cutu =
13249             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13250                                     signature, is_debug_types);
13251
13252           if (dwo_cutu != NULL)
13253             {
13254               if (dwarf_read_debug)
13255                 {
13256                   fprintf_unfiltered (gdb_stdlog,
13257                                       "Virtual DWO %s %s found: @%s\n",
13258                                       kind, hex_string (signature),
13259                                       host_address_to_string (dwo_cutu));
13260                 }
13261               return dwo_cutu;
13262             }
13263         }
13264     }
13265   else
13266     {
13267       /* No DWP file, look for the DWO file.  */
13268
13269       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13270                                             dwo_name, comp_dir);
13271       if (*dwo_file_slot == NULL)
13272         {
13273           /* Read in the file and build a table of the CUs/TUs it contains.  */
13274           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13275         }
13276       /* NOTE: This will be NULL if unable to open the file.  */
13277       dwo_file = (struct dwo_file *) *dwo_file_slot;
13278
13279       if (dwo_file != NULL)
13280         {
13281           struct dwo_unit *dwo_cutu = NULL;
13282
13283           if (is_debug_types && dwo_file->tus)
13284             {
13285               struct dwo_unit find_dwo_cutu;
13286
13287               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13288               find_dwo_cutu.signature = signature;
13289               dwo_cutu
13290                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13291             }
13292           else if (!is_debug_types && dwo_file->cus)
13293             {
13294               struct dwo_unit find_dwo_cutu;
13295
13296               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13297               find_dwo_cutu.signature = signature;
13298               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13299                                                        &find_dwo_cutu);
13300             }
13301
13302           if (dwo_cutu != NULL)
13303             {
13304               if (dwarf_read_debug)
13305                 {
13306                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13307                                       kind, dwo_name, hex_string (signature),
13308                                       host_address_to_string (dwo_cutu));
13309                 }
13310               return dwo_cutu;
13311             }
13312         }
13313     }
13314
13315   /* We didn't find it.  This could mean a dwo_id mismatch, or
13316      someone deleted the DWO/DWP file, or the search path isn't set up
13317      correctly to find the file.  */
13318
13319   if (dwarf_read_debug)
13320     {
13321       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13322                           kind, dwo_name, hex_string (signature));
13323     }
13324
13325   /* This is a warning and not a complaint because it can be caused by
13326      pilot error (e.g., user accidentally deleting the DWO).  */
13327   {
13328     /* Print the name of the DWP file if we looked there, helps the user
13329        better diagnose the problem.  */
13330     std::string dwp_text;
13331
13332     if (dwp_file != NULL)
13333       dwp_text = string_printf (" [in DWP file %s]",
13334                                 lbasename (dwp_file->name));
13335
13336     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13337                " [in module %s]"),
13338              kind, dwo_name, hex_string (signature),
13339              dwp_text.c_str (),
13340              this_unit->is_debug_types ? "TU" : "CU",
13341              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13342   }
13343   return NULL;
13344 }
13345
13346 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13347    See lookup_dwo_cutu_unit for details.  */
13348
13349 static struct dwo_unit *
13350 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13351                       const char *dwo_name, const char *comp_dir,
13352                       ULONGEST signature)
13353 {
13354   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13355 }
13356
13357 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13358    See lookup_dwo_cutu_unit for details.  */
13359
13360 static struct dwo_unit *
13361 lookup_dwo_type_unit (struct signatured_type *this_tu,
13362                       const char *dwo_name, const char *comp_dir)
13363 {
13364   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13365 }
13366
13367 /* Traversal function for queue_and_load_all_dwo_tus.  */
13368
13369 static int
13370 queue_and_load_dwo_tu (void **slot, void *info)
13371 {
13372   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13373   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13374   ULONGEST signature = dwo_unit->signature;
13375   struct signatured_type *sig_type =
13376     lookup_dwo_signatured_type (per_cu->cu, signature);
13377
13378   if (sig_type != NULL)
13379     {
13380       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13381
13382       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13383          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13384          while processing PER_CU.  */
13385       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13386         load_full_type_unit (sig_cu);
13387       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13388     }
13389
13390   return 1;
13391 }
13392
13393 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13394    The DWO may have the only definition of the type, though it may not be
13395    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13396    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13397
13398 static void
13399 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13400 {
13401   struct dwo_unit *dwo_unit;
13402   struct dwo_file *dwo_file;
13403
13404   gdb_assert (!per_cu->is_debug_types);
13405   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13406   gdb_assert (per_cu->cu != NULL);
13407
13408   dwo_unit = per_cu->cu->dwo_unit;
13409   gdb_assert (dwo_unit != NULL);
13410
13411   dwo_file = dwo_unit->dwo_file;
13412   if (dwo_file->tus != NULL)
13413     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13414 }
13415
13416 /* Free all resources associated with DWO_FILE.
13417    Close the DWO file and munmap the sections.  */
13418
13419 static void
13420 free_dwo_file (struct dwo_file *dwo_file)
13421 {
13422   /* Note: dbfd is NULL for virtual DWO files.  */
13423   gdb_bfd_unref (dwo_file->dbfd);
13424
13425   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13426 }
13427
13428 /* Traversal function for free_dwo_files.  */
13429
13430 static int
13431 free_dwo_file_from_slot (void **slot, void *info)
13432 {
13433   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13434
13435   free_dwo_file (dwo_file);
13436
13437   return 1;
13438 }
13439
13440 /* Free all resources associated with DWO_FILES.  */
13441
13442 static void
13443 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13444 {
13445   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13446 }
13447 \f
13448 /* Read in various DIEs.  */
13449
13450 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13451    Inherit only the children of the DW_AT_abstract_origin DIE not being
13452    already referenced by DW_AT_abstract_origin from the children of the
13453    current DIE.  */
13454
13455 static void
13456 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13457 {
13458   struct die_info *child_die;
13459   sect_offset *offsetp;
13460   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13461   struct die_info *origin_die;
13462   /* Iterator of the ORIGIN_DIE children.  */
13463   struct die_info *origin_child_die;
13464   struct attribute *attr;
13465   struct dwarf2_cu *origin_cu;
13466   struct pending **origin_previous_list_in_scope;
13467
13468   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13469   if (!attr)
13470     return;
13471
13472   /* Note that following die references may follow to a die in a
13473      different cu.  */
13474
13475   origin_cu = cu;
13476   origin_die = follow_die_ref (die, attr, &origin_cu);
13477
13478   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13479      symbols in.  */
13480   origin_previous_list_in_scope = origin_cu->list_in_scope;
13481   origin_cu->list_in_scope = cu->list_in_scope;
13482
13483   if (die->tag != origin_die->tag
13484       && !(die->tag == DW_TAG_inlined_subroutine
13485            && origin_die->tag == DW_TAG_subprogram))
13486     complaint (_("DIE %s and its abstract origin %s have different tags"),
13487                sect_offset_str (die->sect_off),
13488                sect_offset_str (origin_die->sect_off));
13489
13490   std::vector<sect_offset> offsets;
13491
13492   for (child_die = die->child;
13493        child_die && child_die->tag;
13494        child_die = sibling_die (child_die))
13495     {
13496       struct die_info *child_origin_die;
13497       struct dwarf2_cu *child_origin_cu;
13498
13499       /* We are trying to process concrete instance entries:
13500          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13501          it's not relevant to our analysis here. i.e. detecting DIEs that are
13502          present in the abstract instance but not referenced in the concrete
13503          one.  */
13504       if (child_die->tag == DW_TAG_call_site
13505           || child_die->tag == DW_TAG_GNU_call_site)
13506         continue;
13507
13508       /* For each CHILD_DIE, find the corresponding child of
13509          ORIGIN_DIE.  If there is more than one layer of
13510          DW_AT_abstract_origin, follow them all; there shouldn't be,
13511          but GCC versions at least through 4.4 generate this (GCC PR
13512          40573).  */
13513       child_origin_die = child_die;
13514       child_origin_cu = cu;
13515       while (1)
13516         {
13517           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13518                               child_origin_cu);
13519           if (attr == NULL)
13520             break;
13521           child_origin_die = follow_die_ref (child_origin_die, attr,
13522                                              &child_origin_cu);
13523         }
13524
13525       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13526          counterpart may exist.  */
13527       if (child_origin_die != child_die)
13528         {
13529           if (child_die->tag != child_origin_die->tag
13530               && !(child_die->tag == DW_TAG_inlined_subroutine
13531                    && child_origin_die->tag == DW_TAG_subprogram))
13532             complaint (_("Child DIE %s and its abstract origin %s have "
13533                          "different tags"),
13534                        sect_offset_str (child_die->sect_off),
13535                        sect_offset_str (child_origin_die->sect_off));
13536           if (child_origin_die->parent != origin_die)
13537             complaint (_("Child DIE %s and its abstract origin %s have "
13538                          "different parents"),
13539                        sect_offset_str (child_die->sect_off),
13540                        sect_offset_str (child_origin_die->sect_off));
13541           else
13542             offsets.push_back (child_origin_die->sect_off);
13543         }
13544     }
13545   std::sort (offsets.begin (), offsets.end ());
13546   sect_offset *offsets_end = offsets.data () + offsets.size ();
13547   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13548     if (offsetp[-1] == *offsetp)
13549       complaint (_("Multiple children of DIE %s refer "
13550                    "to DIE %s as their abstract origin"),
13551                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13552
13553   offsetp = offsets.data ();
13554   origin_child_die = origin_die->child;
13555   while (origin_child_die && origin_child_die->tag)
13556     {
13557       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13558       while (offsetp < offsets_end
13559              && *offsetp < origin_child_die->sect_off)
13560         offsetp++;
13561       if (offsetp >= offsets_end
13562           || *offsetp > origin_child_die->sect_off)
13563         {
13564           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13565              Check whether we're already processing ORIGIN_CHILD_DIE.
13566              This can happen with mutually referenced abstract_origins.
13567              PR 16581.  */
13568           if (!origin_child_die->in_process)
13569             process_die (origin_child_die, origin_cu);
13570         }
13571       origin_child_die = sibling_die (origin_child_die);
13572     }
13573   origin_cu->list_in_scope = origin_previous_list_in_scope;
13574 }
13575
13576 static void
13577 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13578 {
13579   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13580   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13581   struct context_stack *newobj;
13582   CORE_ADDR lowpc;
13583   CORE_ADDR highpc;
13584   struct die_info *child_die;
13585   struct attribute *attr, *call_line, *call_file;
13586   const char *name;
13587   CORE_ADDR baseaddr;
13588   struct block *block;
13589   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13590   std::vector<struct symbol *> template_args;
13591   struct template_symbol *templ_func = NULL;
13592
13593   if (inlined_func)
13594     {
13595       /* If we do not have call site information, we can't show the
13596          caller of this inlined function.  That's too confusing, so
13597          only use the scope for local variables.  */
13598       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13599       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13600       if (call_line == NULL || call_file == NULL)
13601         {
13602           read_lexical_block_scope (die, cu);
13603           return;
13604         }
13605     }
13606
13607   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13608
13609   name = dwarf2_name (die, cu);
13610
13611   /* Ignore functions with missing or empty names.  These are actually
13612      illegal according to the DWARF standard.  */
13613   if (name == NULL)
13614     {
13615       complaint (_("missing name for subprogram DIE at %s"),
13616                  sect_offset_str (die->sect_off));
13617       return;
13618     }
13619
13620   /* Ignore functions with missing or invalid low and high pc attributes.  */
13621   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13622       <= PC_BOUNDS_INVALID)
13623     {
13624       attr = dwarf2_attr (die, DW_AT_external, cu);
13625       if (!attr || !DW_UNSND (attr))
13626         complaint (_("cannot get low and high bounds "
13627                      "for subprogram DIE at %s"),
13628                    sect_offset_str (die->sect_off));
13629       return;
13630     }
13631
13632   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13633   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13634
13635   /* If we have any template arguments, then we must allocate a
13636      different sort of symbol.  */
13637   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13638     {
13639       if (child_die->tag == DW_TAG_template_type_param
13640           || child_die->tag == DW_TAG_template_value_param)
13641         {
13642           templ_func = allocate_template_symbol (objfile);
13643           templ_func->subclass = SYMBOL_TEMPLATE;
13644           break;
13645         }
13646     }
13647
13648   newobj = cu->builder->push_context (0, lowpc);
13649   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13650                              (struct symbol *) templ_func);
13651
13652   /* If there is a location expression for DW_AT_frame_base, record
13653      it.  */
13654   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13655   if (attr)
13656     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13657
13658   /* If there is a location for the static link, record it.  */
13659   newobj->static_link = NULL;
13660   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13661   if (attr)
13662     {
13663       newobj->static_link
13664         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13665       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13666     }
13667
13668   cu->list_in_scope = cu->builder->get_local_symbols ();
13669
13670   if (die->child != NULL)
13671     {
13672       child_die = die->child;
13673       while (child_die && child_die->tag)
13674         {
13675           if (child_die->tag == DW_TAG_template_type_param
13676               || child_die->tag == DW_TAG_template_value_param)
13677             {
13678               struct symbol *arg = new_symbol (child_die, NULL, cu);
13679
13680               if (arg != NULL)
13681                 template_args.push_back (arg);
13682             }
13683           else
13684             process_die (child_die, cu);
13685           child_die = sibling_die (child_die);
13686         }
13687     }
13688
13689   inherit_abstract_dies (die, cu);
13690
13691   /* If we have a DW_AT_specification, we might need to import using
13692      directives from the context of the specification DIE.  See the
13693      comment in determine_prefix.  */
13694   if (cu->language == language_cplus
13695       && dwarf2_attr (die, DW_AT_specification, cu))
13696     {
13697       struct dwarf2_cu *spec_cu = cu;
13698       struct die_info *spec_die = die_specification (die, &spec_cu);
13699
13700       while (spec_die)
13701         {
13702           child_die = spec_die->child;
13703           while (child_die && child_die->tag)
13704             {
13705               if (child_die->tag == DW_TAG_imported_module)
13706                 process_die (child_die, spec_cu);
13707               child_die = sibling_die (child_die);
13708             }
13709
13710           /* In some cases, GCC generates specification DIEs that
13711              themselves contain DW_AT_specification attributes.  */
13712           spec_die = die_specification (spec_die, &spec_cu);
13713         }
13714     }
13715
13716   struct context_stack cstk = cu->builder->pop_context ();
13717   /* Make a block for the local symbols within.  */
13718   block = cu->builder->finish_block (cstk.name, cstk.old_blocks,
13719                                      cstk.static_link, lowpc, highpc);
13720
13721   /* For C++, set the block's scope.  */
13722   if ((cu->language == language_cplus
13723        || cu->language == language_fortran
13724        || cu->language == language_d
13725        || cu->language == language_rust)
13726       && cu->processing_has_namespace_info)
13727     block_set_scope (block, determine_prefix (die, cu),
13728                      &objfile->objfile_obstack);
13729
13730   /* If we have address ranges, record them.  */
13731   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13732
13733   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13734
13735   /* Attach template arguments to function.  */
13736   if (!template_args.empty ())
13737     {
13738       gdb_assert (templ_func != NULL);
13739
13740       templ_func->n_template_arguments = template_args.size ();
13741       templ_func->template_arguments
13742         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13743                      templ_func->n_template_arguments);
13744       memcpy (templ_func->template_arguments,
13745               template_args.data (),
13746               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13747     }
13748
13749   /* In C++, we can have functions nested inside functions (e.g., when
13750      a function declares a class that has methods).  This means that
13751      when we finish processing a function scope, we may need to go
13752      back to building a containing block's symbol lists.  */
13753   *cu->builder->get_local_symbols () = cstk.locals;
13754   cu->builder->set_local_using_directives (cstk.local_using_directives);
13755
13756   /* If we've finished processing a top-level function, subsequent
13757      symbols go in the file symbol list.  */
13758   if (cu->builder->outermost_context_p ())
13759     cu->list_in_scope = cu->builder->get_file_symbols ();
13760 }
13761
13762 /* Process all the DIES contained within a lexical block scope.  Start
13763    a new scope, process the dies, and then close the scope.  */
13764
13765 static void
13766 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13767 {
13768   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13769   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13770   CORE_ADDR lowpc, highpc;
13771   struct die_info *child_die;
13772   CORE_ADDR baseaddr;
13773
13774   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13775
13776   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13777   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13778      as multiple lexical blocks?  Handling children in a sane way would
13779      be nasty.  Might be easier to properly extend generic blocks to
13780      describe ranges.  */
13781   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13782     {
13783     case PC_BOUNDS_NOT_PRESENT:
13784       /* DW_TAG_lexical_block has no attributes, process its children as if
13785          there was no wrapping by that DW_TAG_lexical_block.
13786          GCC does no longer produces such DWARF since GCC r224161.  */
13787       for (child_die = die->child;
13788            child_die != NULL && child_die->tag;
13789            child_die = sibling_die (child_die))
13790         process_die (child_die, cu);
13791       return;
13792     case PC_BOUNDS_INVALID:
13793       return;
13794     }
13795   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13796   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13797
13798   cu->builder->push_context (0, lowpc);
13799   if (die->child != NULL)
13800     {
13801       child_die = die->child;
13802       while (child_die && child_die->tag)
13803         {
13804           process_die (child_die, cu);
13805           child_die = sibling_die (child_die);
13806         }
13807     }
13808   inherit_abstract_dies (die, cu);
13809   struct context_stack cstk = cu->builder->pop_context ();
13810
13811   if (*cu->builder->get_local_symbols () != NULL
13812       || (*cu->builder->get_local_using_directives ()) != NULL)
13813     {
13814       struct block *block
13815         = cu->builder->finish_block (0, cstk.old_blocks, NULL,
13816                                      cstk.start_addr, highpc);
13817
13818       /* Note that recording ranges after traversing children, as we
13819          do here, means that recording a parent's ranges entails
13820          walking across all its children's ranges as they appear in
13821          the address map, which is quadratic behavior.
13822
13823          It would be nicer to record the parent's ranges before
13824          traversing its children, simply overriding whatever you find
13825          there.  But since we don't even decide whether to create a
13826          block until after we've traversed its children, that's hard
13827          to do.  */
13828       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13829     }
13830   *cu->builder->get_local_symbols () = cstk.locals;
13831   cu->builder->set_local_using_directives (cstk.local_using_directives);
13832 }
13833
13834 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13835
13836 static void
13837 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13838 {
13839   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13840   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13841   CORE_ADDR pc, baseaddr;
13842   struct attribute *attr;
13843   struct call_site *call_site, call_site_local;
13844   void **slot;
13845   int nparams;
13846   struct die_info *child_die;
13847
13848   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13849
13850   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13851   if (attr == NULL)
13852     {
13853       /* This was a pre-DWARF-5 GNU extension alias
13854          for DW_AT_call_return_pc.  */
13855       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13856     }
13857   if (!attr)
13858     {
13859       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13860                    "DIE %s [in module %s]"),
13861                  sect_offset_str (die->sect_off), objfile_name (objfile));
13862       return;
13863     }
13864   pc = attr_value_as_address (attr) + baseaddr;
13865   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13866
13867   if (cu->call_site_htab == NULL)
13868     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13869                                                NULL, &objfile->objfile_obstack,
13870                                                hashtab_obstack_allocate, NULL);
13871   call_site_local.pc = pc;
13872   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13873   if (*slot != NULL)
13874     {
13875       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13876                    "DIE %s [in module %s]"),
13877                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13878                  objfile_name (objfile));
13879       return;
13880     }
13881
13882   /* Count parameters at the caller.  */
13883
13884   nparams = 0;
13885   for (child_die = die->child; child_die && child_die->tag;
13886        child_die = sibling_die (child_die))
13887     {
13888       if (child_die->tag != DW_TAG_call_site_parameter
13889           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13890         {
13891           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13892                        "DW_TAG_call_site child DIE %s [in module %s]"),
13893                      child_die->tag, sect_offset_str (child_die->sect_off),
13894                      objfile_name (objfile));
13895           continue;
13896         }
13897
13898       nparams++;
13899     }
13900
13901   call_site
13902     = ((struct call_site *)
13903        obstack_alloc (&objfile->objfile_obstack,
13904                       sizeof (*call_site)
13905                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13906   *slot = call_site;
13907   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13908   call_site->pc = pc;
13909
13910   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13911       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13912     {
13913       struct die_info *func_die;
13914
13915       /* Skip also over DW_TAG_inlined_subroutine.  */
13916       for (func_die = die->parent;
13917            func_die && func_die->tag != DW_TAG_subprogram
13918            && func_die->tag != DW_TAG_subroutine_type;
13919            func_die = func_die->parent);
13920
13921       /* DW_AT_call_all_calls is a superset
13922          of DW_AT_call_all_tail_calls.  */
13923       if (func_die
13924           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13925           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13926           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13927           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13928         {
13929           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13930              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13931              both the initial caller containing the real return address PC and
13932              the final callee containing the current PC of a chain of tail
13933              calls do not need to have the tail call list complete.  But any
13934              function candidate for a virtual tail call frame searched via
13935              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13936              determined unambiguously.  */
13937         }
13938       else
13939         {
13940           struct type *func_type = NULL;
13941
13942           if (func_die)
13943             func_type = get_die_type (func_die, cu);
13944           if (func_type != NULL)
13945             {
13946               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13947
13948               /* Enlist this call site to the function.  */
13949               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13950               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13951             }
13952           else
13953             complaint (_("Cannot find function owning DW_TAG_call_site "
13954                          "DIE %s [in module %s]"),
13955                        sect_offset_str (die->sect_off), objfile_name (objfile));
13956         }
13957     }
13958
13959   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13960   if (attr == NULL)
13961     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13962   if (attr == NULL)
13963     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13964   if (attr == NULL)
13965     {
13966       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13967       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13968     }
13969   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13970   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
13971     /* Keep NULL DWARF_BLOCK.  */;
13972   else if (attr_form_is_block (attr))
13973     {
13974       struct dwarf2_locexpr_baton *dlbaton;
13975
13976       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13977       dlbaton->data = DW_BLOCK (attr)->data;
13978       dlbaton->size = DW_BLOCK (attr)->size;
13979       dlbaton->per_cu = cu->per_cu;
13980
13981       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13982     }
13983   else if (attr_form_is_ref (attr))
13984     {
13985       struct dwarf2_cu *target_cu = cu;
13986       struct die_info *target_die;
13987
13988       target_die = follow_die_ref (die, attr, &target_cu);
13989       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
13990       if (die_is_declaration (target_die, target_cu))
13991         {
13992           const char *target_physname;
13993
13994           /* Prefer the mangled name; otherwise compute the demangled one.  */
13995           target_physname = dw2_linkage_name (target_die, target_cu);
13996           if (target_physname == NULL)
13997             target_physname = dwarf2_physname (NULL, target_die, target_cu);
13998           if (target_physname == NULL)
13999             complaint (_("DW_AT_call_target target DIE has invalid "
14000                          "physname, for referencing DIE %s [in module %s]"),
14001                        sect_offset_str (die->sect_off), objfile_name (objfile));
14002           else
14003             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14004         }
14005       else
14006         {
14007           CORE_ADDR lowpc;
14008
14009           /* DW_AT_entry_pc should be preferred.  */
14010           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14011               <= PC_BOUNDS_INVALID)
14012             complaint (_("DW_AT_call_target target DIE has invalid "
14013                          "low pc, for referencing DIE %s [in module %s]"),
14014                        sect_offset_str (die->sect_off), objfile_name (objfile));
14015           else
14016             {
14017               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14018               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14019             }
14020         }
14021     }
14022   else
14023     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
14024                  "block nor reference, for DIE %s [in module %s]"),
14025                sect_offset_str (die->sect_off), objfile_name (objfile));
14026
14027   call_site->per_cu = cu->per_cu;
14028
14029   for (child_die = die->child;
14030        child_die && child_die->tag;
14031        child_die = sibling_die (child_die))
14032     {
14033       struct call_site_parameter *parameter;
14034       struct attribute *loc, *origin;
14035
14036       if (child_die->tag != DW_TAG_call_site_parameter
14037           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14038         {
14039           /* Already printed the complaint above.  */
14040           continue;
14041         }
14042
14043       gdb_assert (call_site->parameter_count < nparams);
14044       parameter = &call_site->parameter[call_site->parameter_count];
14045
14046       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14047          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14048          register is contained in DW_AT_call_value.  */
14049
14050       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14051       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14052       if (origin == NULL)
14053         {
14054           /* This was a pre-DWARF-5 GNU extension alias
14055              for DW_AT_call_parameter.  */
14056           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14057         }
14058       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14059         {
14060           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14061
14062           sect_offset sect_off
14063             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14064           if (!offset_in_cu_p (&cu->header, sect_off))
14065             {
14066               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14067                  binding can be done only inside one CU.  Such referenced DIE
14068                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14069               complaint (_("DW_AT_call_parameter offset is not in CU for "
14070                            "DW_TAG_call_site child DIE %s [in module %s]"),
14071                          sect_offset_str (child_die->sect_off),
14072                          objfile_name (objfile));
14073               continue;
14074             }
14075           parameter->u.param_cu_off
14076             = (cu_offset) (sect_off - cu->header.sect_off);
14077         }
14078       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14079         {
14080           complaint (_("No DW_FORM_block* DW_AT_location for "
14081                        "DW_TAG_call_site child DIE %s [in module %s]"),
14082                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14083           continue;
14084         }
14085       else
14086         {
14087           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14088             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14089           if (parameter->u.dwarf_reg != -1)
14090             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14091           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14092                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14093                                              &parameter->u.fb_offset))
14094             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14095           else
14096             {
14097               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14098                            "for DW_FORM_block* DW_AT_location is supported for "
14099                            "DW_TAG_call_site child DIE %s "
14100                            "[in module %s]"),
14101                          sect_offset_str (child_die->sect_off),
14102                          objfile_name (objfile));
14103               continue;
14104             }
14105         }
14106
14107       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14108       if (attr == NULL)
14109         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14110       if (!attr_form_is_block (attr))
14111         {
14112           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14113                        "DW_TAG_call_site child DIE %s [in module %s]"),
14114                      sect_offset_str (child_die->sect_off),
14115                      objfile_name (objfile));
14116           continue;
14117         }
14118       parameter->value = DW_BLOCK (attr)->data;
14119       parameter->value_size = DW_BLOCK (attr)->size;
14120
14121       /* Parameters are not pre-cleared by memset above.  */
14122       parameter->data_value = NULL;
14123       parameter->data_value_size = 0;
14124       call_site->parameter_count++;
14125
14126       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14127       if (attr == NULL)
14128         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14129       if (attr)
14130         {
14131           if (!attr_form_is_block (attr))
14132             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14133                          "DW_TAG_call_site child DIE %s [in module %s]"),
14134                        sect_offset_str (child_die->sect_off),
14135                        objfile_name (objfile));
14136           else
14137             {
14138               parameter->data_value = DW_BLOCK (attr)->data;
14139               parameter->data_value_size = DW_BLOCK (attr)->size;
14140             }
14141         }
14142     }
14143 }
14144
14145 /* Helper function for read_variable.  If DIE represents a virtual
14146    table, then return the type of the concrete object that is
14147    associated with the virtual table.  Otherwise, return NULL.  */
14148
14149 static struct type *
14150 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14151 {
14152   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14153   if (attr == NULL)
14154     return NULL;
14155
14156   /* Find the type DIE.  */
14157   struct die_info *type_die = NULL;
14158   struct dwarf2_cu *type_cu = cu;
14159
14160   if (attr_form_is_ref (attr))
14161     type_die = follow_die_ref (die, attr, &type_cu);
14162   if (type_die == NULL)
14163     return NULL;
14164
14165   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14166     return NULL;
14167   return die_containing_type (type_die, type_cu);
14168 }
14169
14170 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14171
14172 static void
14173 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14174 {
14175   struct rust_vtable_symbol *storage = NULL;
14176
14177   if (cu->language == language_rust)
14178     {
14179       struct type *containing_type = rust_containing_type (die, cu);
14180
14181       if (containing_type != NULL)
14182         {
14183           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14184
14185           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14186                                     struct rust_vtable_symbol);
14187           initialize_objfile_symbol (storage);
14188           storage->concrete_type = containing_type;
14189           storage->subclass = SYMBOL_RUST_VTABLE;
14190         }
14191     }
14192
14193   new_symbol (die, NULL, cu, storage);
14194 }
14195
14196 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14197    reading .debug_rnglists.
14198    Callback's type should be:
14199     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14200    Return true if the attributes are present and valid, otherwise,
14201    return false.  */
14202
14203 template <typename Callback>
14204 static bool
14205 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14206                          Callback &&callback)
14207 {
14208   struct dwarf2_per_objfile *dwarf2_per_objfile
14209     = cu->per_cu->dwarf2_per_objfile;
14210   struct objfile *objfile = dwarf2_per_objfile->objfile;
14211   bfd *obfd = objfile->obfd;
14212   /* Base address selection entry.  */
14213   CORE_ADDR base;
14214   int found_base;
14215   const gdb_byte *buffer;
14216   CORE_ADDR baseaddr;
14217   bool overflow = false;
14218
14219   found_base = cu->base_known;
14220   base = cu->base_address;
14221
14222   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14223   if (offset >= dwarf2_per_objfile->rnglists.size)
14224     {
14225       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14226                  offset);
14227       return false;
14228     }
14229   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14230
14231   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14232
14233   while (1)
14234     {
14235       /* Initialize it due to a false compiler warning.  */
14236       CORE_ADDR range_beginning = 0, range_end = 0;
14237       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14238                                  + dwarf2_per_objfile->rnglists.size);
14239       unsigned int bytes_read;
14240
14241       if (buffer == buf_end)
14242         {
14243           overflow = true;
14244           break;
14245         }
14246       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14247       switch (rlet)
14248         {
14249         case DW_RLE_end_of_list:
14250           break;
14251         case DW_RLE_base_address:
14252           if (buffer + cu->header.addr_size > buf_end)
14253             {
14254               overflow = true;
14255               break;
14256             }
14257           base = read_address (obfd, buffer, cu, &bytes_read);
14258           found_base = 1;
14259           buffer += bytes_read;
14260           break;
14261         case DW_RLE_start_length:
14262           if (buffer + cu->header.addr_size > buf_end)
14263             {
14264               overflow = true;
14265               break;
14266             }
14267           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14268           buffer += bytes_read;
14269           range_end = (range_beginning
14270                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14271           buffer += bytes_read;
14272           if (buffer > buf_end)
14273             {
14274               overflow = true;
14275               break;
14276             }
14277           break;
14278         case DW_RLE_offset_pair:
14279           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14280           buffer += bytes_read;
14281           if (buffer > buf_end)
14282             {
14283               overflow = true;
14284               break;
14285             }
14286           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14287           buffer += bytes_read;
14288           if (buffer > buf_end)
14289             {
14290               overflow = true;
14291               break;
14292             }
14293           break;
14294         case DW_RLE_start_end:
14295           if (buffer + 2 * cu->header.addr_size > buf_end)
14296             {
14297               overflow = true;
14298               break;
14299             }
14300           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14301           buffer += bytes_read;
14302           range_end = read_address (obfd, buffer, cu, &bytes_read);
14303           buffer += bytes_read;
14304           break;
14305         default:
14306           complaint (_("Invalid .debug_rnglists data (no base address)"));
14307           return false;
14308         }
14309       if (rlet == DW_RLE_end_of_list || overflow)
14310         break;
14311       if (rlet == DW_RLE_base_address)
14312         continue;
14313
14314       if (!found_base)
14315         {
14316           /* We have no valid base address for the ranges
14317              data.  */
14318           complaint (_("Invalid .debug_rnglists data (no base address)"));
14319           return false;
14320         }
14321
14322       if (range_beginning > range_end)
14323         {
14324           /* Inverted range entries are invalid.  */
14325           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14326           return false;
14327         }
14328
14329       /* Empty range entries have no effect.  */
14330       if (range_beginning == range_end)
14331         continue;
14332
14333       range_beginning += base;
14334       range_end += base;
14335
14336       /* A not-uncommon case of bad debug info.
14337          Don't pollute the addrmap with bad data.  */
14338       if (range_beginning + baseaddr == 0
14339           && !dwarf2_per_objfile->has_section_at_zero)
14340         {
14341           complaint (_(".debug_rnglists entry has start address of zero"
14342                        " [in module %s]"), objfile_name (objfile));
14343           continue;
14344         }
14345
14346       callback (range_beginning, range_end);
14347     }
14348
14349   if (overflow)
14350     {
14351       complaint (_("Offset %d is not terminated "
14352                    "for DW_AT_ranges attribute"),
14353                  offset);
14354       return false;
14355     }
14356
14357   return true;
14358 }
14359
14360 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14361    Callback's type should be:
14362     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14363    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14364
14365 template <typename Callback>
14366 static int
14367 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14368                        Callback &&callback)
14369 {
14370   struct dwarf2_per_objfile *dwarf2_per_objfile
14371       = cu->per_cu->dwarf2_per_objfile;
14372   struct objfile *objfile = dwarf2_per_objfile->objfile;
14373   struct comp_unit_head *cu_header = &cu->header;
14374   bfd *obfd = objfile->obfd;
14375   unsigned int addr_size = cu_header->addr_size;
14376   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14377   /* Base address selection entry.  */
14378   CORE_ADDR base;
14379   int found_base;
14380   unsigned int dummy;
14381   const gdb_byte *buffer;
14382   CORE_ADDR baseaddr;
14383
14384   if (cu_header->version >= 5)
14385     return dwarf2_rnglists_process (offset, cu, callback);
14386
14387   found_base = cu->base_known;
14388   base = cu->base_address;
14389
14390   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14391   if (offset >= dwarf2_per_objfile->ranges.size)
14392     {
14393       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14394                  offset);
14395       return 0;
14396     }
14397   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14398
14399   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14400
14401   while (1)
14402     {
14403       CORE_ADDR range_beginning, range_end;
14404
14405       range_beginning = read_address (obfd, buffer, cu, &dummy);
14406       buffer += addr_size;
14407       range_end = read_address (obfd, buffer, cu, &dummy);
14408       buffer += addr_size;
14409       offset += 2 * addr_size;
14410
14411       /* An end of list marker is a pair of zero addresses.  */
14412       if (range_beginning == 0 && range_end == 0)
14413         /* Found the end of list entry.  */
14414         break;
14415
14416       /* Each base address selection entry is a pair of 2 values.
14417          The first is the largest possible address, the second is
14418          the base address.  Check for a base address here.  */
14419       if ((range_beginning & mask) == mask)
14420         {
14421           /* If we found the largest possible address, then we already
14422              have the base address in range_end.  */
14423           base = range_end;
14424           found_base = 1;
14425           continue;
14426         }
14427
14428       if (!found_base)
14429         {
14430           /* We have no valid base address for the ranges
14431              data.  */
14432           complaint (_("Invalid .debug_ranges data (no base address)"));
14433           return 0;
14434         }
14435
14436       if (range_beginning > range_end)
14437         {
14438           /* Inverted range entries are invalid.  */
14439           complaint (_("Invalid .debug_ranges data (inverted range)"));
14440           return 0;
14441         }
14442
14443       /* Empty range entries have no effect.  */
14444       if (range_beginning == range_end)
14445         continue;
14446
14447       range_beginning += base;
14448       range_end += base;
14449
14450       /* A not-uncommon case of bad debug info.
14451          Don't pollute the addrmap with bad data.  */
14452       if (range_beginning + baseaddr == 0
14453           && !dwarf2_per_objfile->has_section_at_zero)
14454         {
14455           complaint (_(".debug_ranges entry has start address of zero"
14456                        " [in module %s]"), objfile_name (objfile));
14457           continue;
14458         }
14459
14460       callback (range_beginning, range_end);
14461     }
14462
14463   return 1;
14464 }
14465
14466 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14467    Return 1 if the attributes are present and valid, otherwise, return 0.
14468    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14469
14470 static int
14471 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14472                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14473                     struct partial_symtab *ranges_pst)
14474 {
14475   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14476   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14477   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14478                                        SECT_OFF_TEXT (objfile));
14479   int low_set = 0;
14480   CORE_ADDR low = 0;
14481   CORE_ADDR high = 0;
14482   int retval;
14483
14484   retval = dwarf2_ranges_process (offset, cu,
14485     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14486     {
14487       if (ranges_pst != NULL)
14488         {
14489           CORE_ADDR lowpc;
14490           CORE_ADDR highpc;
14491
14492           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14493                                               range_beginning + baseaddr);
14494           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14495                                                range_end + baseaddr);
14496           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14497                              ranges_pst);
14498         }
14499
14500       /* FIXME: This is recording everything as a low-high
14501          segment of consecutive addresses.  We should have a
14502          data structure for discontiguous block ranges
14503          instead.  */
14504       if (! low_set)
14505         {
14506           low = range_beginning;
14507           high = range_end;
14508           low_set = 1;
14509         }
14510       else
14511         {
14512           if (range_beginning < low)
14513             low = range_beginning;
14514           if (range_end > high)
14515             high = range_end;
14516         }
14517     });
14518   if (!retval)
14519     return 0;
14520
14521   if (! low_set)
14522     /* If the first entry is an end-of-list marker, the range
14523        describes an empty scope, i.e. no instructions.  */
14524     return 0;
14525
14526   if (low_return)
14527     *low_return = low;
14528   if (high_return)
14529     *high_return = high;
14530   return 1;
14531 }
14532
14533 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14534    definition for the return value.  *LOWPC and *HIGHPC are set iff
14535    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14536
14537 static enum pc_bounds_kind
14538 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14539                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14540                       struct partial_symtab *pst)
14541 {
14542   struct dwarf2_per_objfile *dwarf2_per_objfile
14543     = cu->per_cu->dwarf2_per_objfile;
14544   struct attribute *attr;
14545   struct attribute *attr_high;
14546   CORE_ADDR low = 0;
14547   CORE_ADDR high = 0;
14548   enum pc_bounds_kind ret;
14549
14550   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14551   if (attr_high)
14552     {
14553       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14554       if (attr)
14555         {
14556           low = attr_value_as_address (attr);
14557           high = attr_value_as_address (attr_high);
14558           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14559             high += low;
14560         }
14561       else
14562         /* Found high w/o low attribute.  */
14563         return PC_BOUNDS_INVALID;
14564
14565       /* Found consecutive range of addresses.  */
14566       ret = PC_BOUNDS_HIGH_LOW;
14567     }
14568   else
14569     {
14570       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14571       if (attr != NULL)
14572         {
14573           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14574              We take advantage of the fact that DW_AT_ranges does not appear
14575              in DW_TAG_compile_unit of DWO files.  */
14576           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14577           unsigned int ranges_offset = (DW_UNSND (attr)
14578                                         + (need_ranges_base
14579                                            ? cu->ranges_base
14580                                            : 0));
14581
14582           /* Value of the DW_AT_ranges attribute is the offset in the
14583              .debug_ranges section.  */
14584           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14585             return PC_BOUNDS_INVALID;
14586           /* Found discontinuous range of addresses.  */
14587           ret = PC_BOUNDS_RANGES;
14588         }
14589       else
14590         return PC_BOUNDS_NOT_PRESENT;
14591     }
14592
14593   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14594   if (high <= low)
14595     return PC_BOUNDS_INVALID;
14596
14597   /* When using the GNU linker, .gnu.linkonce. sections are used to
14598      eliminate duplicate copies of functions and vtables and such.
14599      The linker will arbitrarily choose one and discard the others.
14600      The AT_*_pc values for such functions refer to local labels in
14601      these sections.  If the section from that file was discarded, the
14602      labels are not in the output, so the relocs get a value of 0.
14603      If this is a discarded function, mark the pc bounds as invalid,
14604      so that GDB will ignore it.  */
14605   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14606     return PC_BOUNDS_INVALID;
14607
14608   *lowpc = low;
14609   if (highpc)
14610     *highpc = high;
14611   return ret;
14612 }
14613
14614 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14615    its low and high PC addresses.  Do nothing if these addresses could not
14616    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14617    and HIGHPC to the high address if greater than HIGHPC.  */
14618
14619 static void
14620 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14621                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14622                                  struct dwarf2_cu *cu)
14623 {
14624   CORE_ADDR low, high;
14625   struct die_info *child = die->child;
14626
14627   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14628     {
14629       *lowpc = std::min (*lowpc, low);
14630       *highpc = std::max (*highpc, high);
14631     }
14632
14633   /* If the language does not allow nested subprograms (either inside
14634      subprograms or lexical blocks), we're done.  */
14635   if (cu->language != language_ada)
14636     return;
14637
14638   /* Check all the children of the given DIE.  If it contains nested
14639      subprograms, then check their pc bounds.  Likewise, we need to
14640      check lexical blocks as well, as they may also contain subprogram
14641      definitions.  */
14642   while (child && child->tag)
14643     {
14644       if (child->tag == DW_TAG_subprogram
14645           || child->tag == DW_TAG_lexical_block)
14646         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14647       child = sibling_die (child);
14648     }
14649 }
14650
14651 /* Get the low and high pc's represented by the scope DIE, and store
14652    them in *LOWPC and *HIGHPC.  If the correct values can't be
14653    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14654
14655 static void
14656 get_scope_pc_bounds (struct die_info *die,
14657                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14658                      struct dwarf2_cu *cu)
14659 {
14660   CORE_ADDR best_low = (CORE_ADDR) -1;
14661   CORE_ADDR best_high = (CORE_ADDR) 0;
14662   CORE_ADDR current_low, current_high;
14663
14664   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14665       >= PC_BOUNDS_RANGES)
14666     {
14667       best_low = current_low;
14668       best_high = current_high;
14669     }
14670   else
14671     {
14672       struct die_info *child = die->child;
14673
14674       while (child && child->tag)
14675         {
14676           switch (child->tag) {
14677           case DW_TAG_subprogram:
14678             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14679             break;
14680           case DW_TAG_namespace:
14681           case DW_TAG_module:
14682             /* FIXME: carlton/2004-01-16: Should we do this for
14683                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14684                that current GCC's always emit the DIEs corresponding
14685                to definitions of methods of classes as children of a
14686                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14687                the DIEs giving the declarations, which could be
14688                anywhere).  But I don't see any reason why the
14689                standards says that they have to be there.  */
14690             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14691
14692             if (current_low != ((CORE_ADDR) -1))
14693               {
14694                 best_low = std::min (best_low, current_low);
14695                 best_high = std::max (best_high, current_high);
14696               }
14697             break;
14698           default:
14699             /* Ignore.  */
14700             break;
14701           }
14702
14703           child = sibling_die (child);
14704         }
14705     }
14706
14707   *lowpc = best_low;
14708   *highpc = best_high;
14709 }
14710
14711 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14712    in DIE.  */
14713
14714 static void
14715 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14716                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14717 {
14718   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14719   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14720   struct attribute *attr;
14721   struct attribute *attr_high;
14722
14723   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14724   if (attr_high)
14725     {
14726       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14727       if (attr)
14728         {
14729           CORE_ADDR low = attr_value_as_address (attr);
14730           CORE_ADDR high = attr_value_as_address (attr_high);
14731
14732           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14733             high += low;
14734
14735           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14736           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14737           cu->builder->record_block_range (block, low, high - 1);
14738         }
14739     }
14740
14741   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14742   if (attr)
14743     {
14744       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14745          We take advantage of the fact that DW_AT_ranges does not appear
14746          in DW_TAG_compile_unit of DWO files.  */
14747       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14748
14749       /* The value of the DW_AT_ranges attribute is the offset of the
14750          address range list in the .debug_ranges section.  */
14751       unsigned long offset = (DW_UNSND (attr)
14752                               + (need_ranges_base ? cu->ranges_base : 0));
14753
14754       dwarf2_ranges_process (offset, cu,
14755         [&] (CORE_ADDR start, CORE_ADDR end)
14756         {
14757           start += baseaddr;
14758           end += baseaddr;
14759           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14760           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14761           cu->builder->record_block_range (block, start, end - 1);
14762         });
14763     }
14764 }
14765
14766 /* Check whether the producer field indicates either of GCC < 4.6, or the
14767    Intel C/C++ compiler, and cache the result in CU.  */
14768
14769 static void
14770 check_producer (struct dwarf2_cu *cu)
14771 {
14772   int major, minor;
14773
14774   if (cu->producer == NULL)
14775     {
14776       /* For unknown compilers expect their behavior is DWARF version
14777          compliant.
14778
14779          GCC started to support .debug_types sections by -gdwarf-4 since
14780          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14781          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14782          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14783          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14784     }
14785   else if (producer_is_gcc (cu->producer, &major, &minor))
14786     {
14787       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14788       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14789     }
14790   else if (producer_is_icc (cu->producer, &major, &minor))
14791     cu->producer_is_icc_lt_14 = major < 14;
14792   else
14793     {
14794       /* For other non-GCC compilers, expect their behavior is DWARF version
14795          compliant.  */
14796     }
14797
14798   cu->checked_producer = 1;
14799 }
14800
14801 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14802    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14803    during 4.6.0 experimental.  */
14804
14805 static int
14806 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14807 {
14808   if (!cu->checked_producer)
14809     check_producer (cu);
14810
14811   return cu->producer_is_gxx_lt_4_6;
14812 }
14813
14814 /* Return the default accessibility type if it is not overriden by
14815    DW_AT_accessibility.  */
14816
14817 static enum dwarf_access_attribute
14818 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14819 {
14820   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14821     {
14822       /* The default DWARF 2 accessibility for members is public, the default
14823          accessibility for inheritance is private.  */
14824
14825       if (die->tag != DW_TAG_inheritance)
14826         return DW_ACCESS_public;
14827       else
14828         return DW_ACCESS_private;
14829     }
14830   else
14831     {
14832       /* DWARF 3+ defines the default accessibility a different way.  The same
14833          rules apply now for DW_TAG_inheritance as for the members and it only
14834          depends on the container kind.  */
14835
14836       if (die->parent->tag == DW_TAG_class_type)
14837         return DW_ACCESS_private;
14838       else
14839         return DW_ACCESS_public;
14840     }
14841 }
14842
14843 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14844    offset.  If the attribute was not found return 0, otherwise return
14845    1.  If it was found but could not properly be handled, set *OFFSET
14846    to 0.  */
14847
14848 static int
14849 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14850                              LONGEST *offset)
14851 {
14852   struct attribute *attr;
14853
14854   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14855   if (attr != NULL)
14856     {
14857       *offset = 0;
14858
14859       /* Note that we do not check for a section offset first here.
14860          This is because DW_AT_data_member_location is new in DWARF 4,
14861          so if we see it, we can assume that a constant form is really
14862          a constant and not a section offset.  */
14863       if (attr_form_is_constant (attr))
14864         *offset = dwarf2_get_attr_constant_value (attr, 0);
14865       else if (attr_form_is_section_offset (attr))
14866         dwarf2_complex_location_expr_complaint ();
14867       else if (attr_form_is_block (attr))
14868         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14869       else
14870         dwarf2_complex_location_expr_complaint ();
14871
14872       return 1;
14873     }
14874
14875   return 0;
14876 }
14877
14878 /* Add an aggregate field to the field list.  */
14879
14880 static void
14881 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14882                   struct dwarf2_cu *cu)
14883 {
14884   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14885   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14886   struct nextfield *new_field;
14887   struct attribute *attr;
14888   struct field *fp;
14889   const char *fieldname = "";
14890
14891   if (die->tag == DW_TAG_inheritance)
14892     {
14893       fip->baseclasses.emplace_back ();
14894       new_field = &fip->baseclasses.back ();
14895     }
14896   else
14897     {
14898       fip->fields.emplace_back ();
14899       new_field = &fip->fields.back ();
14900     }
14901
14902   fip->nfields++;
14903
14904   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14905   if (attr)
14906     new_field->accessibility = DW_UNSND (attr);
14907   else
14908     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14909   if (new_field->accessibility != DW_ACCESS_public)
14910     fip->non_public_fields = 1;
14911
14912   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14913   if (attr)
14914     new_field->virtuality = DW_UNSND (attr);
14915   else
14916     new_field->virtuality = DW_VIRTUALITY_none;
14917
14918   fp = &new_field->field;
14919
14920   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14921     {
14922       LONGEST offset;
14923
14924       /* Data member other than a C++ static data member.  */
14925
14926       /* Get type of field.  */
14927       fp->type = die_type (die, cu);
14928
14929       SET_FIELD_BITPOS (*fp, 0);
14930
14931       /* Get bit size of field (zero if none).  */
14932       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14933       if (attr)
14934         {
14935           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14936         }
14937       else
14938         {
14939           FIELD_BITSIZE (*fp) = 0;
14940         }
14941
14942       /* Get bit offset of field.  */
14943       if (handle_data_member_location (die, cu, &offset))
14944         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14945       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14946       if (attr)
14947         {
14948           if (gdbarch_bits_big_endian (gdbarch))
14949             {
14950               /* For big endian bits, the DW_AT_bit_offset gives the
14951                  additional bit offset from the MSB of the containing
14952                  anonymous object to the MSB of the field.  We don't
14953                  have to do anything special since we don't need to
14954                  know the size of the anonymous object.  */
14955               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
14956             }
14957           else
14958             {
14959               /* For little endian bits, compute the bit offset to the
14960                  MSB of the anonymous object, subtract off the number of
14961                  bits from the MSB of the field to the MSB of the
14962                  object, and then subtract off the number of bits of
14963                  the field itself.  The result is the bit offset of
14964                  the LSB of the field.  */
14965               int anonymous_size;
14966               int bit_offset = DW_UNSND (attr);
14967
14968               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14969               if (attr)
14970                 {
14971                   /* The size of the anonymous object containing
14972                      the bit field is explicit, so use the
14973                      indicated size (in bytes).  */
14974                   anonymous_size = DW_UNSND (attr);
14975                 }
14976               else
14977                 {
14978                   /* The size of the anonymous object containing
14979                      the bit field must be inferred from the type
14980                      attribute of the data member containing the
14981                      bit field.  */
14982                   anonymous_size = TYPE_LENGTH (fp->type);
14983                 }
14984               SET_FIELD_BITPOS (*fp,
14985                                 (FIELD_BITPOS (*fp)
14986                                  + anonymous_size * bits_per_byte
14987                                  - bit_offset - FIELD_BITSIZE (*fp)));
14988             }
14989         }
14990       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
14991       if (attr != NULL)
14992         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14993                                 + dwarf2_get_attr_constant_value (attr, 0)));
14994
14995       /* Get name of field.  */
14996       fieldname = dwarf2_name (die, cu);
14997       if (fieldname == NULL)
14998         fieldname = "";
14999
15000       /* The name is already allocated along with this objfile, so we don't
15001          need to duplicate it for the type.  */
15002       fp->name = fieldname;
15003
15004       /* Change accessibility for artificial fields (e.g. virtual table
15005          pointer or virtual base class pointer) to private.  */
15006       if (dwarf2_attr (die, DW_AT_artificial, cu))
15007         {
15008           FIELD_ARTIFICIAL (*fp) = 1;
15009           new_field->accessibility = DW_ACCESS_private;
15010           fip->non_public_fields = 1;
15011         }
15012     }
15013   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15014     {
15015       /* C++ static member.  */
15016
15017       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15018          is a declaration, but all versions of G++ as of this writing
15019          (so through at least 3.2.1) incorrectly generate
15020          DW_TAG_variable tags.  */
15021
15022       const char *physname;
15023
15024       /* Get name of field.  */
15025       fieldname = dwarf2_name (die, cu);
15026       if (fieldname == NULL)
15027         return;
15028
15029       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15030       if (attr
15031           /* Only create a symbol if this is an external value.
15032              new_symbol checks this and puts the value in the global symbol
15033              table, which we want.  If it is not external, new_symbol
15034              will try to put the value in cu->list_in_scope which is wrong.  */
15035           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15036         {
15037           /* A static const member, not much different than an enum as far as
15038              we're concerned, except that we can support more types.  */
15039           new_symbol (die, NULL, cu);
15040         }
15041
15042       /* Get physical name.  */
15043       physname = dwarf2_physname (fieldname, die, cu);
15044
15045       /* The name is already allocated along with this objfile, so we don't
15046          need to duplicate it for the type.  */
15047       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15048       FIELD_TYPE (*fp) = die_type (die, cu);
15049       FIELD_NAME (*fp) = fieldname;
15050     }
15051   else if (die->tag == DW_TAG_inheritance)
15052     {
15053       LONGEST offset;
15054
15055       /* C++ base class field.  */
15056       if (handle_data_member_location (die, cu, &offset))
15057         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15058       FIELD_BITSIZE (*fp) = 0;
15059       FIELD_TYPE (*fp) = die_type (die, cu);
15060       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15061     }
15062   else if (die->tag == DW_TAG_variant_part)
15063     {
15064       /* process_structure_scope will treat this DIE as a union.  */
15065       process_structure_scope (die, cu);
15066
15067       /* The variant part is relative to the start of the enclosing
15068          structure.  */
15069       SET_FIELD_BITPOS (*fp, 0);
15070       fp->type = get_die_type (die, cu);
15071       fp->artificial = 1;
15072       fp->name = "<<variant>>";
15073     }
15074   else
15075     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15076 }
15077
15078 /* Can the type given by DIE define another type?  */
15079
15080 static bool
15081 type_can_define_types (const struct die_info *die)
15082 {
15083   switch (die->tag)
15084     {
15085     case DW_TAG_typedef:
15086     case DW_TAG_class_type:
15087     case DW_TAG_structure_type:
15088     case DW_TAG_union_type:
15089     case DW_TAG_enumeration_type:
15090       return true;
15091
15092     default:
15093       return false;
15094     }
15095 }
15096
15097 /* Add a type definition defined in the scope of the FIP's class.  */
15098
15099 static void
15100 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15101                       struct dwarf2_cu *cu)
15102 {
15103   struct decl_field fp;
15104   memset (&fp, 0, sizeof (fp));
15105
15106   gdb_assert (type_can_define_types (die));
15107
15108   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15109   fp.name = dwarf2_name (die, cu);
15110   fp.type = read_type_die (die, cu);
15111
15112   /* Save accessibility.  */
15113   enum dwarf_access_attribute accessibility;
15114   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15115   if (attr != NULL)
15116     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15117   else
15118     accessibility = dwarf2_default_access_attribute (die, cu);
15119   switch (accessibility)
15120     {
15121     case DW_ACCESS_public:
15122       /* The assumed value if neither private nor protected.  */
15123       break;
15124     case DW_ACCESS_private:
15125       fp.is_private = 1;
15126       break;
15127     case DW_ACCESS_protected:
15128       fp.is_protected = 1;
15129       break;
15130     default:
15131       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15132     }
15133
15134   if (die->tag == DW_TAG_typedef)
15135     fip->typedef_field_list.push_back (fp);
15136   else
15137     fip->nested_types_list.push_back (fp);
15138 }
15139
15140 /* Create the vector of fields, and attach it to the type.  */
15141
15142 static void
15143 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15144                               struct dwarf2_cu *cu)
15145 {
15146   int nfields = fip->nfields;
15147
15148   /* Record the field count, allocate space for the array of fields,
15149      and create blank accessibility bitfields if necessary.  */
15150   TYPE_NFIELDS (type) = nfields;
15151   TYPE_FIELDS (type) = (struct field *)
15152     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15153
15154   if (fip->non_public_fields && cu->language != language_ada)
15155     {
15156       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15157
15158       TYPE_FIELD_PRIVATE_BITS (type) =
15159         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15160       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15161
15162       TYPE_FIELD_PROTECTED_BITS (type) =
15163         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15164       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15165
15166       TYPE_FIELD_IGNORE_BITS (type) =
15167         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15168       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15169     }
15170
15171   /* If the type has baseclasses, allocate and clear a bit vector for
15172      TYPE_FIELD_VIRTUAL_BITS.  */
15173   if (!fip->baseclasses.empty () && cu->language != language_ada)
15174     {
15175       int num_bytes = B_BYTES (fip->baseclasses.size ());
15176       unsigned char *pointer;
15177
15178       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15179       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15180       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15181       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15182       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15183     }
15184
15185   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15186     {
15187       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15188
15189       for (int index = 0; index < nfields; ++index)
15190         {
15191           struct nextfield &field = fip->fields[index];
15192
15193           if (field.variant.is_discriminant)
15194             di->discriminant_index = index;
15195           else if (field.variant.default_branch)
15196             di->default_index = index;
15197           else
15198             di->discriminants[index] = field.variant.discriminant_value;
15199         }
15200     }
15201
15202   /* Copy the saved-up fields into the field vector.  */
15203   for (int i = 0; i < nfields; ++i)
15204     {
15205       struct nextfield &field
15206         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15207            : fip->fields[i - fip->baseclasses.size ()]);
15208
15209       TYPE_FIELD (type, i) = field.field;
15210       switch (field.accessibility)
15211         {
15212         case DW_ACCESS_private:
15213           if (cu->language != language_ada)
15214             SET_TYPE_FIELD_PRIVATE (type, i);
15215           break;
15216
15217         case DW_ACCESS_protected:
15218           if (cu->language != language_ada)
15219             SET_TYPE_FIELD_PROTECTED (type, i);
15220           break;
15221
15222         case DW_ACCESS_public:
15223           break;
15224
15225         default:
15226           /* Unknown accessibility.  Complain and treat it as public.  */
15227           {
15228             complaint (_("unsupported accessibility %d"),
15229                        field.accessibility);
15230           }
15231           break;
15232         }
15233       if (i < fip->baseclasses.size ())
15234         {
15235           switch (field.virtuality)
15236             {
15237             case DW_VIRTUALITY_virtual:
15238             case DW_VIRTUALITY_pure_virtual:
15239               if (cu->language == language_ada)
15240                 error (_("unexpected virtuality in component of Ada type"));
15241               SET_TYPE_FIELD_VIRTUAL (type, i);
15242               break;
15243             }
15244         }
15245     }
15246 }
15247
15248 /* Return true if this member function is a constructor, false
15249    otherwise.  */
15250
15251 static int
15252 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15253 {
15254   const char *fieldname;
15255   const char *type_name;
15256   int len;
15257
15258   if (die->parent == NULL)
15259     return 0;
15260
15261   if (die->parent->tag != DW_TAG_structure_type
15262       && die->parent->tag != DW_TAG_union_type
15263       && die->parent->tag != DW_TAG_class_type)
15264     return 0;
15265
15266   fieldname = dwarf2_name (die, cu);
15267   type_name = dwarf2_name (die->parent, cu);
15268   if (fieldname == NULL || type_name == NULL)
15269     return 0;
15270
15271   len = strlen (fieldname);
15272   return (strncmp (fieldname, type_name, len) == 0
15273           && (type_name[len] == '\0' || type_name[len] == '<'));
15274 }
15275
15276 /* Add a member function to the proper fieldlist.  */
15277
15278 static void
15279 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15280                       struct type *type, struct dwarf2_cu *cu)
15281 {
15282   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15283   struct attribute *attr;
15284   int i;
15285   struct fnfieldlist *flp = nullptr;
15286   struct fn_field *fnp;
15287   const char *fieldname;
15288   struct type *this_type;
15289   enum dwarf_access_attribute accessibility;
15290
15291   if (cu->language == language_ada)
15292     error (_("unexpected member function in Ada type"));
15293
15294   /* Get name of member function.  */
15295   fieldname = dwarf2_name (die, cu);
15296   if (fieldname == NULL)
15297     return;
15298
15299   /* Look up member function name in fieldlist.  */
15300   for (i = 0; i < fip->fnfieldlists.size (); i++)
15301     {
15302       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15303         {
15304           flp = &fip->fnfieldlists[i];
15305           break;
15306         }
15307     }
15308
15309   /* Create a new fnfieldlist if necessary.  */
15310   if (flp == nullptr)
15311     {
15312       fip->fnfieldlists.emplace_back ();
15313       flp = &fip->fnfieldlists.back ();
15314       flp->name = fieldname;
15315       i = fip->fnfieldlists.size () - 1;
15316     }
15317
15318   /* Create a new member function field and add it to the vector of
15319      fnfieldlists.  */
15320   flp->fnfields.emplace_back ();
15321   fnp = &flp->fnfields.back ();
15322
15323   /* Delay processing of the physname until later.  */
15324   if (cu->language == language_cplus)
15325     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15326                         die, cu);
15327   else
15328     {
15329       const char *physname = dwarf2_physname (fieldname, die, cu);
15330       fnp->physname = physname ? physname : "";
15331     }
15332
15333   fnp->type = alloc_type (objfile);
15334   this_type = read_type_die (die, cu);
15335   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15336     {
15337       int nparams = TYPE_NFIELDS (this_type);
15338
15339       /* TYPE is the domain of this method, and THIS_TYPE is the type
15340            of the method itself (TYPE_CODE_METHOD).  */
15341       smash_to_method_type (fnp->type, type,
15342                             TYPE_TARGET_TYPE (this_type),
15343                             TYPE_FIELDS (this_type),
15344                             TYPE_NFIELDS (this_type),
15345                             TYPE_VARARGS (this_type));
15346
15347       /* Handle static member functions.
15348          Dwarf2 has no clean way to discern C++ static and non-static
15349          member functions.  G++ helps GDB by marking the first
15350          parameter for non-static member functions (which is the this
15351          pointer) as artificial.  We obtain this information from
15352          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15353       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15354         fnp->voffset = VOFFSET_STATIC;
15355     }
15356   else
15357     complaint (_("member function type missing for '%s'"),
15358                dwarf2_full_name (fieldname, die, cu));
15359
15360   /* Get fcontext from DW_AT_containing_type if present.  */
15361   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15362     fnp->fcontext = die_containing_type (die, cu);
15363
15364   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15365      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15366
15367   /* Get accessibility.  */
15368   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15369   if (attr)
15370     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15371   else
15372     accessibility = dwarf2_default_access_attribute (die, cu);
15373   switch (accessibility)
15374     {
15375     case DW_ACCESS_private:
15376       fnp->is_private = 1;
15377       break;
15378     case DW_ACCESS_protected:
15379       fnp->is_protected = 1;
15380       break;
15381     }
15382
15383   /* Check for artificial methods.  */
15384   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15385   if (attr && DW_UNSND (attr) != 0)
15386     fnp->is_artificial = 1;
15387
15388   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15389
15390   /* Get index in virtual function table if it is a virtual member
15391      function.  For older versions of GCC, this is an offset in the
15392      appropriate virtual table, as specified by DW_AT_containing_type.
15393      For everyone else, it is an expression to be evaluated relative
15394      to the object address.  */
15395
15396   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15397   if (attr)
15398     {
15399       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15400         {
15401           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15402             {
15403               /* Old-style GCC.  */
15404               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15405             }
15406           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15407                    || (DW_BLOCK (attr)->size > 1
15408                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15409                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15410             {
15411               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15412               if ((fnp->voffset % cu->header.addr_size) != 0)
15413                 dwarf2_complex_location_expr_complaint ();
15414               else
15415                 fnp->voffset /= cu->header.addr_size;
15416               fnp->voffset += 2;
15417             }
15418           else
15419             dwarf2_complex_location_expr_complaint ();
15420
15421           if (!fnp->fcontext)
15422             {
15423               /* If there is no `this' field and no DW_AT_containing_type,
15424                  we cannot actually find a base class context for the
15425                  vtable!  */
15426               if (TYPE_NFIELDS (this_type) == 0
15427                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15428                 {
15429                   complaint (_("cannot determine context for virtual member "
15430                                "function \"%s\" (offset %s)"),
15431                              fieldname, sect_offset_str (die->sect_off));
15432                 }
15433               else
15434                 {
15435                   fnp->fcontext
15436                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15437                 }
15438             }
15439         }
15440       else if (attr_form_is_section_offset (attr))
15441         {
15442           dwarf2_complex_location_expr_complaint ();
15443         }
15444       else
15445         {
15446           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15447                                                  fieldname);
15448         }
15449     }
15450   else
15451     {
15452       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15453       if (attr && DW_UNSND (attr))
15454         {
15455           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15456           complaint (_("Member function \"%s\" (offset %s) is virtual "
15457                        "but the vtable offset is not specified"),
15458                      fieldname, sect_offset_str (die->sect_off));
15459           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15460           TYPE_CPLUS_DYNAMIC (type) = 1;
15461         }
15462     }
15463 }
15464
15465 /* Create the vector of member function fields, and attach it to the type.  */
15466
15467 static void
15468 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15469                                  struct dwarf2_cu *cu)
15470 {
15471   if (cu->language == language_ada)
15472     error (_("unexpected member functions in Ada type"));
15473
15474   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15475   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15476     TYPE_ALLOC (type,
15477                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15478
15479   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15480     {
15481       struct fnfieldlist &nf = fip->fnfieldlists[i];
15482       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15483
15484       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15485       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15486       fn_flp->fn_fields = (struct fn_field *)
15487         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15488
15489       for (int k = 0; k < nf.fnfields.size (); ++k)
15490         fn_flp->fn_fields[k] = nf.fnfields[k];
15491     }
15492
15493   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15494 }
15495
15496 /* Returns non-zero if NAME is the name of a vtable member in CU's
15497    language, zero otherwise.  */
15498 static int
15499 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15500 {
15501   static const char vptr[] = "_vptr";
15502
15503   /* Look for the C++ form of the vtable.  */
15504   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15505     return 1;
15506
15507   return 0;
15508 }
15509
15510 /* GCC outputs unnamed structures that are really pointers to member
15511    functions, with the ABI-specified layout.  If TYPE describes
15512    such a structure, smash it into a member function type.
15513
15514    GCC shouldn't do this; it should just output pointer to member DIEs.
15515    This is GCC PR debug/28767.  */
15516
15517 static void
15518 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15519 {
15520   struct type *pfn_type, *self_type, *new_type;
15521
15522   /* Check for a structure with no name and two children.  */
15523   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15524     return;
15525
15526   /* Check for __pfn and __delta members.  */
15527   if (TYPE_FIELD_NAME (type, 0) == NULL
15528       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15529       || TYPE_FIELD_NAME (type, 1) == NULL
15530       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15531     return;
15532
15533   /* Find the type of the method.  */
15534   pfn_type = TYPE_FIELD_TYPE (type, 0);
15535   if (pfn_type == NULL
15536       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15537       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15538     return;
15539
15540   /* Look for the "this" argument.  */
15541   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15542   if (TYPE_NFIELDS (pfn_type) == 0
15543       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15544       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15545     return;
15546
15547   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15548   new_type = alloc_type (objfile);
15549   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15550                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15551                         TYPE_VARARGS (pfn_type));
15552   smash_to_methodptr_type (type, new_type);
15553 }
15554
15555 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15556    appropriate error checking and issuing complaints if there is a
15557    problem.  */
15558
15559 static ULONGEST
15560 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15561 {
15562   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15563
15564   if (attr == nullptr)
15565     return 0;
15566
15567   if (!attr_form_is_constant (attr))
15568     {
15569       complaint (_("DW_AT_alignment must have constant form"
15570                    " - DIE at %s [in module %s]"),
15571                  sect_offset_str (die->sect_off),
15572                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15573       return 0;
15574     }
15575
15576   ULONGEST align;
15577   if (attr->form == DW_FORM_sdata)
15578     {
15579       LONGEST val = DW_SND (attr);
15580       if (val < 0)
15581         {
15582           complaint (_("DW_AT_alignment value must not be negative"
15583                        " - DIE at %s [in module %s]"),
15584                      sect_offset_str (die->sect_off),
15585                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15586           return 0;
15587         }
15588       align = val;
15589     }
15590   else
15591     align = DW_UNSND (attr);
15592
15593   if (align == 0)
15594     {
15595       complaint (_("DW_AT_alignment value must not be zero"
15596                    " - DIE at %s [in module %s]"),
15597                  sect_offset_str (die->sect_off),
15598                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15599       return 0;
15600     }
15601   if ((align & (align - 1)) != 0)
15602     {
15603       complaint (_("DW_AT_alignment value must be a power of 2"
15604                    " - DIE at %s [in module %s]"),
15605                  sect_offset_str (die->sect_off),
15606                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15607       return 0;
15608     }
15609
15610   return align;
15611 }
15612
15613 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15614    the alignment for TYPE.  */
15615
15616 static void
15617 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15618                      struct type *type)
15619 {
15620   if (!set_type_align (type, get_alignment (cu, die)))
15621     complaint (_("DW_AT_alignment value too large"
15622                  " - DIE at %s [in module %s]"),
15623                sect_offset_str (die->sect_off),
15624                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15625 }
15626
15627 /* Called when we find the DIE that starts a structure or union scope
15628    (definition) to create a type for the structure or union.  Fill in
15629    the type's name and general properties; the members will not be
15630    processed until process_structure_scope.  A symbol table entry for
15631    the type will also not be done until process_structure_scope (assuming
15632    the type has a name).
15633
15634    NOTE: we need to call these functions regardless of whether or not the
15635    DIE has a DW_AT_name attribute, since it might be an anonymous
15636    structure or union.  This gets the type entered into our set of
15637    user defined types.  */
15638
15639 static struct type *
15640 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15641 {
15642   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15643   struct type *type;
15644   struct attribute *attr;
15645   const char *name;
15646
15647   /* If the definition of this type lives in .debug_types, read that type.
15648      Don't follow DW_AT_specification though, that will take us back up
15649      the chain and we want to go down.  */
15650   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15651   if (attr)
15652     {
15653       type = get_DW_AT_signature_type (die, attr, cu);
15654
15655       /* The type's CU may not be the same as CU.
15656          Ensure TYPE is recorded with CU in die_type_hash.  */
15657       return set_die_type (die, type, cu);
15658     }
15659
15660   type = alloc_type (objfile);
15661   INIT_CPLUS_SPECIFIC (type);
15662
15663   name = dwarf2_name (die, cu);
15664   if (name != NULL)
15665     {
15666       if (cu->language == language_cplus
15667           || cu->language == language_d
15668           || cu->language == language_rust)
15669         {
15670           const char *full_name = dwarf2_full_name (name, die, cu);
15671
15672           /* dwarf2_full_name might have already finished building the DIE's
15673              type.  If so, there is no need to continue.  */
15674           if (get_die_type (die, cu) != NULL)
15675             return get_die_type (die, cu);
15676
15677           TYPE_NAME (type) = full_name;
15678         }
15679       else
15680         {
15681           /* The name is already allocated along with this objfile, so
15682              we don't need to duplicate it for the type.  */
15683           TYPE_NAME (type) = name;
15684         }
15685     }
15686
15687   if (die->tag == DW_TAG_structure_type)
15688     {
15689       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15690     }
15691   else if (die->tag == DW_TAG_union_type)
15692     {
15693       TYPE_CODE (type) = TYPE_CODE_UNION;
15694     }
15695   else if (die->tag == DW_TAG_variant_part)
15696     {
15697       TYPE_CODE (type) = TYPE_CODE_UNION;
15698       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15699     }
15700   else
15701     {
15702       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15703     }
15704
15705   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15706     TYPE_DECLARED_CLASS (type) = 1;
15707
15708   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15709   if (attr)
15710     {
15711       if (attr_form_is_constant (attr))
15712         TYPE_LENGTH (type) = DW_UNSND (attr);
15713       else
15714         {
15715           /* For the moment, dynamic type sizes are not supported
15716              by GDB's struct type.  The actual size is determined
15717              on-demand when resolving the type of a given object,
15718              so set the type's length to zero for now.  Otherwise,
15719              we record an expression as the length, and that expression
15720              could lead to a very large value, which could eventually
15721              lead to us trying to allocate that much memory when creating
15722              a value of that type.  */
15723           TYPE_LENGTH (type) = 0;
15724         }
15725     }
15726   else
15727     {
15728       TYPE_LENGTH (type) = 0;
15729     }
15730
15731   maybe_set_alignment (cu, die, type);
15732
15733   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15734     {
15735       /* ICC<14 does not output the required DW_AT_declaration on
15736          incomplete types, but gives them a size of zero.  */
15737       TYPE_STUB (type) = 1;
15738     }
15739   else
15740     TYPE_STUB_SUPPORTED (type) = 1;
15741
15742   if (die_is_declaration (die, cu))
15743     TYPE_STUB (type) = 1;
15744   else if (attr == NULL && die->child == NULL
15745            && producer_is_realview (cu->producer))
15746     /* RealView does not output the required DW_AT_declaration
15747        on incomplete types.  */
15748     TYPE_STUB (type) = 1;
15749
15750   /* We need to add the type field to the die immediately so we don't
15751      infinitely recurse when dealing with pointers to the structure
15752      type within the structure itself.  */
15753   set_die_type (die, type, cu);
15754
15755   /* set_die_type should be already done.  */
15756   set_descriptive_type (type, die, cu);
15757
15758   return type;
15759 }
15760
15761 /* A helper for process_structure_scope that handles a single member
15762    DIE.  */
15763
15764 static void
15765 handle_struct_member_die (struct die_info *child_die, struct type *type,
15766                           struct field_info *fi,
15767                           std::vector<struct symbol *> *template_args,
15768                           struct dwarf2_cu *cu)
15769 {
15770   if (child_die->tag == DW_TAG_member
15771       || child_die->tag == DW_TAG_variable
15772       || child_die->tag == DW_TAG_variant_part)
15773     {
15774       /* NOTE: carlton/2002-11-05: A C++ static data member
15775          should be a DW_TAG_member that is a declaration, but
15776          all versions of G++ as of this writing (so through at
15777          least 3.2.1) incorrectly generate DW_TAG_variable
15778          tags for them instead.  */
15779       dwarf2_add_field (fi, child_die, cu);
15780     }
15781   else if (child_die->tag == DW_TAG_subprogram)
15782     {
15783       /* Rust doesn't have member functions in the C++ sense.
15784          However, it does emit ordinary functions as children
15785          of a struct DIE.  */
15786       if (cu->language == language_rust)
15787         read_func_scope (child_die, cu);
15788       else
15789         {
15790           /* C++ member function.  */
15791           dwarf2_add_member_fn (fi, child_die, type, cu);
15792         }
15793     }
15794   else if (child_die->tag == DW_TAG_inheritance)
15795     {
15796       /* C++ base class field.  */
15797       dwarf2_add_field (fi, child_die, cu);
15798     }
15799   else if (type_can_define_types (child_die))
15800     dwarf2_add_type_defn (fi, child_die, cu);
15801   else if (child_die->tag == DW_TAG_template_type_param
15802            || child_die->tag == DW_TAG_template_value_param)
15803     {
15804       struct symbol *arg = new_symbol (child_die, NULL, cu);
15805
15806       if (arg != NULL)
15807         template_args->push_back (arg);
15808     }
15809   else if (child_die->tag == DW_TAG_variant)
15810     {
15811       /* In a variant we want to get the discriminant and also add a
15812          field for our sole member child.  */
15813       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15814
15815       for (struct die_info *variant_child = child_die->child;
15816            variant_child != NULL;
15817            variant_child = sibling_die (variant_child))
15818         {
15819           if (variant_child->tag == DW_TAG_member)
15820             {
15821               handle_struct_member_die (variant_child, type, fi,
15822                                         template_args, cu);
15823               /* Only handle the one.  */
15824               break;
15825             }
15826         }
15827
15828       /* We don't handle this but we might as well report it if we see
15829          it.  */
15830       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15831           complaint (_("DW_AT_discr_list is not supported yet"
15832                        " - DIE at %s [in module %s]"),
15833                      sect_offset_str (child_die->sect_off),
15834                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15835
15836       /* The first field was just added, so we can stash the
15837          discriminant there.  */
15838       gdb_assert (!fi->fields.empty ());
15839       if (discr == NULL)
15840         fi->fields.back ().variant.default_branch = true;
15841       else
15842         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15843     }
15844 }
15845
15846 /* Finish creating a structure or union type, including filling in
15847    its members and creating a symbol for it.  */
15848
15849 static void
15850 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15851 {
15852   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15853   struct die_info *child_die;
15854   struct type *type;
15855
15856   type = get_die_type (die, cu);
15857   if (type == NULL)
15858     type = read_structure_type (die, cu);
15859
15860   /* When reading a DW_TAG_variant_part, we need to notice when we
15861      read the discriminant member, so we can record it later in the
15862      discriminant_info.  */
15863   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15864   sect_offset discr_offset;
15865
15866   if (is_variant_part)
15867     {
15868       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15869       if (discr == NULL)
15870         {
15871           /* Maybe it's a univariant form, an extension we support.
15872              In this case arrange not to check the offset.  */
15873           is_variant_part = false;
15874         }
15875       else if (attr_form_is_ref (discr))
15876         {
15877           struct dwarf2_cu *target_cu = cu;
15878           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15879
15880           discr_offset = target_die->sect_off;
15881         }
15882       else
15883         {
15884           complaint (_("DW_AT_discr does not have DIE reference form"
15885                        " - DIE at %s [in module %s]"),
15886                      sect_offset_str (die->sect_off),
15887                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15888           is_variant_part = false;
15889         }
15890     }
15891
15892   if (die->child != NULL && ! die_is_declaration (die, cu))
15893     {
15894       struct field_info fi;
15895       std::vector<struct symbol *> template_args;
15896
15897       child_die = die->child;
15898
15899       while (child_die && child_die->tag)
15900         {
15901           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15902
15903           if (is_variant_part && discr_offset == child_die->sect_off)
15904             fi.fields.back ().variant.is_discriminant = true;
15905
15906           child_die = sibling_die (child_die);
15907         }
15908
15909       /* Attach template arguments to type.  */
15910       if (!template_args.empty ())
15911         {
15912           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15913           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15914           TYPE_TEMPLATE_ARGUMENTS (type)
15915             = XOBNEWVEC (&objfile->objfile_obstack,
15916                          struct symbol *,
15917                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15918           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15919                   template_args.data (),
15920                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15921                    * sizeof (struct symbol *)));
15922         }
15923
15924       /* Attach fields and member functions to the type.  */
15925       if (fi.nfields)
15926         dwarf2_attach_fields_to_type (&fi, type, cu);
15927       if (!fi.fnfieldlists.empty ())
15928         {
15929           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15930
15931           /* Get the type which refers to the base class (possibly this
15932              class itself) which contains the vtable pointer for the current
15933              class from the DW_AT_containing_type attribute.  This use of
15934              DW_AT_containing_type is a GNU extension.  */
15935
15936           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15937             {
15938               struct type *t = die_containing_type (die, cu);
15939
15940               set_type_vptr_basetype (type, t);
15941               if (type == t)
15942                 {
15943                   int i;
15944
15945                   /* Our own class provides vtbl ptr.  */
15946                   for (i = TYPE_NFIELDS (t) - 1;
15947                        i >= TYPE_N_BASECLASSES (t);
15948                        --i)
15949                     {
15950                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15951
15952                       if (is_vtable_name (fieldname, cu))
15953                         {
15954                           set_type_vptr_fieldno (type, i);
15955                           break;
15956                         }
15957                     }
15958
15959                   /* Complain if virtual function table field not found.  */
15960                   if (i < TYPE_N_BASECLASSES (t))
15961                     complaint (_("virtual function table pointer "
15962                                  "not found when defining class '%s'"),
15963                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
15964                 }
15965               else
15966                 {
15967                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15968                 }
15969             }
15970           else if (cu->producer
15971                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15972             {
15973               /* The IBM XLC compiler does not provide direct indication
15974                  of the containing type, but the vtable pointer is
15975                  always named __vfp.  */
15976
15977               int i;
15978
15979               for (i = TYPE_NFIELDS (type) - 1;
15980                    i >= TYPE_N_BASECLASSES (type);
15981                    --i)
15982                 {
15983                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15984                     {
15985                       set_type_vptr_fieldno (type, i);
15986                       set_type_vptr_basetype (type, type);
15987                       break;
15988                     }
15989                 }
15990             }
15991         }
15992
15993       /* Copy fi.typedef_field_list linked list elements content into the
15994          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15995       if (!fi.typedef_field_list.empty ())
15996         {
15997           int count = fi.typedef_field_list.size ();
15998
15999           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16000           TYPE_TYPEDEF_FIELD_ARRAY (type)
16001             = ((struct decl_field *)
16002                TYPE_ALLOC (type,
16003                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16004           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16005
16006           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16007             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16008         }
16009
16010       /* Copy fi.nested_types_list linked list elements content into the
16011          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16012       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16013         {
16014           int count = fi.nested_types_list.size ();
16015
16016           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16017           TYPE_NESTED_TYPES_ARRAY (type)
16018             = ((struct decl_field *)
16019                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16020           TYPE_NESTED_TYPES_COUNT (type) = count;
16021
16022           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16023             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16024         }
16025     }
16026
16027   quirk_gcc_member_function_pointer (type, objfile);
16028   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16029     cu->rust_unions.push_back (type);
16030
16031   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16032      snapshots) has been known to create a die giving a declaration
16033      for a class that has, as a child, a die giving a definition for a
16034      nested class.  So we have to process our children even if the
16035      current die is a declaration.  Normally, of course, a declaration
16036      won't have any children at all.  */
16037
16038   child_die = die->child;
16039
16040   while (child_die != NULL && child_die->tag)
16041     {
16042       if (child_die->tag == DW_TAG_member
16043           || child_die->tag == DW_TAG_variable
16044           || child_die->tag == DW_TAG_inheritance
16045           || child_die->tag == DW_TAG_template_value_param
16046           || child_die->tag == DW_TAG_template_type_param)
16047         {
16048           /* Do nothing.  */
16049         }
16050       else
16051         process_die (child_die, cu);
16052
16053       child_die = sibling_die (child_die);
16054     }
16055
16056   /* Do not consider external references.  According to the DWARF standard,
16057      these DIEs are identified by the fact that they have no byte_size
16058      attribute, and a declaration attribute.  */
16059   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16060       || !die_is_declaration (die, cu))
16061     new_symbol (die, type, cu);
16062 }
16063
16064 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16065    update TYPE using some information only available in DIE's children.  */
16066
16067 static void
16068 update_enumeration_type_from_children (struct die_info *die,
16069                                        struct type *type,
16070                                        struct dwarf2_cu *cu)
16071 {
16072   struct die_info *child_die;
16073   int unsigned_enum = 1;
16074   int flag_enum = 1;
16075   ULONGEST mask = 0;
16076
16077   auto_obstack obstack;
16078
16079   for (child_die = die->child;
16080        child_die != NULL && child_die->tag;
16081        child_die = sibling_die (child_die))
16082     {
16083       struct attribute *attr;
16084       LONGEST value;
16085       const gdb_byte *bytes;
16086       struct dwarf2_locexpr_baton *baton;
16087       const char *name;
16088
16089       if (child_die->tag != DW_TAG_enumerator)
16090         continue;
16091
16092       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16093       if (attr == NULL)
16094         continue;
16095
16096       name = dwarf2_name (child_die, cu);
16097       if (name == NULL)
16098         name = "<anonymous enumerator>";
16099
16100       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16101                                &value, &bytes, &baton);
16102       if (value < 0)
16103         {
16104           unsigned_enum = 0;
16105           flag_enum = 0;
16106         }
16107       else if ((mask & value) != 0)
16108         flag_enum = 0;
16109       else
16110         mask |= value;
16111
16112       /* If we already know that the enum type is neither unsigned, nor
16113          a flag type, no need to look at the rest of the enumerates.  */
16114       if (!unsigned_enum && !flag_enum)
16115         break;
16116     }
16117
16118   if (unsigned_enum)
16119     TYPE_UNSIGNED (type) = 1;
16120   if (flag_enum)
16121     TYPE_FLAG_ENUM (type) = 1;
16122 }
16123
16124 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16125    complete the type's fields yet, or create any symbols.  */
16126
16127 static struct type *
16128 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16129 {
16130   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16131   struct type *type;
16132   struct attribute *attr;
16133   const char *name;
16134
16135   /* If the definition of this type lives in .debug_types, read that type.
16136      Don't follow DW_AT_specification though, that will take us back up
16137      the chain and we want to go down.  */
16138   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16139   if (attr)
16140     {
16141       type = get_DW_AT_signature_type (die, attr, cu);
16142
16143       /* The type's CU may not be the same as CU.
16144          Ensure TYPE is recorded with CU in die_type_hash.  */
16145       return set_die_type (die, type, cu);
16146     }
16147
16148   type = alloc_type (objfile);
16149
16150   TYPE_CODE (type) = TYPE_CODE_ENUM;
16151   name = dwarf2_full_name (NULL, die, cu);
16152   if (name != NULL)
16153     TYPE_NAME (type) = name;
16154
16155   attr = dwarf2_attr (die, DW_AT_type, cu);
16156   if (attr != NULL)
16157     {
16158       struct type *underlying_type = die_type (die, cu);
16159
16160       TYPE_TARGET_TYPE (type) = underlying_type;
16161     }
16162
16163   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16164   if (attr)
16165     {
16166       TYPE_LENGTH (type) = DW_UNSND (attr);
16167     }
16168   else
16169     {
16170       TYPE_LENGTH (type) = 0;
16171     }
16172
16173   maybe_set_alignment (cu, die, type);
16174
16175   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16176      declared as private in the package spec, and then defined only
16177      inside the package body.  Such types are known as Taft Amendment
16178      Types.  When another package uses such a type, an incomplete DIE
16179      may be generated by the compiler.  */
16180   if (die_is_declaration (die, cu))
16181     TYPE_STUB (type) = 1;
16182
16183   /* Finish the creation of this type by using the enum's children.
16184      We must call this even when the underlying type has been provided
16185      so that we can determine if we're looking at a "flag" enum.  */
16186   update_enumeration_type_from_children (die, type, cu);
16187
16188   /* If this type has an underlying type that is not a stub, then we
16189      may use its attributes.  We always use the "unsigned" attribute
16190      in this situation, because ordinarily we guess whether the type
16191      is unsigned -- but the guess can be wrong and the underlying type
16192      can tell us the reality.  However, we defer to a local size
16193      attribute if one exists, because this lets the compiler override
16194      the underlying type if needed.  */
16195   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16196     {
16197       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16198       if (TYPE_LENGTH (type) == 0)
16199         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16200       if (TYPE_RAW_ALIGN (type) == 0
16201           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16202         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16203     }
16204
16205   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16206
16207   return set_die_type (die, type, cu);
16208 }
16209
16210 /* Given a pointer to a die which begins an enumeration, process all
16211    the dies that define the members of the enumeration, and create the
16212    symbol for the enumeration type.
16213
16214    NOTE: We reverse the order of the element list.  */
16215
16216 static void
16217 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16218 {
16219   struct type *this_type;
16220
16221   this_type = get_die_type (die, cu);
16222   if (this_type == NULL)
16223     this_type = read_enumeration_type (die, cu);
16224
16225   if (die->child != NULL)
16226     {
16227       struct die_info *child_die;
16228       struct symbol *sym;
16229       struct field *fields = NULL;
16230       int num_fields = 0;
16231       const char *name;
16232
16233       child_die = die->child;
16234       while (child_die && child_die->tag)
16235         {
16236           if (child_die->tag != DW_TAG_enumerator)
16237             {
16238               process_die (child_die, cu);
16239             }
16240           else
16241             {
16242               name = dwarf2_name (child_die, cu);
16243               if (name)
16244                 {
16245                   sym = new_symbol (child_die, this_type, cu);
16246
16247                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16248                     {
16249                       fields = (struct field *)
16250                         xrealloc (fields,
16251                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16252                                   * sizeof (struct field));
16253                     }
16254
16255                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16256                   FIELD_TYPE (fields[num_fields]) = NULL;
16257                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16258                   FIELD_BITSIZE (fields[num_fields]) = 0;
16259
16260                   num_fields++;
16261                 }
16262             }
16263
16264           child_die = sibling_die (child_die);
16265         }
16266
16267       if (num_fields)
16268         {
16269           TYPE_NFIELDS (this_type) = num_fields;
16270           TYPE_FIELDS (this_type) = (struct field *)
16271             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16272           memcpy (TYPE_FIELDS (this_type), fields,
16273                   sizeof (struct field) * num_fields);
16274           xfree (fields);
16275         }
16276     }
16277
16278   /* If we are reading an enum from a .debug_types unit, and the enum
16279      is a declaration, and the enum is not the signatured type in the
16280      unit, then we do not want to add a symbol for it.  Adding a
16281      symbol would in some cases obscure the true definition of the
16282      enum, giving users an incomplete type when the definition is
16283      actually available.  Note that we do not want to do this for all
16284      enums which are just declarations, because C++0x allows forward
16285      enum declarations.  */
16286   if (cu->per_cu->is_debug_types
16287       && die_is_declaration (die, cu))
16288     {
16289       struct signatured_type *sig_type;
16290
16291       sig_type = (struct signatured_type *) cu->per_cu;
16292       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16293       if (sig_type->type_offset_in_section != die->sect_off)
16294         return;
16295     }
16296
16297   new_symbol (die, this_type, cu);
16298 }
16299
16300 /* Extract all information from a DW_TAG_array_type DIE and put it in
16301    the DIE's type field.  For now, this only handles one dimensional
16302    arrays.  */
16303
16304 static struct type *
16305 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16306 {
16307   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16308   struct die_info *child_die;
16309   struct type *type;
16310   struct type *element_type, *range_type, *index_type;
16311   struct attribute *attr;
16312   const char *name;
16313   struct dynamic_prop *byte_stride_prop = NULL;
16314   unsigned int bit_stride = 0;
16315
16316   element_type = die_type (die, cu);
16317
16318   /* The die_type call above may have already set the type for this DIE.  */
16319   type = get_die_type (die, cu);
16320   if (type)
16321     return type;
16322
16323   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16324   if (attr != NULL)
16325     {
16326       int stride_ok;
16327
16328       byte_stride_prop
16329         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16330       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16331       if (!stride_ok)
16332         {
16333           complaint (_("unable to read array DW_AT_byte_stride "
16334                        " - DIE at %s [in module %s]"),
16335                      sect_offset_str (die->sect_off),
16336                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16337           /* Ignore this attribute.  We will likely not be able to print
16338              arrays of this type correctly, but there is little we can do
16339              to help if we cannot read the attribute's value.  */
16340           byte_stride_prop = NULL;
16341         }
16342     }
16343
16344   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16345   if (attr != NULL)
16346     bit_stride = DW_UNSND (attr);
16347
16348   /* Irix 6.2 native cc creates array types without children for
16349      arrays with unspecified length.  */
16350   if (die->child == NULL)
16351     {
16352       index_type = objfile_type (objfile)->builtin_int;
16353       range_type = create_static_range_type (NULL, index_type, 0, -1);
16354       type = create_array_type_with_stride (NULL, element_type, range_type,
16355                                             byte_stride_prop, bit_stride);
16356       return set_die_type (die, type, cu);
16357     }
16358
16359   std::vector<struct type *> range_types;
16360   child_die = die->child;
16361   while (child_die && child_die->tag)
16362     {
16363       if (child_die->tag == DW_TAG_subrange_type)
16364         {
16365           struct type *child_type = read_type_die (child_die, cu);
16366
16367           if (child_type != NULL)
16368             {
16369               /* The range type was succesfully read.  Save it for the
16370                  array type creation.  */
16371               range_types.push_back (child_type);
16372             }
16373         }
16374       child_die = sibling_die (child_die);
16375     }
16376
16377   /* Dwarf2 dimensions are output from left to right, create the
16378      necessary array types in backwards order.  */
16379
16380   type = element_type;
16381
16382   if (read_array_order (die, cu) == DW_ORD_col_major)
16383     {
16384       int i = 0;
16385
16386       while (i < range_types.size ())
16387         type = create_array_type_with_stride (NULL, type, range_types[i++],
16388                                               byte_stride_prop, bit_stride);
16389     }
16390   else
16391     {
16392       size_t ndim = range_types.size ();
16393       while (ndim-- > 0)
16394         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16395                                               byte_stride_prop, bit_stride);
16396     }
16397
16398   /* Understand Dwarf2 support for vector types (like they occur on
16399      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16400      array type.  This is not part of the Dwarf2/3 standard yet, but a
16401      custom vendor extension.  The main difference between a regular
16402      array and the vector variant is that vectors are passed by value
16403      to functions.  */
16404   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16405   if (attr)
16406     make_vector_type (type);
16407
16408   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16409      implementation may choose to implement triple vectors using this
16410      attribute.  */
16411   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16412   if (attr)
16413     {
16414       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16415         TYPE_LENGTH (type) = DW_UNSND (attr);
16416       else
16417         complaint (_("DW_AT_byte_size for array type smaller "
16418                      "than the total size of elements"));
16419     }
16420
16421   name = dwarf2_name (die, cu);
16422   if (name)
16423     TYPE_NAME (type) = name;
16424
16425   maybe_set_alignment (cu, die, type);
16426
16427   /* Install the type in the die.  */
16428   set_die_type (die, type, cu);
16429
16430   /* set_die_type should be already done.  */
16431   set_descriptive_type (type, die, cu);
16432
16433   return type;
16434 }
16435
16436 static enum dwarf_array_dim_ordering
16437 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16438 {
16439   struct attribute *attr;
16440
16441   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16442
16443   if (attr)
16444     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16445
16446   /* GNU F77 is a special case, as at 08/2004 array type info is the
16447      opposite order to the dwarf2 specification, but data is still
16448      laid out as per normal fortran.
16449
16450      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16451      version checking.  */
16452
16453   if (cu->language == language_fortran
16454       && cu->producer && strstr (cu->producer, "GNU F77"))
16455     {
16456       return DW_ORD_row_major;
16457     }
16458
16459   switch (cu->language_defn->la_array_ordering)
16460     {
16461     case array_column_major:
16462       return DW_ORD_col_major;
16463     case array_row_major:
16464     default:
16465       return DW_ORD_row_major;
16466     };
16467 }
16468
16469 /* Extract all information from a DW_TAG_set_type DIE and put it in
16470    the DIE's type field.  */
16471
16472 static struct type *
16473 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16474 {
16475   struct type *domain_type, *set_type;
16476   struct attribute *attr;
16477
16478   domain_type = die_type (die, cu);
16479
16480   /* The die_type call above may have already set the type for this DIE.  */
16481   set_type = get_die_type (die, cu);
16482   if (set_type)
16483     return set_type;
16484
16485   set_type = create_set_type (NULL, domain_type);
16486
16487   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16488   if (attr)
16489     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16490
16491   maybe_set_alignment (cu, die, set_type);
16492
16493   return set_die_type (die, set_type, cu);
16494 }
16495
16496 /* A helper for read_common_block that creates a locexpr baton.
16497    SYM is the symbol which we are marking as computed.
16498    COMMON_DIE is the DIE for the common block.
16499    COMMON_LOC is the location expression attribute for the common
16500    block itself.
16501    MEMBER_LOC is the location expression attribute for the particular
16502    member of the common block that we are processing.
16503    CU is the CU from which the above come.  */
16504
16505 static void
16506 mark_common_block_symbol_computed (struct symbol *sym,
16507                                    struct die_info *common_die,
16508                                    struct attribute *common_loc,
16509                                    struct attribute *member_loc,
16510                                    struct dwarf2_cu *cu)
16511 {
16512   struct dwarf2_per_objfile *dwarf2_per_objfile
16513     = cu->per_cu->dwarf2_per_objfile;
16514   struct objfile *objfile = dwarf2_per_objfile->objfile;
16515   struct dwarf2_locexpr_baton *baton;
16516   gdb_byte *ptr;
16517   unsigned int cu_off;
16518   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16519   LONGEST offset = 0;
16520
16521   gdb_assert (common_loc && member_loc);
16522   gdb_assert (attr_form_is_block (common_loc));
16523   gdb_assert (attr_form_is_block (member_loc)
16524               || attr_form_is_constant (member_loc));
16525
16526   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16527   baton->per_cu = cu->per_cu;
16528   gdb_assert (baton->per_cu);
16529
16530   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16531
16532   if (attr_form_is_constant (member_loc))
16533     {
16534       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16535       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16536     }
16537   else
16538     baton->size += DW_BLOCK (member_loc)->size;
16539
16540   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16541   baton->data = ptr;
16542
16543   *ptr++ = DW_OP_call4;
16544   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16545   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16546   ptr += 4;
16547
16548   if (attr_form_is_constant (member_loc))
16549     {
16550       *ptr++ = DW_OP_addr;
16551       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16552       ptr += cu->header.addr_size;
16553     }
16554   else
16555     {
16556       /* We have to copy the data here, because DW_OP_call4 will only
16557          use a DW_AT_location attribute.  */
16558       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16559       ptr += DW_BLOCK (member_loc)->size;
16560     }
16561
16562   *ptr++ = DW_OP_plus;
16563   gdb_assert (ptr - baton->data == baton->size);
16564
16565   SYMBOL_LOCATION_BATON (sym) = baton;
16566   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16567 }
16568
16569 /* Create appropriate locally-scoped variables for all the
16570    DW_TAG_common_block entries.  Also create a struct common_block
16571    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16572    is used to sepate the common blocks name namespace from regular
16573    variable names.  */
16574
16575 static void
16576 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16577 {
16578   struct attribute *attr;
16579
16580   attr = dwarf2_attr (die, DW_AT_location, cu);
16581   if (attr)
16582     {
16583       /* Support the .debug_loc offsets.  */
16584       if (attr_form_is_block (attr))
16585         {
16586           /* Ok.  */
16587         }
16588       else if (attr_form_is_section_offset (attr))
16589         {
16590           dwarf2_complex_location_expr_complaint ();
16591           attr = NULL;
16592         }
16593       else
16594         {
16595           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16596                                                  "common block member");
16597           attr = NULL;
16598         }
16599     }
16600
16601   if (die->child != NULL)
16602     {
16603       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16604       struct die_info *child_die;
16605       size_t n_entries = 0, size;
16606       struct common_block *common_block;
16607       struct symbol *sym;
16608
16609       for (child_die = die->child;
16610            child_die && child_die->tag;
16611            child_die = sibling_die (child_die))
16612         ++n_entries;
16613
16614       size = (sizeof (struct common_block)
16615               + (n_entries - 1) * sizeof (struct symbol *));
16616       common_block
16617         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16618                                                  size);
16619       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16620       common_block->n_entries = 0;
16621
16622       for (child_die = die->child;
16623            child_die && child_die->tag;
16624            child_die = sibling_die (child_die))
16625         {
16626           /* Create the symbol in the DW_TAG_common_block block in the current
16627              symbol scope.  */
16628           sym = new_symbol (child_die, NULL, cu);
16629           if (sym != NULL)
16630             {
16631               struct attribute *member_loc;
16632
16633               common_block->contents[common_block->n_entries++] = sym;
16634
16635               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16636                                         cu);
16637               if (member_loc)
16638                 {
16639                   /* GDB has handled this for a long time, but it is
16640                      not specified by DWARF.  It seems to have been
16641                      emitted by gfortran at least as recently as:
16642                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16643                   complaint (_("Variable in common block has "
16644                                "DW_AT_data_member_location "
16645                                "- DIE at %s [in module %s]"),
16646                                sect_offset_str (child_die->sect_off),
16647                              objfile_name (objfile));
16648
16649                   if (attr_form_is_section_offset (member_loc))
16650                     dwarf2_complex_location_expr_complaint ();
16651                   else if (attr_form_is_constant (member_loc)
16652                            || attr_form_is_block (member_loc))
16653                     {
16654                       if (attr)
16655                         mark_common_block_symbol_computed (sym, die, attr,
16656                                                            member_loc, cu);
16657                     }
16658                   else
16659                     dwarf2_complex_location_expr_complaint ();
16660                 }
16661             }
16662         }
16663
16664       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16665       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16666     }
16667 }
16668
16669 /* Create a type for a C++ namespace.  */
16670
16671 static struct type *
16672 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16673 {
16674   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16675   const char *previous_prefix, *name;
16676   int is_anonymous;
16677   struct type *type;
16678
16679   /* For extensions, reuse the type of the original namespace.  */
16680   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16681     {
16682       struct die_info *ext_die;
16683       struct dwarf2_cu *ext_cu = cu;
16684
16685       ext_die = dwarf2_extension (die, &ext_cu);
16686       type = read_type_die (ext_die, ext_cu);
16687
16688       /* EXT_CU may not be the same as CU.
16689          Ensure TYPE is recorded with CU in die_type_hash.  */
16690       return set_die_type (die, type, cu);
16691     }
16692
16693   name = namespace_name (die, &is_anonymous, cu);
16694
16695   /* Now build the name of the current namespace.  */
16696
16697   previous_prefix = determine_prefix (die, cu);
16698   if (previous_prefix[0] != '\0')
16699     name = typename_concat (&objfile->objfile_obstack,
16700                             previous_prefix, name, 0, cu);
16701
16702   /* Create the type.  */
16703   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16704
16705   return set_die_type (die, type, cu);
16706 }
16707
16708 /* Read a namespace scope.  */
16709
16710 static void
16711 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16712 {
16713   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16714   int is_anonymous;
16715
16716   /* Add a symbol associated to this if we haven't seen the namespace
16717      before.  Also, add a using directive if it's an anonymous
16718      namespace.  */
16719
16720   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16721     {
16722       struct type *type;
16723
16724       type = read_type_die (die, cu);
16725       new_symbol (die, type, cu);
16726
16727       namespace_name (die, &is_anonymous, cu);
16728       if (is_anonymous)
16729         {
16730           const char *previous_prefix = determine_prefix (die, cu);
16731
16732           std::vector<const char *> excludes;
16733           add_using_directive (using_directives (cu),
16734                                previous_prefix, TYPE_NAME (type), NULL,
16735                                NULL, excludes, 0, &objfile->objfile_obstack);
16736         }
16737     }
16738
16739   if (die->child != NULL)
16740     {
16741       struct die_info *child_die = die->child;
16742
16743       while (child_die && child_die->tag)
16744         {
16745           process_die (child_die, cu);
16746           child_die = sibling_die (child_die);
16747         }
16748     }
16749 }
16750
16751 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16752    imported module.  Still we need that type as local Fortran "use ... only"
16753    declaration imports depend on the created type in determine_prefix.  */
16754
16755 static struct type *
16756 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16757 {
16758   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16759   const char *module_name;
16760   struct type *type;
16761
16762   module_name = dwarf2_name (die, cu);
16763   if (!module_name)
16764     complaint (_("DW_TAG_module has no name, offset %s"),
16765                sect_offset_str (die->sect_off));
16766   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16767
16768   return set_die_type (die, type, cu);
16769 }
16770
16771 /* Read a Fortran module.  */
16772
16773 static void
16774 read_module (struct die_info *die, struct dwarf2_cu *cu)
16775 {
16776   struct die_info *child_die = die->child;
16777   struct type *type;
16778
16779   type = read_type_die (die, cu);
16780   new_symbol (die, type, cu);
16781
16782   while (child_die && child_die->tag)
16783     {
16784       process_die (child_die, cu);
16785       child_die = sibling_die (child_die);
16786     }
16787 }
16788
16789 /* Return the name of the namespace represented by DIE.  Set
16790    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16791    namespace.  */
16792
16793 static const char *
16794 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16795 {
16796   struct die_info *current_die;
16797   const char *name = NULL;
16798
16799   /* Loop through the extensions until we find a name.  */
16800
16801   for (current_die = die;
16802        current_die != NULL;
16803        current_die = dwarf2_extension (die, &cu))
16804     {
16805       /* We don't use dwarf2_name here so that we can detect the absence
16806          of a name -> anonymous namespace.  */
16807       name = dwarf2_string_attr (die, DW_AT_name, cu);
16808
16809       if (name != NULL)
16810         break;
16811     }
16812
16813   /* Is it an anonymous namespace?  */
16814
16815   *is_anonymous = (name == NULL);
16816   if (*is_anonymous)
16817     name = CP_ANONYMOUS_NAMESPACE_STR;
16818
16819   return name;
16820 }
16821
16822 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16823    the user defined type vector.  */
16824
16825 static struct type *
16826 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16827 {
16828   struct gdbarch *gdbarch
16829     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16830   struct comp_unit_head *cu_header = &cu->header;
16831   struct type *type;
16832   struct attribute *attr_byte_size;
16833   struct attribute *attr_address_class;
16834   int byte_size, addr_class;
16835   struct type *target_type;
16836
16837   target_type = die_type (die, cu);
16838
16839   /* The die_type call above may have already set the type for this DIE.  */
16840   type = get_die_type (die, cu);
16841   if (type)
16842     return type;
16843
16844   type = lookup_pointer_type (target_type);
16845
16846   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16847   if (attr_byte_size)
16848     byte_size = DW_UNSND (attr_byte_size);
16849   else
16850     byte_size = cu_header->addr_size;
16851
16852   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16853   if (attr_address_class)
16854     addr_class = DW_UNSND (attr_address_class);
16855   else
16856     addr_class = DW_ADDR_none;
16857
16858   ULONGEST alignment = get_alignment (cu, die);
16859
16860   /* If the pointer size, alignment, or address class is different
16861      than the default, create a type variant marked as such and set
16862      the length accordingly.  */
16863   if (TYPE_LENGTH (type) != byte_size
16864       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16865           && alignment != TYPE_RAW_ALIGN (type))
16866       || addr_class != DW_ADDR_none)
16867     {
16868       if (gdbarch_address_class_type_flags_p (gdbarch))
16869         {
16870           int type_flags;
16871
16872           type_flags = gdbarch_address_class_type_flags
16873                          (gdbarch, byte_size, addr_class);
16874           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16875                       == 0);
16876           type = make_type_with_address_space (type, type_flags);
16877         }
16878       else if (TYPE_LENGTH (type) != byte_size)
16879         {
16880           complaint (_("invalid pointer size %d"), byte_size);
16881         }
16882       else if (TYPE_RAW_ALIGN (type) != alignment)
16883         {
16884           complaint (_("Invalid DW_AT_alignment"
16885                        " - DIE at %s [in module %s]"),
16886                      sect_offset_str (die->sect_off),
16887                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16888         }
16889       else
16890         {
16891           /* Should we also complain about unhandled address classes?  */
16892         }
16893     }
16894
16895   TYPE_LENGTH (type) = byte_size;
16896   set_type_align (type, alignment);
16897   return set_die_type (die, type, cu);
16898 }
16899
16900 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16901    the user defined type vector.  */
16902
16903 static struct type *
16904 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16905 {
16906   struct type *type;
16907   struct type *to_type;
16908   struct type *domain;
16909
16910   to_type = die_type (die, cu);
16911   domain = die_containing_type (die, cu);
16912
16913   /* The calls above may have already set the type for this DIE.  */
16914   type = get_die_type (die, cu);
16915   if (type)
16916     return type;
16917
16918   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16919     type = lookup_methodptr_type (to_type);
16920   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16921     {
16922       struct type *new_type
16923         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16924
16925       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16926                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16927                             TYPE_VARARGS (to_type));
16928       type = lookup_methodptr_type (new_type);
16929     }
16930   else
16931     type = lookup_memberptr_type (to_type, domain);
16932
16933   return set_die_type (die, type, cu);
16934 }
16935
16936 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16937    the user defined type vector.  */
16938
16939 static struct type *
16940 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16941                           enum type_code refcode)
16942 {
16943   struct comp_unit_head *cu_header = &cu->header;
16944   struct type *type, *target_type;
16945   struct attribute *attr;
16946
16947   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16948
16949   target_type = die_type (die, cu);
16950
16951   /* The die_type call above may have already set the type for this DIE.  */
16952   type = get_die_type (die, cu);
16953   if (type)
16954     return type;
16955
16956   type = lookup_reference_type (target_type, refcode);
16957   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16958   if (attr)
16959     {
16960       TYPE_LENGTH (type) = DW_UNSND (attr);
16961     }
16962   else
16963     {
16964       TYPE_LENGTH (type) = cu_header->addr_size;
16965     }
16966   maybe_set_alignment (cu, die, type);
16967   return set_die_type (die, type, cu);
16968 }
16969
16970 /* Add the given cv-qualifiers to the element type of the array.  GCC
16971    outputs DWARF type qualifiers that apply to an array, not the
16972    element type.  But GDB relies on the array element type to carry
16973    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16974    specification.  */
16975
16976 static struct type *
16977 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16978                    struct type *base_type, int cnst, int voltl)
16979 {
16980   struct type *el_type, *inner_array;
16981
16982   base_type = copy_type (base_type);
16983   inner_array = base_type;
16984
16985   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16986     {
16987       TYPE_TARGET_TYPE (inner_array) =
16988         copy_type (TYPE_TARGET_TYPE (inner_array));
16989       inner_array = TYPE_TARGET_TYPE (inner_array);
16990     }
16991
16992   el_type = TYPE_TARGET_TYPE (inner_array);
16993   cnst |= TYPE_CONST (el_type);
16994   voltl |= TYPE_VOLATILE (el_type);
16995   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16996
16997   return set_die_type (die, base_type, cu);
16998 }
16999
17000 static struct type *
17001 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17002 {
17003   struct type *base_type, *cv_type;
17004
17005   base_type = die_type (die, cu);
17006
17007   /* The die_type call above may have already set the type for this DIE.  */
17008   cv_type = get_die_type (die, cu);
17009   if (cv_type)
17010     return cv_type;
17011
17012   /* In case the const qualifier is applied to an array type, the element type
17013      is so qualified, not the array type (section 6.7.3 of C99).  */
17014   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17015     return add_array_cv_type (die, cu, base_type, 1, 0);
17016
17017   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17018   return set_die_type (die, cv_type, cu);
17019 }
17020
17021 static struct type *
17022 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17023 {
17024   struct type *base_type, *cv_type;
17025
17026   base_type = die_type (die, cu);
17027
17028   /* The die_type call above may have already set the type for this DIE.  */
17029   cv_type = get_die_type (die, cu);
17030   if (cv_type)
17031     return cv_type;
17032
17033   /* In case the volatile qualifier is applied to an array type, the
17034      element type is so qualified, not the array type (section 6.7.3
17035      of C99).  */
17036   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17037     return add_array_cv_type (die, cu, base_type, 0, 1);
17038
17039   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17040   return set_die_type (die, cv_type, cu);
17041 }
17042
17043 /* Handle DW_TAG_restrict_type.  */
17044
17045 static struct type *
17046 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17047 {
17048   struct type *base_type, *cv_type;
17049
17050   base_type = die_type (die, cu);
17051
17052   /* The die_type call above may have already set the type for this DIE.  */
17053   cv_type = get_die_type (die, cu);
17054   if (cv_type)
17055     return cv_type;
17056
17057   cv_type = make_restrict_type (base_type);
17058   return set_die_type (die, cv_type, cu);
17059 }
17060
17061 /* Handle DW_TAG_atomic_type.  */
17062
17063 static struct type *
17064 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17065 {
17066   struct type *base_type, *cv_type;
17067
17068   base_type = die_type (die, cu);
17069
17070   /* The die_type call above may have already set the type for this DIE.  */
17071   cv_type = get_die_type (die, cu);
17072   if (cv_type)
17073     return cv_type;
17074
17075   cv_type = make_atomic_type (base_type);
17076   return set_die_type (die, cv_type, cu);
17077 }
17078
17079 /* Extract all information from a DW_TAG_string_type DIE and add to
17080    the user defined type vector.  It isn't really a user defined type,
17081    but it behaves like one, with other DIE's using an AT_user_def_type
17082    attribute to reference it.  */
17083
17084 static struct type *
17085 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17086 {
17087   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17088   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17089   struct type *type, *range_type, *index_type, *char_type;
17090   struct attribute *attr;
17091   unsigned int length;
17092
17093   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17094   if (attr)
17095     {
17096       length = DW_UNSND (attr);
17097     }
17098   else
17099     {
17100       /* Check for the DW_AT_byte_size attribute.  */
17101       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17102       if (attr)
17103         {
17104           length = DW_UNSND (attr);
17105         }
17106       else
17107         {
17108           length = 1;
17109         }
17110     }
17111
17112   index_type = objfile_type (objfile)->builtin_int;
17113   range_type = create_static_range_type (NULL, index_type, 1, length);
17114   char_type = language_string_char_type (cu->language_defn, gdbarch);
17115   type = create_string_type (NULL, char_type, range_type);
17116
17117   return set_die_type (die, type, cu);
17118 }
17119
17120 /* Assuming that DIE corresponds to a function, returns nonzero
17121    if the function is prototyped.  */
17122
17123 static int
17124 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17125 {
17126   struct attribute *attr;
17127
17128   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17129   if (attr && (DW_UNSND (attr) != 0))
17130     return 1;
17131
17132   /* The DWARF standard implies that the DW_AT_prototyped attribute
17133      is only meaninful for C, but the concept also extends to other
17134      languages that allow unprototyped functions (Eg: Objective C).
17135      For all other languages, assume that functions are always
17136      prototyped.  */
17137   if (cu->language != language_c
17138       && cu->language != language_objc
17139       && cu->language != language_opencl)
17140     return 1;
17141
17142   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17143      prototyped and unprototyped functions; default to prototyped,
17144      since that is more common in modern code (and RealView warns
17145      about unprototyped functions).  */
17146   if (producer_is_realview (cu->producer))
17147     return 1;
17148
17149   return 0;
17150 }
17151
17152 /* Handle DIES due to C code like:
17153
17154    struct foo
17155    {
17156    int (*funcp)(int a, long l);
17157    int b;
17158    };
17159
17160    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17161
17162 static struct type *
17163 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17164 {
17165   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17166   struct type *type;            /* Type that this function returns.  */
17167   struct type *ftype;           /* Function that returns above type.  */
17168   struct attribute *attr;
17169
17170   type = die_type (die, cu);
17171
17172   /* The die_type call above may have already set the type for this DIE.  */
17173   ftype = get_die_type (die, cu);
17174   if (ftype)
17175     return ftype;
17176
17177   ftype = lookup_function_type (type);
17178
17179   if (prototyped_function_p (die, cu))
17180     TYPE_PROTOTYPED (ftype) = 1;
17181
17182   /* Store the calling convention in the type if it's available in
17183      the subroutine die.  Otherwise set the calling convention to
17184      the default value DW_CC_normal.  */
17185   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17186   if (attr)
17187     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17188   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17189     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17190   else
17191     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17192
17193   /* Record whether the function returns normally to its caller or not
17194      if the DWARF producer set that information.  */
17195   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17196   if (attr && (DW_UNSND (attr) != 0))
17197     TYPE_NO_RETURN (ftype) = 1;
17198
17199   /* We need to add the subroutine type to the die immediately so
17200      we don't infinitely recurse when dealing with parameters
17201      declared as the same subroutine type.  */
17202   set_die_type (die, ftype, cu);
17203
17204   if (die->child != NULL)
17205     {
17206       struct type *void_type = objfile_type (objfile)->builtin_void;
17207       struct die_info *child_die;
17208       int nparams, iparams;
17209
17210       /* Count the number of parameters.
17211          FIXME: GDB currently ignores vararg functions, but knows about
17212          vararg member functions.  */
17213       nparams = 0;
17214       child_die = die->child;
17215       while (child_die && child_die->tag)
17216         {
17217           if (child_die->tag == DW_TAG_formal_parameter)
17218             nparams++;
17219           else if (child_die->tag == DW_TAG_unspecified_parameters)
17220             TYPE_VARARGS (ftype) = 1;
17221           child_die = sibling_die (child_die);
17222         }
17223
17224       /* Allocate storage for parameters and fill them in.  */
17225       TYPE_NFIELDS (ftype) = nparams;
17226       TYPE_FIELDS (ftype) = (struct field *)
17227         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17228
17229       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17230          even if we error out during the parameters reading below.  */
17231       for (iparams = 0; iparams < nparams; iparams++)
17232         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17233
17234       iparams = 0;
17235       child_die = die->child;
17236       while (child_die && child_die->tag)
17237         {
17238           if (child_die->tag == DW_TAG_formal_parameter)
17239             {
17240               struct type *arg_type;
17241
17242               /* DWARF version 2 has no clean way to discern C++
17243                  static and non-static member functions.  G++ helps
17244                  GDB by marking the first parameter for non-static
17245                  member functions (which is the this pointer) as
17246                  artificial.  We pass this information to
17247                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17248
17249                  DWARF version 3 added DW_AT_object_pointer, which GCC
17250                  4.5 does not yet generate.  */
17251               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17252               if (attr)
17253                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17254               else
17255                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17256               arg_type = die_type (child_die, cu);
17257
17258               /* RealView does not mark THIS as const, which the testsuite
17259                  expects.  GCC marks THIS as const in method definitions,
17260                  but not in the class specifications (GCC PR 43053).  */
17261               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17262                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17263                 {
17264                   int is_this = 0;
17265                   struct dwarf2_cu *arg_cu = cu;
17266                   const char *name = dwarf2_name (child_die, cu);
17267
17268                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17269                   if (attr)
17270                     {
17271                       /* If the compiler emits this, use it.  */
17272                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17273                         is_this = 1;
17274                     }
17275                   else if (name && strcmp (name, "this") == 0)
17276                     /* Function definitions will have the argument names.  */
17277                     is_this = 1;
17278                   else if (name == NULL && iparams == 0)
17279                     /* Declarations may not have the names, so like
17280                        elsewhere in GDB, assume an artificial first
17281                        argument is "this".  */
17282                     is_this = 1;
17283
17284                   if (is_this)
17285                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17286                                              arg_type, 0);
17287                 }
17288
17289               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17290               iparams++;
17291             }
17292           child_die = sibling_die (child_die);
17293         }
17294     }
17295
17296   return ftype;
17297 }
17298
17299 static struct type *
17300 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17301 {
17302   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17303   const char *name = NULL;
17304   struct type *this_type, *target_type;
17305
17306   name = dwarf2_full_name (NULL, die, cu);
17307   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17308   TYPE_TARGET_STUB (this_type) = 1;
17309   set_die_type (die, this_type, cu);
17310   target_type = die_type (die, cu);
17311   if (target_type != this_type)
17312     TYPE_TARGET_TYPE (this_type) = target_type;
17313   else
17314     {
17315       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17316          spec and cause infinite loops in GDB.  */
17317       complaint (_("Self-referential DW_TAG_typedef "
17318                    "- DIE at %s [in module %s]"),
17319                  sect_offset_str (die->sect_off), objfile_name (objfile));
17320       TYPE_TARGET_TYPE (this_type) = NULL;
17321     }
17322   return this_type;
17323 }
17324
17325 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17326    (which may be different from NAME) to the architecture back-end to allow
17327    it to guess the correct format if necessary.  */
17328
17329 static struct type *
17330 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17331                         const char *name_hint)
17332 {
17333   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17334   const struct floatformat **format;
17335   struct type *type;
17336
17337   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17338   if (format)
17339     type = init_float_type (objfile, bits, name, format);
17340   else
17341     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17342
17343   return type;
17344 }
17345
17346 /* Find a representation of a given base type and install
17347    it in the TYPE field of the die.  */
17348
17349 static struct type *
17350 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17351 {
17352   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17353   struct type *type;
17354   struct attribute *attr;
17355   int encoding = 0, bits = 0;
17356   const char *name;
17357
17358   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17359   if (attr)
17360     {
17361       encoding = DW_UNSND (attr);
17362     }
17363   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17364   if (attr)
17365     {
17366       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17367     }
17368   name = dwarf2_name (die, cu);
17369   if (!name)
17370     {
17371       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17372     }
17373
17374   switch (encoding)
17375     {
17376       case DW_ATE_address:
17377         /* Turn DW_ATE_address into a void * pointer.  */
17378         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17379         type = init_pointer_type (objfile, bits, name, type);
17380         break;
17381       case DW_ATE_boolean:
17382         type = init_boolean_type (objfile, bits, 1, name);
17383         break;
17384       case DW_ATE_complex_float:
17385         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17386         type = init_complex_type (objfile, name, type);
17387         break;
17388       case DW_ATE_decimal_float:
17389         type = init_decfloat_type (objfile, bits, name);
17390         break;
17391       case DW_ATE_float:
17392         type = dwarf2_init_float_type (objfile, bits, name, name);
17393         break;
17394       case DW_ATE_signed:
17395         type = init_integer_type (objfile, bits, 0, name);
17396         break;
17397       case DW_ATE_unsigned:
17398         if (cu->language == language_fortran
17399             && name
17400             && startswith (name, "character("))
17401           type = init_character_type (objfile, bits, 1, name);
17402         else
17403           type = init_integer_type (objfile, bits, 1, name);
17404         break;
17405       case DW_ATE_signed_char:
17406         if (cu->language == language_ada || cu->language == language_m2
17407             || cu->language == language_pascal
17408             || cu->language == language_fortran)
17409           type = init_character_type (objfile, bits, 0, name);
17410         else
17411           type = init_integer_type (objfile, bits, 0, name);
17412         break;
17413       case DW_ATE_unsigned_char:
17414         if (cu->language == language_ada || cu->language == language_m2
17415             || cu->language == language_pascal
17416             || cu->language == language_fortran
17417             || cu->language == language_rust)
17418           type = init_character_type (objfile, bits, 1, name);
17419         else
17420           type = init_integer_type (objfile, bits, 1, name);
17421         break;
17422       case DW_ATE_UTF:
17423         {
17424           gdbarch *arch = get_objfile_arch (objfile);
17425
17426           if (bits == 16)
17427             type = builtin_type (arch)->builtin_char16;
17428           else if (bits == 32)
17429             type = builtin_type (arch)->builtin_char32;
17430           else
17431             {
17432               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17433                          bits);
17434               type = init_integer_type (objfile, bits, 1, name);
17435             }
17436           return set_die_type (die, type, cu);
17437         }
17438         break;
17439
17440       default:
17441         complaint (_("unsupported DW_AT_encoding: '%s'"),
17442                    dwarf_type_encoding_name (encoding));
17443         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17444         break;
17445     }
17446
17447   if (name && strcmp (name, "char") == 0)
17448     TYPE_NOSIGN (type) = 1;
17449
17450   maybe_set_alignment (cu, die, type);
17451
17452   return set_die_type (die, type, cu);
17453 }
17454
17455 /* Parse dwarf attribute if it's a block, reference or constant and put the
17456    resulting value of the attribute into struct bound_prop.
17457    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17458
17459 static int
17460 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17461                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17462 {
17463   struct dwarf2_property_baton *baton;
17464   struct obstack *obstack
17465     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17466
17467   if (attr == NULL || prop == NULL)
17468     return 0;
17469
17470   if (attr_form_is_block (attr))
17471     {
17472       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17473       baton->referenced_type = NULL;
17474       baton->locexpr.per_cu = cu->per_cu;
17475       baton->locexpr.size = DW_BLOCK (attr)->size;
17476       baton->locexpr.data = DW_BLOCK (attr)->data;
17477       prop->data.baton = baton;
17478       prop->kind = PROP_LOCEXPR;
17479       gdb_assert (prop->data.baton != NULL);
17480     }
17481   else if (attr_form_is_ref (attr))
17482     {
17483       struct dwarf2_cu *target_cu = cu;
17484       struct die_info *target_die;
17485       struct attribute *target_attr;
17486
17487       target_die = follow_die_ref (die, attr, &target_cu);
17488       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17489       if (target_attr == NULL)
17490         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17491                                    target_cu);
17492       if (target_attr == NULL)
17493         return 0;
17494
17495       switch (target_attr->name)
17496         {
17497           case DW_AT_location:
17498             if (attr_form_is_section_offset (target_attr))
17499               {
17500                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17501                 baton->referenced_type = die_type (target_die, target_cu);
17502                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17503                 prop->data.baton = baton;
17504                 prop->kind = PROP_LOCLIST;
17505                 gdb_assert (prop->data.baton != NULL);
17506               }
17507             else if (attr_form_is_block (target_attr))
17508               {
17509                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17510                 baton->referenced_type = die_type (target_die, target_cu);
17511                 baton->locexpr.per_cu = cu->per_cu;
17512                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17513                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17514                 prop->data.baton = baton;
17515                 prop->kind = PROP_LOCEXPR;
17516                 gdb_assert (prop->data.baton != NULL);
17517               }
17518             else
17519               {
17520                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17521                                                        "dynamic property");
17522                 return 0;
17523               }
17524             break;
17525           case DW_AT_data_member_location:
17526             {
17527               LONGEST offset;
17528
17529               if (!handle_data_member_location (target_die, target_cu,
17530                                                 &offset))
17531                 return 0;
17532
17533               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17534               baton->referenced_type = read_type_die (target_die->parent,
17535                                                       target_cu);
17536               baton->offset_info.offset = offset;
17537               baton->offset_info.type = die_type (target_die, target_cu);
17538               prop->data.baton = baton;
17539               prop->kind = PROP_ADDR_OFFSET;
17540               break;
17541             }
17542         }
17543     }
17544   else if (attr_form_is_constant (attr))
17545     {
17546       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17547       prop->kind = PROP_CONST;
17548     }
17549   else
17550     {
17551       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17552                                              dwarf2_name (die, cu));
17553       return 0;
17554     }
17555
17556   return 1;
17557 }
17558
17559 /* Read the given DW_AT_subrange DIE.  */
17560
17561 static struct type *
17562 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17563 {
17564   struct type *base_type, *orig_base_type;
17565   struct type *range_type;
17566   struct attribute *attr;
17567   struct dynamic_prop low, high;
17568   int low_default_is_valid;
17569   int high_bound_is_count = 0;
17570   const char *name;
17571   LONGEST negative_mask;
17572
17573   orig_base_type = die_type (die, cu);
17574   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17575      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17576      creating the range type, but we use the result of check_typedef
17577      when examining properties of the type.  */
17578   base_type = check_typedef (orig_base_type);
17579
17580   /* The die_type call above may have already set the type for this DIE.  */
17581   range_type = get_die_type (die, cu);
17582   if (range_type)
17583     return range_type;
17584
17585   low.kind = PROP_CONST;
17586   high.kind = PROP_CONST;
17587   high.data.const_val = 0;
17588
17589   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17590      omitting DW_AT_lower_bound.  */
17591   switch (cu->language)
17592     {
17593     case language_c:
17594     case language_cplus:
17595       low.data.const_val = 0;
17596       low_default_is_valid = 1;
17597       break;
17598     case language_fortran:
17599       low.data.const_val = 1;
17600       low_default_is_valid = 1;
17601       break;
17602     case language_d:
17603     case language_objc:
17604     case language_rust:
17605       low.data.const_val = 0;
17606       low_default_is_valid = (cu->header.version >= 4);
17607       break;
17608     case language_ada:
17609     case language_m2:
17610     case language_pascal:
17611       low.data.const_val = 1;
17612       low_default_is_valid = (cu->header.version >= 4);
17613       break;
17614     default:
17615       low.data.const_val = 0;
17616       low_default_is_valid = 0;
17617       break;
17618     }
17619
17620   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17621   if (attr)
17622     attr_to_dynamic_prop (attr, die, cu, &low);
17623   else if (!low_default_is_valid)
17624     complaint (_("Missing DW_AT_lower_bound "
17625                                       "- DIE at %s [in module %s]"),
17626                sect_offset_str (die->sect_off),
17627                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17628
17629   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17630   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17631     {
17632       attr = dwarf2_attr (die, DW_AT_count, cu);
17633       if (attr_to_dynamic_prop (attr, die, cu, &high))
17634         {
17635           /* If bounds are constant do the final calculation here.  */
17636           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17637             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17638           else
17639             high_bound_is_count = 1;
17640         }
17641     }
17642
17643   /* Dwarf-2 specifications explicitly allows to create subrange types
17644      without specifying a base type.
17645      In that case, the base type must be set to the type of
17646      the lower bound, upper bound or count, in that order, if any of these
17647      three attributes references an object that has a type.
17648      If no base type is found, the Dwarf-2 specifications say that
17649      a signed integer type of size equal to the size of an address should
17650      be used.
17651      For the following C code: `extern char gdb_int [];'
17652      GCC produces an empty range DIE.
17653      FIXME: muller/2010-05-28: Possible references to object for low bound,
17654      high bound or count are not yet handled by this code.  */
17655   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17656     {
17657       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17658       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17659       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17660       struct type *int_type = objfile_type (objfile)->builtin_int;
17661
17662       /* Test "int", "long int", and "long long int" objfile types,
17663          and select the first one having a size above or equal to the
17664          architecture address size.  */
17665       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17666         base_type = int_type;
17667       else
17668         {
17669           int_type = objfile_type (objfile)->builtin_long;
17670           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17671             base_type = int_type;
17672           else
17673             {
17674               int_type = objfile_type (objfile)->builtin_long_long;
17675               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17676                 base_type = int_type;
17677             }
17678         }
17679     }
17680
17681   /* Normally, the DWARF producers are expected to use a signed
17682      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17683      But this is unfortunately not always the case, as witnessed
17684      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17685      is used instead.  To work around that ambiguity, we treat
17686      the bounds as signed, and thus sign-extend their values, when
17687      the base type is signed.  */
17688   negative_mask =
17689     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17690   if (low.kind == PROP_CONST
17691       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17692     low.data.const_val |= negative_mask;
17693   if (high.kind == PROP_CONST
17694       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17695     high.data.const_val |= negative_mask;
17696
17697   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17698
17699   if (high_bound_is_count)
17700     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17701
17702   /* Ada expects an empty array on no boundary attributes.  */
17703   if (attr == NULL && cu->language != language_ada)
17704     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17705
17706   name = dwarf2_name (die, cu);
17707   if (name)
17708     TYPE_NAME (range_type) = name;
17709
17710   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17711   if (attr)
17712     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17713
17714   maybe_set_alignment (cu, die, range_type);
17715
17716   set_die_type (die, range_type, cu);
17717
17718   /* set_die_type should be already done.  */
17719   set_descriptive_type (range_type, die, cu);
17720
17721   return range_type;
17722 }
17723
17724 static struct type *
17725 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17726 {
17727   struct type *type;
17728
17729   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17730                     NULL);
17731   TYPE_NAME (type) = dwarf2_name (die, cu);
17732
17733   /* In Ada, an unspecified type is typically used when the description
17734      of the type is defered to a different unit.  When encountering
17735      such a type, we treat it as a stub, and try to resolve it later on,
17736      when needed.  */
17737   if (cu->language == language_ada)
17738     TYPE_STUB (type) = 1;
17739
17740   return set_die_type (die, type, cu);
17741 }
17742
17743 /* Read a single die and all its descendents.  Set the die's sibling
17744    field to NULL; set other fields in the die correctly, and set all
17745    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17746    location of the info_ptr after reading all of those dies.  PARENT
17747    is the parent of the die in question.  */
17748
17749 static struct die_info *
17750 read_die_and_children (const struct die_reader_specs *reader,
17751                        const gdb_byte *info_ptr,
17752                        const gdb_byte **new_info_ptr,
17753                        struct die_info *parent)
17754 {
17755   struct die_info *die;
17756   const gdb_byte *cur_ptr;
17757   int has_children;
17758
17759   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17760   if (die == NULL)
17761     {
17762       *new_info_ptr = cur_ptr;
17763       return NULL;
17764     }
17765   store_in_ref_table (die, reader->cu);
17766
17767   if (has_children)
17768     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17769   else
17770     {
17771       die->child = NULL;
17772       *new_info_ptr = cur_ptr;
17773     }
17774
17775   die->sibling = NULL;
17776   die->parent = parent;
17777   return die;
17778 }
17779
17780 /* Read a die, all of its descendents, and all of its siblings; set
17781    all of the fields of all of the dies correctly.  Arguments are as
17782    in read_die_and_children.  */
17783
17784 static struct die_info *
17785 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17786                          const gdb_byte *info_ptr,
17787                          const gdb_byte **new_info_ptr,
17788                          struct die_info *parent)
17789 {
17790   struct die_info *first_die, *last_sibling;
17791   const gdb_byte *cur_ptr;
17792
17793   cur_ptr = info_ptr;
17794   first_die = last_sibling = NULL;
17795
17796   while (1)
17797     {
17798       struct die_info *die
17799         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17800
17801       if (die == NULL)
17802         {
17803           *new_info_ptr = cur_ptr;
17804           return first_die;
17805         }
17806
17807       if (!first_die)
17808         first_die = die;
17809       else
17810         last_sibling->sibling = die;
17811
17812       last_sibling = die;
17813     }
17814 }
17815
17816 /* Read a die, all of its descendents, and all of its siblings; set
17817    all of the fields of all of the dies correctly.  Arguments are as
17818    in read_die_and_children.
17819    This the main entry point for reading a DIE and all its children.  */
17820
17821 static struct die_info *
17822 read_die_and_siblings (const struct die_reader_specs *reader,
17823                        const gdb_byte *info_ptr,
17824                        const gdb_byte **new_info_ptr,
17825                        struct die_info *parent)
17826 {
17827   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17828                                                   new_info_ptr, parent);
17829
17830   if (dwarf_die_debug)
17831     {
17832       fprintf_unfiltered (gdb_stdlog,
17833                           "Read die from %s@0x%x of %s:\n",
17834                           get_section_name (reader->die_section),
17835                           (unsigned) (info_ptr - reader->die_section->buffer),
17836                           bfd_get_filename (reader->abfd));
17837       dump_die (die, dwarf_die_debug);
17838     }
17839
17840   return die;
17841 }
17842
17843 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17844    attributes.
17845    The caller is responsible for filling in the extra attributes
17846    and updating (*DIEP)->num_attrs.
17847    Set DIEP to point to a newly allocated die with its information,
17848    except for its child, sibling, and parent fields.
17849    Set HAS_CHILDREN to tell whether the die has children or not.  */
17850
17851 static const gdb_byte *
17852 read_full_die_1 (const struct die_reader_specs *reader,
17853                  struct die_info **diep, const gdb_byte *info_ptr,
17854                  int *has_children, int num_extra_attrs)
17855 {
17856   unsigned int abbrev_number, bytes_read, i;
17857   struct abbrev_info *abbrev;
17858   struct die_info *die;
17859   struct dwarf2_cu *cu = reader->cu;
17860   bfd *abfd = reader->abfd;
17861
17862   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17863   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17864   info_ptr += bytes_read;
17865   if (!abbrev_number)
17866     {
17867       *diep = NULL;
17868       *has_children = 0;
17869       return info_ptr;
17870     }
17871
17872   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17873   if (!abbrev)
17874     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17875            abbrev_number,
17876            bfd_get_filename (abfd));
17877
17878   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17879   die->sect_off = sect_off;
17880   die->tag = abbrev->tag;
17881   die->abbrev = abbrev_number;
17882
17883   /* Make the result usable.
17884      The caller needs to update num_attrs after adding the extra
17885      attributes.  */
17886   die->num_attrs = abbrev->num_attrs;
17887
17888   for (i = 0; i < abbrev->num_attrs; ++i)
17889     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17890                                info_ptr);
17891
17892   *diep = die;
17893   *has_children = abbrev->has_children;
17894   return info_ptr;
17895 }
17896
17897 /* Read a die and all its attributes.
17898    Set DIEP to point to a newly allocated die with its information,
17899    except for its child, sibling, and parent fields.
17900    Set HAS_CHILDREN to tell whether the die has children or not.  */
17901
17902 static const gdb_byte *
17903 read_full_die (const struct die_reader_specs *reader,
17904                struct die_info **diep, const gdb_byte *info_ptr,
17905                int *has_children)
17906 {
17907   const gdb_byte *result;
17908
17909   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17910
17911   if (dwarf_die_debug)
17912     {
17913       fprintf_unfiltered (gdb_stdlog,
17914                           "Read die from %s@0x%x of %s:\n",
17915                           get_section_name (reader->die_section),
17916                           (unsigned) (info_ptr - reader->die_section->buffer),
17917                           bfd_get_filename (reader->abfd));
17918       dump_die (*diep, dwarf_die_debug);
17919     }
17920
17921   return result;
17922 }
17923 \f
17924 /* Abbreviation tables.
17925
17926    In DWARF version 2, the description of the debugging information is
17927    stored in a separate .debug_abbrev section.  Before we read any
17928    dies from a section we read in all abbreviations and install them
17929    in a hash table.  */
17930
17931 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17932
17933 struct abbrev_info *
17934 abbrev_table::alloc_abbrev ()
17935 {
17936   struct abbrev_info *abbrev;
17937
17938   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
17939   memset (abbrev, 0, sizeof (struct abbrev_info));
17940
17941   return abbrev;
17942 }
17943
17944 /* Add an abbreviation to the table.  */
17945
17946 void
17947 abbrev_table::add_abbrev (unsigned int abbrev_number,
17948                           struct abbrev_info *abbrev)
17949 {
17950   unsigned int hash_number;
17951
17952   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17953   abbrev->next = m_abbrevs[hash_number];
17954   m_abbrevs[hash_number] = abbrev;
17955 }
17956
17957 /* Look up an abbrev in the table.
17958    Returns NULL if the abbrev is not found.  */
17959
17960 struct abbrev_info *
17961 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
17962 {
17963   unsigned int hash_number;
17964   struct abbrev_info *abbrev;
17965
17966   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17967   abbrev = m_abbrevs[hash_number];
17968
17969   while (abbrev)
17970     {
17971       if (abbrev->number == abbrev_number)
17972         return abbrev;
17973       abbrev = abbrev->next;
17974     }
17975   return NULL;
17976 }
17977
17978 /* Read in an abbrev table.  */
17979
17980 static abbrev_table_up
17981 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
17982                          struct dwarf2_section_info *section,
17983                          sect_offset sect_off)
17984 {
17985   struct objfile *objfile = dwarf2_per_objfile->objfile;
17986   bfd *abfd = get_section_bfd_owner (section);
17987   const gdb_byte *abbrev_ptr;
17988   struct abbrev_info *cur_abbrev;
17989   unsigned int abbrev_number, bytes_read, abbrev_name;
17990   unsigned int abbrev_form;
17991   struct attr_abbrev *cur_attrs;
17992   unsigned int allocated_attrs;
17993
17994   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
17995
17996   dwarf2_read_section (objfile, section);
17997   abbrev_ptr = section->buffer + to_underlying (sect_off);
17998   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17999   abbrev_ptr += bytes_read;
18000
18001   allocated_attrs = ATTR_ALLOC_CHUNK;
18002   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18003
18004   /* Loop until we reach an abbrev number of 0.  */
18005   while (abbrev_number)
18006     {
18007       cur_abbrev = abbrev_table->alloc_abbrev ();
18008
18009       /* read in abbrev header */
18010       cur_abbrev->number = abbrev_number;
18011       cur_abbrev->tag
18012         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18013       abbrev_ptr += bytes_read;
18014       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18015       abbrev_ptr += 1;
18016
18017       /* now read in declarations */
18018       for (;;)
18019         {
18020           LONGEST implicit_const;
18021
18022           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18023           abbrev_ptr += bytes_read;
18024           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18025           abbrev_ptr += bytes_read;
18026           if (abbrev_form == DW_FORM_implicit_const)
18027             {
18028               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18029                                                    &bytes_read);
18030               abbrev_ptr += bytes_read;
18031             }
18032           else
18033             {
18034               /* Initialize it due to a false compiler warning.  */
18035               implicit_const = -1;
18036             }
18037
18038           if (abbrev_name == 0)
18039             break;
18040
18041           if (cur_abbrev->num_attrs == allocated_attrs)
18042             {
18043               allocated_attrs += ATTR_ALLOC_CHUNK;
18044               cur_attrs
18045                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18046             }
18047
18048           cur_attrs[cur_abbrev->num_attrs].name
18049             = (enum dwarf_attribute) abbrev_name;
18050           cur_attrs[cur_abbrev->num_attrs].form
18051             = (enum dwarf_form) abbrev_form;
18052           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18053           ++cur_abbrev->num_attrs;
18054         }
18055
18056       cur_abbrev->attrs =
18057         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18058                    cur_abbrev->num_attrs);
18059       memcpy (cur_abbrev->attrs, cur_attrs,
18060               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18061
18062       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18063
18064       /* Get next abbreviation.
18065          Under Irix6 the abbreviations for a compilation unit are not
18066          always properly terminated with an abbrev number of 0.
18067          Exit loop if we encounter an abbreviation which we have
18068          already read (which means we are about to read the abbreviations
18069          for the next compile unit) or if the end of the abbreviation
18070          table is reached.  */
18071       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18072         break;
18073       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18074       abbrev_ptr += bytes_read;
18075       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18076         break;
18077     }
18078
18079   xfree (cur_attrs);
18080   return abbrev_table;
18081 }
18082
18083 /* Returns nonzero if TAG represents a type that we might generate a partial
18084    symbol for.  */
18085
18086 static int
18087 is_type_tag_for_partial (int tag)
18088 {
18089   switch (tag)
18090     {
18091 #if 0
18092     /* Some types that would be reasonable to generate partial symbols for,
18093        that we don't at present.  */
18094     case DW_TAG_array_type:
18095     case DW_TAG_file_type:
18096     case DW_TAG_ptr_to_member_type:
18097     case DW_TAG_set_type:
18098     case DW_TAG_string_type:
18099     case DW_TAG_subroutine_type:
18100 #endif
18101     case DW_TAG_base_type:
18102     case DW_TAG_class_type:
18103     case DW_TAG_interface_type:
18104     case DW_TAG_enumeration_type:
18105     case DW_TAG_structure_type:
18106     case DW_TAG_subrange_type:
18107     case DW_TAG_typedef:
18108     case DW_TAG_union_type:
18109       return 1;
18110     default:
18111       return 0;
18112     }
18113 }
18114
18115 /* Load all DIEs that are interesting for partial symbols into memory.  */
18116
18117 static struct partial_die_info *
18118 load_partial_dies (const struct die_reader_specs *reader,
18119                    const gdb_byte *info_ptr, int building_psymtab)
18120 {
18121   struct dwarf2_cu *cu = reader->cu;
18122   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18123   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18124   unsigned int bytes_read;
18125   unsigned int load_all = 0;
18126   int nesting_level = 1;
18127
18128   parent_die = NULL;
18129   last_die = NULL;
18130
18131   gdb_assert (cu->per_cu != NULL);
18132   if (cu->per_cu->load_all_dies)
18133     load_all = 1;
18134
18135   cu->partial_dies
18136     = htab_create_alloc_ex (cu->header.length / 12,
18137                             partial_die_hash,
18138                             partial_die_eq,
18139                             NULL,
18140                             &cu->comp_unit_obstack,
18141                             hashtab_obstack_allocate,
18142                             dummy_obstack_deallocate);
18143
18144   while (1)
18145     {
18146       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18147
18148       /* A NULL abbrev means the end of a series of children.  */
18149       if (abbrev == NULL)
18150         {
18151           if (--nesting_level == 0)
18152             return first_die;
18153
18154           info_ptr += bytes_read;
18155           last_die = parent_die;
18156           parent_die = parent_die->die_parent;
18157           continue;
18158         }
18159
18160       /* Check for template arguments.  We never save these; if
18161          they're seen, we just mark the parent, and go on our way.  */
18162       if (parent_die != NULL
18163           && cu->language == language_cplus
18164           && (abbrev->tag == DW_TAG_template_type_param
18165               || abbrev->tag == DW_TAG_template_value_param))
18166         {
18167           parent_die->has_template_arguments = 1;
18168
18169           if (!load_all)
18170             {
18171               /* We don't need a partial DIE for the template argument.  */
18172               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18173               continue;
18174             }
18175         }
18176
18177       /* We only recurse into c++ subprograms looking for template arguments.
18178          Skip their other children.  */
18179       if (!load_all
18180           && cu->language == language_cplus
18181           && parent_die != NULL
18182           && parent_die->tag == DW_TAG_subprogram)
18183         {
18184           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18185           continue;
18186         }
18187
18188       /* Check whether this DIE is interesting enough to save.  Normally
18189          we would not be interested in members here, but there may be
18190          later variables referencing them via DW_AT_specification (for
18191          static members).  */
18192       if (!load_all
18193           && !is_type_tag_for_partial (abbrev->tag)
18194           && abbrev->tag != DW_TAG_constant
18195           && abbrev->tag != DW_TAG_enumerator
18196           && abbrev->tag != DW_TAG_subprogram
18197           && abbrev->tag != DW_TAG_inlined_subroutine
18198           && abbrev->tag != DW_TAG_lexical_block
18199           && abbrev->tag != DW_TAG_variable
18200           && abbrev->tag != DW_TAG_namespace
18201           && abbrev->tag != DW_TAG_module
18202           && abbrev->tag != DW_TAG_member
18203           && abbrev->tag != DW_TAG_imported_unit
18204           && abbrev->tag != DW_TAG_imported_declaration)
18205         {
18206           /* Otherwise we skip to the next sibling, if any.  */
18207           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18208           continue;
18209         }
18210
18211       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18212                                    abbrev);
18213
18214       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18215
18216       /* This two-pass algorithm for processing partial symbols has a
18217          high cost in cache pressure.  Thus, handle some simple cases
18218          here which cover the majority of C partial symbols.  DIEs
18219          which neither have specification tags in them, nor could have
18220          specification tags elsewhere pointing at them, can simply be
18221          processed and discarded.
18222
18223          This segment is also optional; scan_partial_symbols and
18224          add_partial_symbol will handle these DIEs if we chain
18225          them in normally.  When compilers which do not emit large
18226          quantities of duplicate debug information are more common,
18227          this code can probably be removed.  */
18228
18229       /* Any complete simple types at the top level (pretty much all
18230          of them, for a language without namespaces), can be processed
18231          directly.  */
18232       if (parent_die == NULL
18233           && pdi.has_specification == 0
18234           && pdi.is_declaration == 0
18235           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18236               || pdi.tag == DW_TAG_base_type
18237               || pdi.tag == DW_TAG_subrange_type))
18238         {
18239           if (building_psymtab && pdi.name != NULL)
18240             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18241                                  VAR_DOMAIN, LOC_TYPEDEF,
18242                                  &objfile->static_psymbols,
18243                                  0, cu->language, objfile);
18244           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18245           continue;
18246         }
18247
18248       /* The exception for DW_TAG_typedef with has_children above is
18249          a workaround of GCC PR debug/47510.  In the case of this complaint
18250          type_name_or_error will error on such types later.
18251
18252          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18253          it could not find the child DIEs referenced later, this is checked
18254          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18255
18256       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18257         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18258                      "- DIE at %s [in module %s]"),
18259                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18260
18261       /* If we're at the second level, and we're an enumerator, and
18262          our parent has no specification (meaning possibly lives in a
18263          namespace elsewhere), then we can add the partial symbol now
18264          instead of queueing it.  */
18265       if (pdi.tag == DW_TAG_enumerator
18266           && parent_die != NULL
18267           && parent_die->die_parent == NULL
18268           && parent_die->tag == DW_TAG_enumeration_type
18269           && parent_die->has_specification == 0)
18270         {
18271           if (pdi.name == NULL)
18272             complaint (_("malformed enumerator DIE ignored"));
18273           else if (building_psymtab)
18274             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18275                                  VAR_DOMAIN, LOC_CONST,
18276                                  cu->language == language_cplus
18277                                  ? &objfile->global_psymbols
18278                                  : &objfile->static_psymbols,
18279                                  0, cu->language, objfile);
18280
18281           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18282           continue;
18283         }
18284
18285       struct partial_die_info *part_die
18286         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18287
18288       /* We'll save this DIE so link it in.  */
18289       part_die->die_parent = parent_die;
18290       part_die->die_sibling = NULL;
18291       part_die->die_child = NULL;
18292
18293       if (last_die && last_die == parent_die)
18294         last_die->die_child = part_die;
18295       else if (last_die)
18296         last_die->die_sibling = part_die;
18297
18298       last_die = part_die;
18299
18300       if (first_die == NULL)
18301         first_die = part_die;
18302
18303       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18304          find interesting need to be in the hash table, because we
18305          also have the parent/sibling/child chains; only those that we
18306          might refer to by offset later during partial symbol reading.
18307
18308          For now this means things that might have be the target of a
18309          DW_AT_specification, DW_AT_abstract_origin, or
18310          DW_AT_extension.  DW_AT_extension will refer only to
18311          namespaces; DW_AT_abstract_origin refers to functions (and
18312          many things under the function DIE, but we do not recurse
18313          into function DIEs during partial symbol reading) and
18314          possibly variables as well; DW_AT_specification refers to
18315          declarations.  Declarations ought to have the DW_AT_declaration
18316          flag.  It happens that GCC forgets to put it in sometimes, but
18317          only for functions, not for types.
18318
18319          Adding more things than necessary to the hash table is harmless
18320          except for the performance cost.  Adding too few will result in
18321          wasted time in find_partial_die, when we reread the compilation
18322          unit with load_all_dies set.  */
18323
18324       if (load_all
18325           || abbrev->tag == DW_TAG_constant
18326           || abbrev->tag == DW_TAG_subprogram
18327           || abbrev->tag == DW_TAG_variable
18328           || abbrev->tag == DW_TAG_namespace
18329           || part_die->is_declaration)
18330         {
18331           void **slot;
18332
18333           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18334                                            to_underlying (part_die->sect_off),
18335                                            INSERT);
18336           *slot = part_die;
18337         }
18338
18339       /* For some DIEs we want to follow their children (if any).  For C
18340          we have no reason to follow the children of structures; for other
18341          languages we have to, so that we can get at method physnames
18342          to infer fully qualified class names, for DW_AT_specification,
18343          and for C++ template arguments.  For C++, we also look one level
18344          inside functions to find template arguments (if the name of the
18345          function does not already contain the template arguments).
18346
18347          For Ada, we need to scan the children of subprograms and lexical
18348          blocks as well because Ada allows the definition of nested
18349          entities that could be interesting for the debugger, such as
18350          nested subprograms for instance.  */
18351       if (last_die->has_children
18352           && (load_all
18353               || last_die->tag == DW_TAG_namespace
18354               || last_die->tag == DW_TAG_module
18355               || last_die->tag == DW_TAG_enumeration_type
18356               || (cu->language == language_cplus
18357                   && last_die->tag == DW_TAG_subprogram
18358                   && (last_die->name == NULL
18359                       || strchr (last_die->name, '<') == NULL))
18360               || (cu->language != language_c
18361                   && (last_die->tag == DW_TAG_class_type
18362                       || last_die->tag == DW_TAG_interface_type
18363                       || last_die->tag == DW_TAG_structure_type
18364                       || last_die->tag == DW_TAG_union_type))
18365               || (cu->language == language_ada
18366                   && (last_die->tag == DW_TAG_subprogram
18367                       || last_die->tag == DW_TAG_lexical_block))))
18368         {
18369           nesting_level++;
18370           parent_die = last_die;
18371           continue;
18372         }
18373
18374       /* Otherwise we skip to the next sibling, if any.  */
18375       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18376
18377       /* Back to the top, do it again.  */
18378     }
18379 }
18380
18381 partial_die_info::partial_die_info (sect_offset sect_off_,
18382                                     struct abbrev_info *abbrev)
18383   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18384 {
18385 }
18386
18387 /* Read a minimal amount of information into the minimal die structure.
18388    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18389
18390 const gdb_byte *
18391 partial_die_info::read (const struct die_reader_specs *reader,
18392                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18393 {
18394   struct dwarf2_cu *cu = reader->cu;
18395   struct dwarf2_per_objfile *dwarf2_per_objfile
18396     = cu->per_cu->dwarf2_per_objfile;
18397   unsigned int i;
18398   int has_low_pc_attr = 0;
18399   int has_high_pc_attr = 0;
18400   int high_pc_relative = 0;
18401
18402   for (i = 0; i < abbrev.num_attrs; ++i)
18403     {
18404       struct attribute attr;
18405
18406       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18407
18408       /* Store the data if it is of an attribute we want to keep in a
18409          partial symbol table.  */
18410       switch (attr.name)
18411         {
18412         case DW_AT_name:
18413           switch (tag)
18414             {
18415             case DW_TAG_compile_unit:
18416             case DW_TAG_partial_unit:
18417             case DW_TAG_type_unit:
18418               /* Compilation units have a DW_AT_name that is a filename, not
18419                  a source language identifier.  */
18420             case DW_TAG_enumeration_type:
18421             case DW_TAG_enumerator:
18422               /* These tags always have simple identifiers already; no need
18423                  to canonicalize them.  */
18424               name = DW_STRING (&attr);
18425               break;
18426             default:
18427               {
18428                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18429
18430                 name
18431                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18432                                               &objfile->per_bfd->storage_obstack);
18433               }
18434               break;
18435             }
18436           break;
18437         case DW_AT_linkage_name:
18438         case DW_AT_MIPS_linkage_name:
18439           /* Note that both forms of linkage name might appear.  We
18440              assume they will be the same, and we only store the last
18441              one we see.  */
18442           if (cu->language == language_ada)
18443             name = DW_STRING (&attr);
18444           linkage_name = DW_STRING (&attr);
18445           break;
18446         case DW_AT_low_pc:
18447           has_low_pc_attr = 1;
18448           lowpc = attr_value_as_address (&attr);
18449           break;
18450         case DW_AT_high_pc:
18451           has_high_pc_attr = 1;
18452           highpc = attr_value_as_address (&attr);
18453           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18454                 high_pc_relative = 1;
18455           break;
18456         case DW_AT_location:
18457           /* Support the .debug_loc offsets.  */
18458           if (attr_form_is_block (&attr))
18459             {
18460                d.locdesc = DW_BLOCK (&attr);
18461             }
18462           else if (attr_form_is_section_offset (&attr))
18463             {
18464               dwarf2_complex_location_expr_complaint ();
18465             }
18466           else
18467             {
18468               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18469                                                      "partial symbol information");
18470             }
18471           break;
18472         case DW_AT_external:
18473           is_external = DW_UNSND (&attr);
18474           break;
18475         case DW_AT_declaration:
18476           is_declaration = DW_UNSND (&attr);
18477           break;
18478         case DW_AT_type:
18479           has_type = 1;
18480           break;
18481         case DW_AT_abstract_origin:
18482         case DW_AT_specification:
18483         case DW_AT_extension:
18484           has_specification = 1;
18485           spec_offset = dwarf2_get_ref_die_offset (&attr);
18486           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18487                                    || cu->per_cu->is_dwz);
18488           break;
18489         case DW_AT_sibling:
18490           /* Ignore absolute siblings, they might point outside of
18491              the current compile unit.  */
18492           if (attr.form == DW_FORM_ref_addr)
18493             complaint (_("ignoring absolute DW_AT_sibling"));
18494           else
18495             {
18496               const gdb_byte *buffer = reader->buffer;
18497               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18498               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18499
18500               if (sibling_ptr < info_ptr)
18501                 complaint (_("DW_AT_sibling points backwards"));
18502               else if (sibling_ptr > reader->buffer_end)
18503                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18504               else
18505                 sibling = sibling_ptr;
18506             }
18507           break;
18508         case DW_AT_byte_size:
18509           has_byte_size = 1;
18510           break;
18511         case DW_AT_const_value:
18512           has_const_value = 1;
18513           break;
18514         case DW_AT_calling_convention:
18515           /* DWARF doesn't provide a way to identify a program's source-level
18516              entry point.  DW_AT_calling_convention attributes are only meant
18517              to describe functions' calling conventions.
18518
18519              However, because it's a necessary piece of information in
18520              Fortran, and before DWARF 4 DW_CC_program was the only
18521              piece of debugging information whose definition refers to
18522              a 'main program' at all, several compilers marked Fortran
18523              main programs with DW_CC_program --- even when those
18524              functions use the standard calling conventions.
18525
18526              Although DWARF now specifies a way to provide this
18527              information, we support this practice for backward
18528              compatibility.  */
18529           if (DW_UNSND (&attr) == DW_CC_program
18530               && cu->language == language_fortran)
18531             main_subprogram = 1;
18532           break;
18533         case DW_AT_inline:
18534           if (DW_UNSND (&attr) == DW_INL_inlined
18535               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18536             may_be_inlined = 1;
18537           break;
18538
18539         case DW_AT_import:
18540           if (tag == DW_TAG_imported_unit)
18541             {
18542               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18543               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18544                                   || cu->per_cu->is_dwz);
18545             }
18546           break;
18547
18548         case DW_AT_main_subprogram:
18549           main_subprogram = DW_UNSND (&attr);
18550           break;
18551
18552         default:
18553           break;
18554         }
18555     }
18556
18557   if (high_pc_relative)
18558     highpc += lowpc;
18559
18560   if (has_low_pc_attr && has_high_pc_attr)
18561     {
18562       /* When using the GNU linker, .gnu.linkonce. sections are used to
18563          eliminate duplicate copies of functions and vtables and such.
18564          The linker will arbitrarily choose one and discard the others.
18565          The AT_*_pc values for such functions refer to local labels in
18566          these sections.  If the section from that file was discarded, the
18567          labels are not in the output, so the relocs get a value of 0.
18568          If this is a discarded function, mark the pc bounds as invalid,
18569          so that GDB will ignore it.  */
18570       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18571         {
18572           struct objfile *objfile = dwarf2_per_objfile->objfile;
18573           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18574
18575           complaint (_("DW_AT_low_pc %s is zero "
18576                        "for DIE at %s [in module %s]"),
18577                      paddress (gdbarch, lowpc),
18578                      sect_offset_str (sect_off),
18579                      objfile_name (objfile));
18580         }
18581       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18582       else if (lowpc >= highpc)
18583         {
18584           struct objfile *objfile = dwarf2_per_objfile->objfile;
18585           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18586
18587           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18588                        "for DIE at %s [in module %s]"),
18589                      paddress (gdbarch, lowpc),
18590                      paddress (gdbarch, highpc),
18591                      sect_offset_str (sect_off),
18592                      objfile_name (objfile));
18593         }
18594       else
18595         has_pc_info = 1;
18596     }
18597
18598   return info_ptr;
18599 }
18600
18601 /* Find a cached partial DIE at OFFSET in CU.  */
18602
18603 struct partial_die_info *
18604 dwarf2_cu::find_partial_die (sect_offset sect_off)
18605 {
18606   struct partial_die_info *lookup_die = NULL;
18607   struct partial_die_info part_die (sect_off);
18608
18609   lookup_die = ((struct partial_die_info *)
18610                 htab_find_with_hash (partial_dies, &part_die,
18611                                      to_underlying (sect_off)));
18612
18613   return lookup_die;
18614 }
18615
18616 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18617    except in the case of .debug_types DIEs which do not reference
18618    outside their CU (they do however referencing other types via
18619    DW_FORM_ref_sig8).  */
18620
18621 static struct partial_die_info *
18622 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18623 {
18624   struct dwarf2_per_objfile *dwarf2_per_objfile
18625     = cu->per_cu->dwarf2_per_objfile;
18626   struct objfile *objfile = dwarf2_per_objfile->objfile;
18627   struct dwarf2_per_cu_data *per_cu = NULL;
18628   struct partial_die_info *pd = NULL;
18629
18630   if (offset_in_dwz == cu->per_cu->is_dwz
18631       && offset_in_cu_p (&cu->header, sect_off))
18632     {
18633       pd = cu->find_partial_die (sect_off);
18634       if (pd != NULL)
18635         return pd;
18636       /* We missed recording what we needed.
18637          Load all dies and try again.  */
18638       per_cu = cu->per_cu;
18639     }
18640   else
18641     {
18642       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18643       if (cu->per_cu->is_debug_types)
18644         {
18645           error (_("Dwarf Error: Type Unit at offset %s contains"
18646                    " external reference to offset %s [in module %s].\n"),
18647                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18648                  bfd_get_filename (objfile->obfd));
18649         }
18650       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18651                                                  dwarf2_per_objfile);
18652
18653       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18654         load_partial_comp_unit (per_cu);
18655
18656       per_cu->cu->last_used = 0;
18657       pd = per_cu->cu->find_partial_die (sect_off);
18658     }
18659
18660   /* If we didn't find it, and not all dies have been loaded,
18661      load them all and try again.  */
18662
18663   if (pd == NULL && per_cu->load_all_dies == 0)
18664     {
18665       per_cu->load_all_dies = 1;
18666
18667       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18668          THIS_CU->cu may already be in use.  So we can't just free it and
18669          replace its DIEs with the ones we read in.  Instead, we leave those
18670          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18671          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18672          set.  */
18673       load_partial_comp_unit (per_cu);
18674
18675       pd = per_cu->cu->find_partial_die (sect_off);
18676     }
18677
18678   if (pd == NULL)
18679     internal_error (__FILE__, __LINE__,
18680                     _("could not find partial DIE %s "
18681                       "in cache [from module %s]\n"),
18682                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18683   return pd;
18684 }
18685
18686 /* See if we can figure out if the class lives in a namespace.  We do
18687    this by looking for a member function; its demangled name will
18688    contain namespace info, if there is any.  */
18689
18690 static void
18691 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18692                                   struct dwarf2_cu *cu)
18693 {
18694   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18695      what template types look like, because the demangler
18696      frequently doesn't give the same name as the debug info.  We
18697      could fix this by only using the demangled name to get the
18698      prefix (but see comment in read_structure_type).  */
18699
18700   struct partial_die_info *real_pdi;
18701   struct partial_die_info *child_pdi;
18702
18703   /* If this DIE (this DIE's specification, if any) has a parent, then
18704      we should not do this.  We'll prepend the parent's fully qualified
18705      name when we create the partial symbol.  */
18706
18707   real_pdi = struct_pdi;
18708   while (real_pdi->has_specification)
18709     real_pdi = find_partial_die (real_pdi->spec_offset,
18710                                  real_pdi->spec_is_dwz, cu);
18711
18712   if (real_pdi->die_parent != NULL)
18713     return;
18714
18715   for (child_pdi = struct_pdi->die_child;
18716        child_pdi != NULL;
18717        child_pdi = child_pdi->die_sibling)
18718     {
18719       if (child_pdi->tag == DW_TAG_subprogram
18720           && child_pdi->linkage_name != NULL)
18721         {
18722           char *actual_class_name
18723             = language_class_name_from_physname (cu->language_defn,
18724                                                  child_pdi->linkage_name);
18725           if (actual_class_name != NULL)
18726             {
18727               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18728               struct_pdi->name
18729                 = ((const char *)
18730                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18731                                   actual_class_name,
18732                                   strlen (actual_class_name)));
18733               xfree (actual_class_name);
18734             }
18735           break;
18736         }
18737     }
18738 }
18739
18740 void
18741 partial_die_info::fixup (struct dwarf2_cu *cu)
18742 {
18743   /* Once we've fixed up a die, there's no point in doing so again.
18744      This also avoids a memory leak if we were to call
18745      guess_partial_die_structure_name multiple times.  */
18746   if (fixup_called)
18747     return;
18748
18749   /* If we found a reference attribute and the DIE has no name, try
18750      to find a name in the referred to DIE.  */
18751
18752   if (name == NULL && has_specification)
18753     {
18754       struct partial_die_info *spec_die;
18755
18756       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18757
18758       spec_die->fixup (cu);
18759
18760       if (spec_die->name)
18761         {
18762           name = spec_die->name;
18763
18764           /* Copy DW_AT_external attribute if it is set.  */
18765           if (spec_die->is_external)
18766             is_external = spec_die->is_external;
18767         }
18768     }
18769
18770   /* Set default names for some unnamed DIEs.  */
18771
18772   if (name == NULL && tag == DW_TAG_namespace)
18773     name = CP_ANONYMOUS_NAMESPACE_STR;
18774
18775   /* If there is no parent die to provide a namespace, and there are
18776      children, see if we can determine the namespace from their linkage
18777      name.  */
18778   if (cu->language == language_cplus
18779       && !VEC_empty (dwarf2_section_info_def,
18780                      cu->per_cu->dwarf2_per_objfile->types)
18781       && die_parent == NULL
18782       && has_children
18783       && (tag == DW_TAG_class_type
18784           || tag == DW_TAG_structure_type
18785           || tag == DW_TAG_union_type))
18786     guess_partial_die_structure_name (this, cu);
18787
18788   /* GCC might emit a nameless struct or union that has a linkage
18789      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18790   if (name == NULL
18791       && (tag == DW_TAG_class_type
18792           || tag == DW_TAG_interface_type
18793           || tag == DW_TAG_structure_type
18794           || tag == DW_TAG_union_type)
18795       && linkage_name != NULL)
18796     {
18797       char *demangled;
18798
18799       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18800       if (demangled)
18801         {
18802           const char *base;
18803
18804           /* Strip any leading namespaces/classes, keep only the base name.
18805              DW_AT_name for named DIEs does not contain the prefixes.  */
18806           base = strrchr (demangled, ':');
18807           if (base && base > demangled && base[-1] == ':')
18808             base++;
18809           else
18810             base = demangled;
18811
18812           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18813           name
18814             = ((const char *)
18815                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18816                               base, strlen (base)));
18817           xfree (demangled);
18818         }
18819     }
18820
18821   fixup_called = 1;
18822 }
18823
18824 /* Read an attribute value described by an attribute form.  */
18825
18826 static const gdb_byte *
18827 read_attribute_value (const struct die_reader_specs *reader,
18828                       struct attribute *attr, unsigned form,
18829                       LONGEST implicit_const, const gdb_byte *info_ptr)
18830 {
18831   struct dwarf2_cu *cu = reader->cu;
18832   struct dwarf2_per_objfile *dwarf2_per_objfile
18833     = cu->per_cu->dwarf2_per_objfile;
18834   struct objfile *objfile = dwarf2_per_objfile->objfile;
18835   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18836   bfd *abfd = reader->abfd;
18837   struct comp_unit_head *cu_header = &cu->header;
18838   unsigned int bytes_read;
18839   struct dwarf_block *blk;
18840
18841   attr->form = (enum dwarf_form) form;
18842   switch (form)
18843     {
18844     case DW_FORM_ref_addr:
18845       if (cu->header.version == 2)
18846         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18847       else
18848         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18849                                        &cu->header, &bytes_read);
18850       info_ptr += bytes_read;
18851       break;
18852     case DW_FORM_GNU_ref_alt:
18853       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18854       info_ptr += bytes_read;
18855       break;
18856     case DW_FORM_addr:
18857       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18858       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18859       info_ptr += bytes_read;
18860       break;
18861     case DW_FORM_block2:
18862       blk = dwarf_alloc_block (cu);
18863       blk->size = read_2_bytes (abfd, info_ptr);
18864       info_ptr += 2;
18865       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18866       info_ptr += blk->size;
18867       DW_BLOCK (attr) = blk;
18868       break;
18869     case DW_FORM_block4:
18870       blk = dwarf_alloc_block (cu);
18871       blk->size = read_4_bytes (abfd, info_ptr);
18872       info_ptr += 4;
18873       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18874       info_ptr += blk->size;
18875       DW_BLOCK (attr) = blk;
18876       break;
18877     case DW_FORM_data2:
18878       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18879       info_ptr += 2;
18880       break;
18881     case DW_FORM_data4:
18882       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18883       info_ptr += 4;
18884       break;
18885     case DW_FORM_data8:
18886       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18887       info_ptr += 8;
18888       break;
18889     case DW_FORM_data16:
18890       blk = dwarf_alloc_block (cu);
18891       blk->size = 16;
18892       blk->data = read_n_bytes (abfd, info_ptr, 16);
18893       info_ptr += 16;
18894       DW_BLOCK (attr) = blk;
18895       break;
18896     case DW_FORM_sec_offset:
18897       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18898       info_ptr += bytes_read;
18899       break;
18900     case DW_FORM_string:
18901       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18902       DW_STRING_IS_CANONICAL (attr) = 0;
18903       info_ptr += bytes_read;
18904       break;
18905     case DW_FORM_strp:
18906       if (!cu->per_cu->is_dwz)
18907         {
18908           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18909                                                    abfd, info_ptr, cu_header,
18910                                                    &bytes_read);
18911           DW_STRING_IS_CANONICAL (attr) = 0;
18912           info_ptr += bytes_read;
18913           break;
18914         }
18915       /* FALLTHROUGH */
18916     case DW_FORM_line_strp:
18917       if (!cu->per_cu->is_dwz)
18918         {
18919           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18920                                                         abfd, info_ptr,
18921                                                         cu_header, &bytes_read);
18922           DW_STRING_IS_CANONICAL (attr) = 0;
18923           info_ptr += bytes_read;
18924           break;
18925         }
18926       /* FALLTHROUGH */
18927     case DW_FORM_GNU_strp_alt:
18928       {
18929         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
18930         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18931                                           &bytes_read);
18932
18933         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
18934                                                           dwz, str_offset);
18935         DW_STRING_IS_CANONICAL (attr) = 0;
18936         info_ptr += bytes_read;
18937       }
18938       break;
18939     case DW_FORM_exprloc:
18940     case DW_FORM_block:
18941       blk = dwarf_alloc_block (cu);
18942       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18943       info_ptr += bytes_read;
18944       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18945       info_ptr += blk->size;
18946       DW_BLOCK (attr) = blk;
18947       break;
18948     case DW_FORM_block1:
18949       blk = dwarf_alloc_block (cu);
18950       blk->size = read_1_byte (abfd, info_ptr);
18951       info_ptr += 1;
18952       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18953       info_ptr += blk->size;
18954       DW_BLOCK (attr) = blk;
18955       break;
18956     case DW_FORM_data1:
18957       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18958       info_ptr += 1;
18959       break;
18960     case DW_FORM_flag:
18961       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18962       info_ptr += 1;
18963       break;
18964     case DW_FORM_flag_present:
18965       DW_UNSND (attr) = 1;
18966       break;
18967     case DW_FORM_sdata:
18968       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18969       info_ptr += bytes_read;
18970       break;
18971     case DW_FORM_udata:
18972       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18973       info_ptr += bytes_read;
18974       break;
18975     case DW_FORM_ref1:
18976       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18977                          + read_1_byte (abfd, info_ptr));
18978       info_ptr += 1;
18979       break;
18980     case DW_FORM_ref2:
18981       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18982                          + read_2_bytes (abfd, info_ptr));
18983       info_ptr += 2;
18984       break;
18985     case DW_FORM_ref4:
18986       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18987                          + read_4_bytes (abfd, info_ptr));
18988       info_ptr += 4;
18989       break;
18990     case DW_FORM_ref8:
18991       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18992                          + read_8_bytes (abfd, info_ptr));
18993       info_ptr += 8;
18994       break;
18995     case DW_FORM_ref_sig8:
18996       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
18997       info_ptr += 8;
18998       break;
18999     case DW_FORM_ref_udata:
19000       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19001                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19002       info_ptr += bytes_read;
19003       break;
19004     case DW_FORM_indirect:
19005       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19006       info_ptr += bytes_read;
19007       if (form == DW_FORM_implicit_const)
19008         {
19009           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19010           info_ptr += bytes_read;
19011         }
19012       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19013                                        info_ptr);
19014       break;
19015     case DW_FORM_implicit_const:
19016       DW_SND (attr) = implicit_const;
19017       break;
19018     case DW_FORM_GNU_addr_index:
19019       if (reader->dwo_file == NULL)
19020         {
19021           /* For now flag a hard error.
19022              Later we can turn this into a complaint.  */
19023           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19024                  dwarf_form_name (form),
19025                  bfd_get_filename (abfd));
19026         }
19027       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19028       info_ptr += bytes_read;
19029       break;
19030     case DW_FORM_GNU_str_index:
19031       if (reader->dwo_file == NULL)
19032         {
19033           /* For now flag a hard error.
19034              Later we can turn this into a complaint if warranted.  */
19035           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19036                  dwarf_form_name (form),
19037                  bfd_get_filename (abfd));
19038         }
19039       {
19040         ULONGEST str_index =
19041           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19042
19043         DW_STRING (attr) = read_str_index (reader, str_index);
19044         DW_STRING_IS_CANONICAL (attr) = 0;
19045         info_ptr += bytes_read;
19046       }
19047       break;
19048     default:
19049       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19050              dwarf_form_name (form),
19051              bfd_get_filename (abfd));
19052     }
19053
19054   /* Super hack.  */
19055   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19056     attr->form = DW_FORM_GNU_ref_alt;
19057
19058   /* We have seen instances where the compiler tried to emit a byte
19059      size attribute of -1 which ended up being encoded as an unsigned
19060      0xffffffff.  Although 0xffffffff is technically a valid size value,
19061      an object of this size seems pretty unlikely so we can relatively
19062      safely treat these cases as if the size attribute was invalid and
19063      treat them as zero by default.  */
19064   if (attr->name == DW_AT_byte_size
19065       && form == DW_FORM_data4
19066       && DW_UNSND (attr) >= 0xffffffff)
19067     {
19068       complaint
19069         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19070          hex_string (DW_UNSND (attr)));
19071       DW_UNSND (attr) = 0;
19072     }
19073
19074   return info_ptr;
19075 }
19076
19077 /* Read an attribute described by an abbreviated attribute.  */
19078
19079 static const gdb_byte *
19080 read_attribute (const struct die_reader_specs *reader,
19081                 struct attribute *attr, struct attr_abbrev *abbrev,
19082                 const gdb_byte *info_ptr)
19083 {
19084   attr->name = abbrev->name;
19085   return read_attribute_value (reader, attr, abbrev->form,
19086                                abbrev->implicit_const, info_ptr);
19087 }
19088
19089 /* Read dwarf information from a buffer.  */
19090
19091 static unsigned int
19092 read_1_byte (bfd *abfd, const gdb_byte *buf)
19093 {
19094   return bfd_get_8 (abfd, buf);
19095 }
19096
19097 static int
19098 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19099 {
19100   return bfd_get_signed_8 (abfd, buf);
19101 }
19102
19103 static unsigned int
19104 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19105 {
19106   return bfd_get_16 (abfd, buf);
19107 }
19108
19109 static int
19110 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19111 {
19112   return bfd_get_signed_16 (abfd, buf);
19113 }
19114
19115 static unsigned int
19116 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19117 {
19118   return bfd_get_32 (abfd, buf);
19119 }
19120
19121 static int
19122 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19123 {
19124   return bfd_get_signed_32 (abfd, buf);
19125 }
19126
19127 static ULONGEST
19128 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19129 {
19130   return bfd_get_64 (abfd, buf);
19131 }
19132
19133 static CORE_ADDR
19134 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19135               unsigned int *bytes_read)
19136 {
19137   struct comp_unit_head *cu_header = &cu->header;
19138   CORE_ADDR retval = 0;
19139
19140   if (cu_header->signed_addr_p)
19141     {
19142       switch (cu_header->addr_size)
19143         {
19144         case 2:
19145           retval = bfd_get_signed_16 (abfd, buf);
19146           break;
19147         case 4:
19148           retval = bfd_get_signed_32 (abfd, buf);
19149           break;
19150         case 8:
19151           retval = bfd_get_signed_64 (abfd, buf);
19152           break;
19153         default:
19154           internal_error (__FILE__, __LINE__,
19155                           _("read_address: bad switch, signed [in module %s]"),
19156                           bfd_get_filename (abfd));
19157         }
19158     }
19159   else
19160     {
19161       switch (cu_header->addr_size)
19162         {
19163         case 2:
19164           retval = bfd_get_16 (abfd, buf);
19165           break;
19166         case 4:
19167           retval = bfd_get_32 (abfd, buf);
19168           break;
19169         case 8:
19170           retval = bfd_get_64 (abfd, buf);
19171           break;
19172         default:
19173           internal_error (__FILE__, __LINE__,
19174                           _("read_address: bad switch, "
19175                             "unsigned [in module %s]"),
19176                           bfd_get_filename (abfd));
19177         }
19178     }
19179
19180   *bytes_read = cu_header->addr_size;
19181   return retval;
19182 }
19183
19184 /* Read the initial length from a section.  The (draft) DWARF 3
19185    specification allows the initial length to take up either 4 bytes
19186    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19187    bytes describe the length and all offsets will be 8 bytes in length
19188    instead of 4.
19189
19190    An older, non-standard 64-bit format is also handled by this
19191    function.  The older format in question stores the initial length
19192    as an 8-byte quantity without an escape value.  Lengths greater
19193    than 2^32 aren't very common which means that the initial 4 bytes
19194    is almost always zero.  Since a length value of zero doesn't make
19195    sense for the 32-bit format, this initial zero can be considered to
19196    be an escape value which indicates the presence of the older 64-bit
19197    format.  As written, the code can't detect (old format) lengths
19198    greater than 4GB.  If it becomes necessary to handle lengths
19199    somewhat larger than 4GB, we could allow other small values (such
19200    as the non-sensical values of 1, 2, and 3) to also be used as
19201    escape values indicating the presence of the old format.
19202
19203    The value returned via bytes_read should be used to increment the
19204    relevant pointer after calling read_initial_length().
19205
19206    [ Note:  read_initial_length() and read_offset() are based on the
19207      document entitled "DWARF Debugging Information Format", revision
19208      3, draft 8, dated November 19, 2001.  This document was obtained
19209      from:
19210
19211         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19212
19213      This document is only a draft and is subject to change.  (So beware.)
19214
19215      Details regarding the older, non-standard 64-bit format were
19216      determined empirically by examining 64-bit ELF files produced by
19217      the SGI toolchain on an IRIX 6.5 machine.
19218
19219      - Kevin, July 16, 2002
19220    ] */
19221
19222 static LONGEST
19223 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19224 {
19225   LONGEST length = bfd_get_32 (abfd, buf);
19226
19227   if (length == 0xffffffff)
19228     {
19229       length = bfd_get_64 (abfd, buf + 4);
19230       *bytes_read = 12;
19231     }
19232   else if (length == 0)
19233     {
19234       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19235       length = bfd_get_64 (abfd, buf);
19236       *bytes_read = 8;
19237     }
19238   else
19239     {
19240       *bytes_read = 4;
19241     }
19242
19243   return length;
19244 }
19245
19246 /* Cover function for read_initial_length.
19247    Returns the length of the object at BUF, and stores the size of the
19248    initial length in *BYTES_READ and stores the size that offsets will be in
19249    *OFFSET_SIZE.
19250    If the initial length size is not equivalent to that specified in
19251    CU_HEADER then issue a complaint.
19252    This is useful when reading non-comp-unit headers.  */
19253
19254 static LONGEST
19255 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19256                                         const struct comp_unit_head *cu_header,
19257                                         unsigned int *bytes_read,
19258                                         unsigned int *offset_size)
19259 {
19260   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19261
19262   gdb_assert (cu_header->initial_length_size == 4
19263               || cu_header->initial_length_size == 8
19264               || cu_header->initial_length_size == 12);
19265
19266   if (cu_header->initial_length_size != *bytes_read)
19267     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19268
19269   *offset_size = (*bytes_read == 4) ? 4 : 8;
19270   return length;
19271 }
19272
19273 /* Read an offset from the data stream.  The size of the offset is
19274    given by cu_header->offset_size.  */
19275
19276 static LONGEST
19277 read_offset (bfd *abfd, const gdb_byte *buf,
19278              const struct comp_unit_head *cu_header,
19279              unsigned int *bytes_read)
19280 {
19281   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19282
19283   *bytes_read = cu_header->offset_size;
19284   return offset;
19285 }
19286
19287 /* Read an offset from the data stream.  */
19288
19289 static LONGEST
19290 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19291 {
19292   LONGEST retval = 0;
19293
19294   switch (offset_size)
19295     {
19296     case 4:
19297       retval = bfd_get_32 (abfd, buf);
19298       break;
19299     case 8:
19300       retval = bfd_get_64 (abfd, buf);
19301       break;
19302     default:
19303       internal_error (__FILE__, __LINE__,
19304                       _("read_offset_1: bad switch [in module %s]"),
19305                       bfd_get_filename (abfd));
19306     }
19307
19308   return retval;
19309 }
19310
19311 static const gdb_byte *
19312 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19313 {
19314   /* If the size of a host char is 8 bits, we can return a pointer
19315      to the buffer, otherwise we have to copy the data to a buffer
19316      allocated on the temporary obstack.  */
19317   gdb_assert (HOST_CHAR_BIT == 8);
19318   return buf;
19319 }
19320
19321 static const char *
19322 read_direct_string (bfd *abfd, const gdb_byte *buf,
19323                     unsigned int *bytes_read_ptr)
19324 {
19325   /* If the size of a host char is 8 bits, we can return a pointer
19326      to the string, otherwise we have to copy the string to a buffer
19327      allocated on the temporary obstack.  */
19328   gdb_assert (HOST_CHAR_BIT == 8);
19329   if (*buf == '\0')
19330     {
19331       *bytes_read_ptr = 1;
19332       return NULL;
19333     }
19334   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19335   return (const char *) buf;
19336 }
19337
19338 /* Return pointer to string at section SECT offset STR_OFFSET with error
19339    reporting strings FORM_NAME and SECT_NAME.  */
19340
19341 static const char *
19342 read_indirect_string_at_offset_from (struct objfile *objfile,
19343                                      bfd *abfd, LONGEST str_offset,
19344                                      struct dwarf2_section_info *sect,
19345                                      const char *form_name,
19346                                      const char *sect_name)
19347 {
19348   dwarf2_read_section (objfile, sect);
19349   if (sect->buffer == NULL)
19350     error (_("%s used without %s section [in module %s]"),
19351            form_name, sect_name, bfd_get_filename (abfd));
19352   if (str_offset >= sect->size)
19353     error (_("%s pointing outside of %s section [in module %s]"),
19354            form_name, sect_name, bfd_get_filename (abfd));
19355   gdb_assert (HOST_CHAR_BIT == 8);
19356   if (sect->buffer[str_offset] == '\0')
19357     return NULL;
19358   return (const char *) (sect->buffer + str_offset);
19359 }
19360
19361 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19362
19363 static const char *
19364 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19365                                 bfd *abfd, LONGEST str_offset)
19366 {
19367   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19368                                               abfd, str_offset,
19369                                               &dwarf2_per_objfile->str,
19370                                               "DW_FORM_strp", ".debug_str");
19371 }
19372
19373 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19374
19375 static const char *
19376 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19377                                      bfd *abfd, LONGEST str_offset)
19378 {
19379   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19380                                               abfd, str_offset,
19381                                               &dwarf2_per_objfile->line_str,
19382                                               "DW_FORM_line_strp",
19383                                               ".debug_line_str");
19384 }
19385
19386 /* Read a string at offset STR_OFFSET in the .debug_str section from
19387    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19388    the string consists of a single NUL byte, return NULL; otherwise
19389    return a pointer to the string.  */
19390
19391 static const char *
19392 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19393                                LONGEST str_offset)
19394 {
19395   dwarf2_read_section (objfile, &dwz->str);
19396
19397   if (dwz->str.buffer == NULL)
19398     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19399              "section [in module %s]"),
19400            bfd_get_filename (dwz->dwz_bfd));
19401   if (str_offset >= dwz->str.size)
19402     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19403              ".debug_str section [in module %s]"),
19404            bfd_get_filename (dwz->dwz_bfd));
19405   gdb_assert (HOST_CHAR_BIT == 8);
19406   if (dwz->str.buffer[str_offset] == '\0')
19407     return NULL;
19408   return (const char *) (dwz->str.buffer + str_offset);
19409 }
19410
19411 /* Return pointer to string at .debug_str offset as read from BUF.
19412    BUF is assumed to be in a compilation unit described by CU_HEADER.
19413    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19414
19415 static const char *
19416 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19417                       const gdb_byte *buf,
19418                       const struct comp_unit_head *cu_header,
19419                       unsigned int *bytes_read_ptr)
19420 {
19421   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19422
19423   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19424 }
19425
19426 /* Return pointer to string at .debug_line_str offset as read from BUF.
19427    BUF is assumed to be in a compilation unit described by CU_HEADER.
19428    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19429
19430 static const char *
19431 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19432                            bfd *abfd, const gdb_byte *buf,
19433                            const struct comp_unit_head *cu_header,
19434                            unsigned int *bytes_read_ptr)
19435 {
19436   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19437
19438   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19439                                               str_offset);
19440 }
19441
19442 ULONGEST
19443 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19444                           unsigned int *bytes_read_ptr)
19445 {
19446   ULONGEST result;
19447   unsigned int num_read;
19448   int shift;
19449   unsigned char byte;
19450
19451   result = 0;
19452   shift = 0;
19453   num_read = 0;
19454   while (1)
19455     {
19456       byte = bfd_get_8 (abfd, buf);
19457       buf++;
19458       num_read++;
19459       result |= ((ULONGEST) (byte & 127) << shift);
19460       if ((byte & 128) == 0)
19461         {
19462           break;
19463         }
19464       shift += 7;
19465     }
19466   *bytes_read_ptr = num_read;
19467   return result;
19468 }
19469
19470 static LONGEST
19471 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19472                     unsigned int *bytes_read_ptr)
19473 {
19474   LONGEST result;
19475   int shift, num_read;
19476   unsigned char byte;
19477
19478   result = 0;
19479   shift = 0;
19480   num_read = 0;
19481   while (1)
19482     {
19483       byte = bfd_get_8 (abfd, buf);
19484       buf++;
19485       num_read++;
19486       result |= ((LONGEST) (byte & 127) << shift);
19487       shift += 7;
19488       if ((byte & 128) == 0)
19489         {
19490           break;
19491         }
19492     }
19493   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19494     result |= -(((LONGEST) 1) << shift);
19495   *bytes_read_ptr = num_read;
19496   return result;
19497 }
19498
19499 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19500    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19501    ADDR_SIZE is the size of addresses from the CU header.  */
19502
19503 static CORE_ADDR
19504 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19505                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19506 {
19507   struct objfile *objfile = dwarf2_per_objfile->objfile;
19508   bfd *abfd = objfile->obfd;
19509   const gdb_byte *info_ptr;
19510
19511   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19512   if (dwarf2_per_objfile->addr.buffer == NULL)
19513     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19514            objfile_name (objfile));
19515   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19516     error (_("DW_FORM_addr_index pointing outside of "
19517              ".debug_addr section [in module %s]"),
19518            objfile_name (objfile));
19519   info_ptr = (dwarf2_per_objfile->addr.buffer
19520               + addr_base + addr_index * addr_size);
19521   if (addr_size == 4)
19522     return bfd_get_32 (abfd, info_ptr);
19523   else
19524     return bfd_get_64 (abfd, info_ptr);
19525 }
19526
19527 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19528
19529 static CORE_ADDR
19530 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19531 {
19532   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19533                             cu->addr_base, cu->header.addr_size);
19534 }
19535
19536 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19537
19538 static CORE_ADDR
19539 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19540                              unsigned int *bytes_read)
19541 {
19542   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19543   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19544
19545   return read_addr_index (cu, addr_index);
19546 }
19547
19548 /* Data structure to pass results from dwarf2_read_addr_index_reader
19549    back to dwarf2_read_addr_index.  */
19550
19551 struct dwarf2_read_addr_index_data
19552 {
19553   ULONGEST addr_base;
19554   int addr_size;
19555 };
19556
19557 /* die_reader_func for dwarf2_read_addr_index.  */
19558
19559 static void
19560 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19561                                const gdb_byte *info_ptr,
19562                                struct die_info *comp_unit_die,
19563                                int has_children,
19564                                void *data)
19565 {
19566   struct dwarf2_cu *cu = reader->cu;
19567   struct dwarf2_read_addr_index_data *aidata =
19568     (struct dwarf2_read_addr_index_data *) data;
19569
19570   aidata->addr_base = cu->addr_base;
19571   aidata->addr_size = cu->header.addr_size;
19572 }
19573
19574 /* Given an index in .debug_addr, fetch the value.
19575    NOTE: This can be called during dwarf expression evaluation,
19576    long after the debug information has been read, and thus per_cu->cu
19577    may no longer exist.  */
19578
19579 CORE_ADDR
19580 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19581                         unsigned int addr_index)
19582 {
19583   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19584   struct dwarf2_cu *cu = per_cu->cu;
19585   ULONGEST addr_base;
19586   int addr_size;
19587
19588   /* We need addr_base and addr_size.
19589      If we don't have PER_CU->cu, we have to get it.
19590      Nasty, but the alternative is storing the needed info in PER_CU,
19591      which at this point doesn't seem justified: it's not clear how frequently
19592      it would get used and it would increase the size of every PER_CU.
19593      Entry points like dwarf2_per_cu_addr_size do a similar thing
19594      so we're not in uncharted territory here.
19595      Alas we need to be a bit more complicated as addr_base is contained
19596      in the DIE.
19597
19598      We don't need to read the entire CU(/TU).
19599      We just need the header and top level die.
19600
19601      IWBN to use the aging mechanism to let us lazily later discard the CU.
19602      For now we skip this optimization.  */
19603
19604   if (cu != NULL)
19605     {
19606       addr_base = cu->addr_base;
19607       addr_size = cu->header.addr_size;
19608     }
19609   else
19610     {
19611       struct dwarf2_read_addr_index_data aidata;
19612
19613       /* Note: We can't use init_cutu_and_read_dies_simple here,
19614          we need addr_base.  */
19615       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19616                                dwarf2_read_addr_index_reader, &aidata);
19617       addr_base = aidata.addr_base;
19618       addr_size = aidata.addr_size;
19619     }
19620
19621   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19622                             addr_size);
19623 }
19624
19625 /* Given a DW_FORM_GNU_str_index, fetch the string.
19626    This is only used by the Fission support.  */
19627
19628 static const char *
19629 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19630 {
19631   struct dwarf2_cu *cu = reader->cu;
19632   struct dwarf2_per_objfile *dwarf2_per_objfile
19633     = cu->per_cu->dwarf2_per_objfile;
19634   struct objfile *objfile = dwarf2_per_objfile->objfile;
19635   const char *objf_name = objfile_name (objfile);
19636   bfd *abfd = objfile->obfd;
19637   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19638   struct dwarf2_section_info *str_offsets_section =
19639     &reader->dwo_file->sections.str_offsets;
19640   const gdb_byte *info_ptr;
19641   ULONGEST str_offset;
19642   static const char form_name[] = "DW_FORM_GNU_str_index";
19643
19644   dwarf2_read_section (objfile, str_section);
19645   dwarf2_read_section (objfile, str_offsets_section);
19646   if (str_section->buffer == NULL)
19647     error (_("%s used without .debug_str.dwo section"
19648              " in CU at offset %s [in module %s]"),
19649            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19650   if (str_offsets_section->buffer == NULL)
19651     error (_("%s used without .debug_str_offsets.dwo section"
19652              " in CU at offset %s [in module %s]"),
19653            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19654   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19655     error (_("%s pointing outside of .debug_str_offsets.dwo"
19656              " section in CU at offset %s [in module %s]"),
19657            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19658   info_ptr = (str_offsets_section->buffer
19659               + str_index * cu->header.offset_size);
19660   if (cu->header.offset_size == 4)
19661     str_offset = bfd_get_32 (abfd, info_ptr);
19662   else
19663     str_offset = bfd_get_64 (abfd, info_ptr);
19664   if (str_offset >= str_section->size)
19665     error (_("Offset from %s pointing outside of"
19666              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19667            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19668   return (const char *) (str_section->buffer + str_offset);
19669 }
19670
19671 /* Return the length of an LEB128 number in BUF.  */
19672
19673 static int
19674 leb128_size (const gdb_byte *buf)
19675 {
19676   const gdb_byte *begin = buf;
19677   gdb_byte byte;
19678
19679   while (1)
19680     {
19681       byte = *buf++;
19682       if ((byte & 128) == 0)
19683         return buf - begin;
19684     }
19685 }
19686
19687 static void
19688 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19689 {
19690   switch (lang)
19691     {
19692     case DW_LANG_C89:
19693     case DW_LANG_C99:
19694     case DW_LANG_C11:
19695     case DW_LANG_C:
19696     case DW_LANG_UPC:
19697       cu->language = language_c;
19698       break;
19699     case DW_LANG_Java:
19700     case DW_LANG_C_plus_plus:
19701     case DW_LANG_C_plus_plus_11:
19702     case DW_LANG_C_plus_plus_14:
19703       cu->language = language_cplus;
19704       break;
19705     case DW_LANG_D:
19706       cu->language = language_d;
19707       break;
19708     case DW_LANG_Fortran77:
19709     case DW_LANG_Fortran90:
19710     case DW_LANG_Fortran95:
19711     case DW_LANG_Fortran03:
19712     case DW_LANG_Fortran08:
19713       cu->language = language_fortran;
19714       break;
19715     case DW_LANG_Go:
19716       cu->language = language_go;
19717       break;
19718     case DW_LANG_Mips_Assembler:
19719       cu->language = language_asm;
19720       break;
19721     case DW_LANG_Ada83:
19722     case DW_LANG_Ada95:
19723       cu->language = language_ada;
19724       break;
19725     case DW_LANG_Modula2:
19726       cu->language = language_m2;
19727       break;
19728     case DW_LANG_Pascal83:
19729       cu->language = language_pascal;
19730       break;
19731     case DW_LANG_ObjC:
19732       cu->language = language_objc;
19733       break;
19734     case DW_LANG_Rust:
19735     case DW_LANG_Rust_old:
19736       cu->language = language_rust;
19737       break;
19738     case DW_LANG_Cobol74:
19739     case DW_LANG_Cobol85:
19740     default:
19741       cu->language = language_minimal;
19742       break;
19743     }
19744   cu->language_defn = language_def (cu->language);
19745 }
19746
19747 /* Return the named attribute or NULL if not there.  */
19748
19749 static struct attribute *
19750 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19751 {
19752   for (;;)
19753     {
19754       unsigned int i;
19755       struct attribute *spec = NULL;
19756
19757       for (i = 0; i < die->num_attrs; ++i)
19758         {
19759           if (die->attrs[i].name == name)
19760             return &die->attrs[i];
19761           if (die->attrs[i].name == DW_AT_specification
19762               || die->attrs[i].name == DW_AT_abstract_origin)
19763             spec = &die->attrs[i];
19764         }
19765
19766       if (!spec)
19767         break;
19768
19769       die = follow_die_ref (die, spec, &cu);
19770     }
19771
19772   return NULL;
19773 }
19774
19775 /* Return the named attribute or NULL if not there,
19776    but do not follow DW_AT_specification, etc.
19777    This is for use in contexts where we're reading .debug_types dies.
19778    Following DW_AT_specification, DW_AT_abstract_origin will take us
19779    back up the chain, and we want to go down.  */
19780
19781 static struct attribute *
19782 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19783 {
19784   unsigned int i;
19785
19786   for (i = 0; i < die->num_attrs; ++i)
19787     if (die->attrs[i].name == name)
19788       return &die->attrs[i];
19789
19790   return NULL;
19791 }
19792
19793 /* Return the string associated with a string-typed attribute, or NULL if it
19794    is either not found or is of an incorrect type.  */
19795
19796 static const char *
19797 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19798 {
19799   struct attribute *attr;
19800   const char *str = NULL;
19801
19802   attr = dwarf2_attr (die, name, cu);
19803
19804   if (attr != NULL)
19805     {
19806       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19807           || attr->form == DW_FORM_string
19808           || attr->form == DW_FORM_GNU_str_index
19809           || attr->form == DW_FORM_GNU_strp_alt)
19810         str = DW_STRING (attr);
19811       else
19812         complaint (_("string type expected for attribute %s for "
19813                      "DIE at %s in module %s"),
19814                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19815                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19816     }
19817
19818   return str;
19819 }
19820
19821 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19822    and holds a non-zero value.  This function should only be used for
19823    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19824
19825 static int
19826 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19827 {
19828   struct attribute *attr = dwarf2_attr (die, name, cu);
19829
19830   return (attr && DW_UNSND (attr));
19831 }
19832
19833 static int
19834 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19835 {
19836   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19837      which value is non-zero.  However, we have to be careful with
19838      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19839      (via dwarf2_flag_true_p) follows this attribute.  So we may
19840      end up accidently finding a declaration attribute that belongs
19841      to a different DIE referenced by the specification attribute,
19842      even though the given DIE does not have a declaration attribute.  */
19843   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19844           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19845 }
19846
19847 /* Return the die giving the specification for DIE, if there is
19848    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19849    containing the return value on output.  If there is no
19850    specification, but there is an abstract origin, that is
19851    returned.  */
19852
19853 static struct die_info *
19854 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19855 {
19856   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19857                                              *spec_cu);
19858
19859   if (spec_attr == NULL)
19860     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19861
19862   if (spec_attr == NULL)
19863     return NULL;
19864   else
19865     return follow_die_ref (die, spec_attr, spec_cu);
19866 }
19867
19868 /* Stub for free_line_header to match void * callback types.  */
19869
19870 static void
19871 free_line_header_voidp (void *arg)
19872 {
19873   struct line_header *lh = (struct line_header *) arg;
19874
19875   delete lh;
19876 }
19877
19878 void
19879 line_header::add_include_dir (const char *include_dir)
19880 {
19881   if (dwarf_line_debug >= 2)
19882     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19883                         include_dirs.size () + 1, include_dir);
19884
19885   include_dirs.push_back (include_dir);
19886 }
19887
19888 void
19889 line_header::add_file_name (const char *name,
19890                             dir_index d_index,
19891                             unsigned int mod_time,
19892                             unsigned int length)
19893 {
19894   if (dwarf_line_debug >= 2)
19895     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19896                         (unsigned) file_names.size () + 1, name);
19897
19898   file_names.emplace_back (name, d_index, mod_time, length);
19899 }
19900
19901 /* A convenience function to find the proper .debug_line section for a CU.  */
19902
19903 static struct dwarf2_section_info *
19904 get_debug_line_section (struct dwarf2_cu *cu)
19905 {
19906   struct dwarf2_section_info *section;
19907   struct dwarf2_per_objfile *dwarf2_per_objfile
19908     = cu->per_cu->dwarf2_per_objfile;
19909
19910   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19911      DWO file.  */
19912   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19913     section = &cu->dwo_unit->dwo_file->sections.line;
19914   else if (cu->per_cu->is_dwz)
19915     {
19916       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19917
19918       section = &dwz->line;
19919     }
19920   else
19921     section = &dwarf2_per_objfile->line;
19922
19923   return section;
19924 }
19925
19926 /* Read directory or file name entry format, starting with byte of
19927    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19928    entries count and the entries themselves in the described entry
19929    format.  */
19930
19931 static void
19932 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
19933                         bfd *abfd, const gdb_byte **bufp,
19934                         struct line_header *lh,
19935                         const struct comp_unit_head *cu_header,
19936                         void (*callback) (struct line_header *lh,
19937                                           const char *name,
19938                                           dir_index d_index,
19939                                           unsigned int mod_time,
19940                                           unsigned int length))
19941 {
19942   gdb_byte format_count, formati;
19943   ULONGEST data_count, datai;
19944   const gdb_byte *buf = *bufp;
19945   const gdb_byte *format_header_data;
19946   unsigned int bytes_read;
19947
19948   format_count = read_1_byte (abfd, buf);
19949   buf += 1;
19950   format_header_data = buf;
19951   for (formati = 0; formati < format_count; formati++)
19952     {
19953       read_unsigned_leb128 (abfd, buf, &bytes_read);
19954       buf += bytes_read;
19955       read_unsigned_leb128 (abfd, buf, &bytes_read);
19956       buf += bytes_read;
19957     }
19958
19959   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
19960   buf += bytes_read;
19961   for (datai = 0; datai < data_count; datai++)
19962     {
19963       const gdb_byte *format = format_header_data;
19964       struct file_entry fe;
19965
19966       for (formati = 0; formati < format_count; formati++)
19967         {
19968           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
19969           format += bytes_read;
19970
19971           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
19972           format += bytes_read;
19973
19974           gdb::optional<const char *> string;
19975           gdb::optional<unsigned int> uint;
19976
19977           switch (form)
19978             {
19979             case DW_FORM_string:
19980               string.emplace (read_direct_string (abfd, buf, &bytes_read));
19981               buf += bytes_read;
19982               break;
19983
19984             case DW_FORM_line_strp:
19985               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
19986                                                          abfd, buf,
19987                                                          cu_header,
19988                                                          &bytes_read));
19989               buf += bytes_read;
19990               break;
19991
19992             case DW_FORM_data1:
19993               uint.emplace (read_1_byte (abfd, buf));
19994               buf += 1;
19995               break;
19996
19997             case DW_FORM_data2:
19998               uint.emplace (read_2_bytes (abfd, buf));
19999               buf += 2;
20000               break;
20001
20002             case DW_FORM_data4:
20003               uint.emplace (read_4_bytes (abfd, buf));
20004               buf += 4;
20005               break;
20006
20007             case DW_FORM_data8:
20008               uint.emplace (read_8_bytes (abfd, buf));
20009               buf += 8;
20010               break;
20011
20012             case DW_FORM_udata:
20013               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20014               buf += bytes_read;
20015               break;
20016
20017             case DW_FORM_block:
20018               /* It is valid only for DW_LNCT_timestamp which is ignored by
20019                  current GDB.  */
20020               break;
20021             }
20022
20023           switch (content_type)
20024             {
20025             case DW_LNCT_path:
20026               if (string.has_value ())
20027                 fe.name = *string;
20028               break;
20029             case DW_LNCT_directory_index:
20030               if (uint.has_value ())
20031                 fe.d_index = (dir_index) *uint;
20032               break;
20033             case DW_LNCT_timestamp:
20034               if (uint.has_value ())
20035                 fe.mod_time = *uint;
20036               break;
20037             case DW_LNCT_size:
20038               if (uint.has_value ())
20039                 fe.length = *uint;
20040               break;
20041             case DW_LNCT_MD5:
20042               break;
20043             default:
20044               complaint (_("Unknown format content type %s"),
20045                          pulongest (content_type));
20046             }
20047         }
20048
20049       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20050     }
20051
20052   *bufp = buf;
20053 }
20054
20055 /* Read the statement program header starting at OFFSET in
20056    .debug_line, or .debug_line.dwo.  Return a pointer
20057    to a struct line_header, allocated using xmalloc.
20058    Returns NULL if there is a problem reading the header, e.g., if it
20059    has a version we don't understand.
20060
20061    NOTE: the strings in the include directory and file name tables of
20062    the returned object point into the dwarf line section buffer,
20063    and must not be freed.  */
20064
20065 static line_header_up
20066 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20067 {
20068   const gdb_byte *line_ptr;
20069   unsigned int bytes_read, offset_size;
20070   int i;
20071   const char *cur_dir, *cur_file;
20072   struct dwarf2_section_info *section;
20073   bfd *abfd;
20074   struct dwarf2_per_objfile *dwarf2_per_objfile
20075     = cu->per_cu->dwarf2_per_objfile;
20076
20077   section = get_debug_line_section (cu);
20078   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20079   if (section->buffer == NULL)
20080     {
20081       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20082         complaint (_("missing .debug_line.dwo section"));
20083       else
20084         complaint (_("missing .debug_line section"));
20085       return 0;
20086     }
20087
20088   /* We can't do this until we know the section is non-empty.
20089      Only then do we know we have such a section.  */
20090   abfd = get_section_bfd_owner (section);
20091
20092   /* Make sure that at least there's room for the total_length field.
20093      That could be 12 bytes long, but we're just going to fudge that.  */
20094   if (to_underlying (sect_off) + 4 >= section->size)
20095     {
20096       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20097       return 0;
20098     }
20099
20100   line_header_up lh (new line_header ());
20101
20102   lh->sect_off = sect_off;
20103   lh->offset_in_dwz = cu->per_cu->is_dwz;
20104
20105   line_ptr = section->buffer + to_underlying (sect_off);
20106
20107   /* Read in the header.  */
20108   lh->total_length =
20109     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20110                                             &bytes_read, &offset_size);
20111   line_ptr += bytes_read;
20112   if (line_ptr + lh->total_length > (section->buffer + section->size))
20113     {
20114       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20115       return 0;
20116     }
20117   lh->statement_program_end = line_ptr + lh->total_length;
20118   lh->version = read_2_bytes (abfd, line_ptr);
20119   line_ptr += 2;
20120   if (lh->version > 5)
20121     {
20122       /* This is a version we don't understand.  The format could have
20123          changed in ways we don't handle properly so just punt.  */
20124       complaint (_("unsupported version in .debug_line section"));
20125       return NULL;
20126     }
20127   if (lh->version >= 5)
20128     {
20129       gdb_byte segment_selector_size;
20130
20131       /* Skip address size.  */
20132       read_1_byte (abfd, line_ptr);
20133       line_ptr += 1;
20134
20135       segment_selector_size = read_1_byte (abfd, line_ptr);
20136       line_ptr += 1;
20137       if (segment_selector_size != 0)
20138         {
20139           complaint (_("unsupported segment selector size %u "
20140                        "in .debug_line section"),
20141                      segment_selector_size);
20142           return NULL;
20143         }
20144     }
20145   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20146   line_ptr += offset_size;
20147   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20148   line_ptr += 1;
20149   if (lh->version >= 4)
20150     {
20151       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20152       line_ptr += 1;
20153     }
20154   else
20155     lh->maximum_ops_per_instruction = 1;
20156
20157   if (lh->maximum_ops_per_instruction == 0)
20158     {
20159       lh->maximum_ops_per_instruction = 1;
20160       complaint (_("invalid maximum_ops_per_instruction "
20161                    "in `.debug_line' section"));
20162     }
20163
20164   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20165   line_ptr += 1;
20166   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20167   line_ptr += 1;
20168   lh->line_range = read_1_byte (abfd, line_ptr);
20169   line_ptr += 1;
20170   lh->opcode_base = read_1_byte (abfd, line_ptr);
20171   line_ptr += 1;
20172   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20173
20174   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20175   for (i = 1; i < lh->opcode_base; ++i)
20176     {
20177       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20178       line_ptr += 1;
20179     }
20180
20181   if (lh->version >= 5)
20182     {
20183       /* Read directory table.  */
20184       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20185                               &cu->header,
20186                               [] (struct line_header *lh, const char *name,
20187                                   dir_index d_index, unsigned int mod_time,
20188                                   unsigned int length)
20189         {
20190           lh->add_include_dir (name);
20191         });
20192
20193       /* Read file name table.  */
20194       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20195                               &cu->header,
20196                               [] (struct line_header *lh, const char *name,
20197                                   dir_index d_index, unsigned int mod_time,
20198                                   unsigned int length)
20199         {
20200           lh->add_file_name (name, d_index, mod_time, length);
20201         });
20202     }
20203   else
20204     {
20205       /* Read directory table.  */
20206       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20207         {
20208           line_ptr += bytes_read;
20209           lh->add_include_dir (cur_dir);
20210         }
20211       line_ptr += bytes_read;
20212
20213       /* Read file name table.  */
20214       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20215         {
20216           unsigned int mod_time, length;
20217           dir_index d_index;
20218
20219           line_ptr += bytes_read;
20220           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20221           line_ptr += bytes_read;
20222           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20223           line_ptr += bytes_read;
20224           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20225           line_ptr += bytes_read;
20226
20227           lh->add_file_name (cur_file, d_index, mod_time, length);
20228         }
20229       line_ptr += bytes_read;
20230     }
20231   lh->statement_program_start = line_ptr;
20232
20233   if (line_ptr > (section->buffer + section->size))
20234     complaint (_("line number info header doesn't "
20235                  "fit in `.debug_line' section"));
20236
20237   return lh;
20238 }
20239
20240 /* Subroutine of dwarf_decode_lines to simplify it.
20241    Return the file name of the psymtab for included file FILE_INDEX
20242    in line header LH of PST.
20243    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20244    If space for the result is malloc'd, *NAME_HOLDER will be set.
20245    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20246
20247 static const char *
20248 psymtab_include_file_name (const struct line_header *lh, int file_index,
20249                            const struct partial_symtab *pst,
20250                            const char *comp_dir,
20251                            gdb::unique_xmalloc_ptr<char> *name_holder)
20252 {
20253   const file_entry &fe = lh->file_names[file_index];
20254   const char *include_name = fe.name;
20255   const char *include_name_to_compare = include_name;
20256   const char *pst_filename;
20257   int file_is_pst;
20258
20259   const char *dir_name = fe.include_dir (lh);
20260
20261   gdb::unique_xmalloc_ptr<char> hold_compare;
20262   if (!IS_ABSOLUTE_PATH (include_name)
20263       && (dir_name != NULL || comp_dir != NULL))
20264     {
20265       /* Avoid creating a duplicate psymtab for PST.
20266          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20267          Before we do the comparison, however, we need to account
20268          for DIR_NAME and COMP_DIR.
20269          First prepend dir_name (if non-NULL).  If we still don't
20270          have an absolute path prepend comp_dir (if non-NULL).
20271          However, the directory we record in the include-file's
20272          psymtab does not contain COMP_DIR (to match the
20273          corresponding symtab(s)).
20274
20275          Example:
20276
20277          bash$ cd /tmp
20278          bash$ gcc -g ./hello.c
20279          include_name = "hello.c"
20280          dir_name = "."
20281          DW_AT_comp_dir = comp_dir = "/tmp"
20282          DW_AT_name = "./hello.c"
20283
20284       */
20285
20286       if (dir_name != NULL)
20287         {
20288           name_holder->reset (concat (dir_name, SLASH_STRING,
20289                                       include_name, (char *) NULL));
20290           include_name = name_holder->get ();
20291           include_name_to_compare = include_name;
20292         }
20293       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20294         {
20295           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20296                                       include_name, (char *) NULL));
20297           include_name_to_compare = hold_compare.get ();
20298         }
20299     }
20300
20301   pst_filename = pst->filename;
20302   gdb::unique_xmalloc_ptr<char> copied_name;
20303   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20304     {
20305       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20306                                  pst_filename, (char *) NULL));
20307       pst_filename = copied_name.get ();
20308     }
20309
20310   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20311
20312   if (file_is_pst)
20313     return NULL;
20314   return include_name;
20315 }
20316
20317 /* State machine to track the state of the line number program.  */
20318
20319 class lnp_state_machine
20320 {
20321 public:
20322   /* Initialize a machine state for the start of a line number
20323      program.  */
20324   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20325                      bool record_lines_p);
20326
20327   file_entry *current_file ()
20328   {
20329     /* lh->file_names is 0-based, but the file name numbers in the
20330        statement program are 1-based.  */
20331     return m_line_header->file_name_at (m_file);
20332   }
20333
20334   /* Record the line in the state machine.  END_SEQUENCE is true if
20335      we're processing the end of a sequence.  */
20336   void record_line (bool end_sequence);
20337
20338   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20339      nop-out rest of the lines in this sequence.  */
20340   void check_line_address (struct dwarf2_cu *cu,
20341                            const gdb_byte *line_ptr,
20342                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20343
20344   void handle_set_discriminator (unsigned int discriminator)
20345   {
20346     m_discriminator = discriminator;
20347     m_line_has_non_zero_discriminator |= discriminator != 0;
20348   }
20349
20350   /* Handle DW_LNE_set_address.  */
20351   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20352   {
20353     m_op_index = 0;
20354     address += baseaddr;
20355     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20356   }
20357
20358   /* Handle DW_LNS_advance_pc.  */
20359   void handle_advance_pc (CORE_ADDR adjust);
20360
20361   /* Handle a special opcode.  */
20362   void handle_special_opcode (unsigned char op_code);
20363
20364   /* Handle DW_LNS_advance_line.  */
20365   void handle_advance_line (int line_delta)
20366   {
20367     advance_line (line_delta);
20368   }
20369
20370   /* Handle DW_LNS_set_file.  */
20371   void handle_set_file (file_name_index file);
20372
20373   /* Handle DW_LNS_negate_stmt.  */
20374   void handle_negate_stmt ()
20375   {
20376     m_is_stmt = !m_is_stmt;
20377   }
20378
20379   /* Handle DW_LNS_const_add_pc.  */
20380   void handle_const_add_pc ();
20381
20382   /* Handle DW_LNS_fixed_advance_pc.  */
20383   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20384   {
20385     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20386     m_op_index = 0;
20387   }
20388
20389   /* Handle DW_LNS_copy.  */
20390   void handle_copy ()
20391   {
20392     record_line (false);
20393     m_discriminator = 0;
20394   }
20395
20396   /* Handle DW_LNE_end_sequence.  */
20397   void handle_end_sequence ()
20398   {
20399     m_currently_recording_lines = true;
20400   }
20401
20402 private:
20403   /* Advance the line by LINE_DELTA.  */
20404   void advance_line (int line_delta)
20405   {
20406     m_line += line_delta;
20407
20408     if (line_delta != 0)
20409       m_line_has_non_zero_discriminator = m_discriminator != 0;
20410   }
20411
20412   struct dwarf2_cu *m_cu;
20413
20414   gdbarch *m_gdbarch;
20415
20416   /* True if we're recording lines.
20417      Otherwise we're building partial symtabs and are just interested in
20418      finding include files mentioned by the line number program.  */
20419   bool m_record_lines_p;
20420
20421   /* The line number header.  */
20422   line_header *m_line_header;
20423
20424   /* These are part of the standard DWARF line number state machine,
20425      and initialized according to the DWARF spec.  */
20426
20427   unsigned char m_op_index = 0;
20428   /* The line table index (1-based) of the current file.  */
20429   file_name_index m_file = (file_name_index) 1;
20430   unsigned int m_line = 1;
20431
20432   /* These are initialized in the constructor.  */
20433
20434   CORE_ADDR m_address;
20435   bool m_is_stmt;
20436   unsigned int m_discriminator;
20437
20438   /* Additional bits of state we need to track.  */
20439
20440   /* The last file that we called dwarf2_start_subfile for.
20441      This is only used for TLLs.  */
20442   unsigned int m_last_file = 0;
20443   /* The last file a line number was recorded for.  */
20444   struct subfile *m_last_subfile = NULL;
20445
20446   /* When true, record the lines we decode.  */
20447   bool m_currently_recording_lines = false;
20448
20449   /* The last line number that was recorded, used to coalesce
20450      consecutive entries for the same line.  This can happen, for
20451      example, when discriminators are present.  PR 17276.  */
20452   unsigned int m_last_line = 0;
20453   bool m_line_has_non_zero_discriminator = false;
20454 };
20455
20456 void
20457 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20458 {
20459   CORE_ADDR addr_adj = (((m_op_index + adjust)
20460                          / m_line_header->maximum_ops_per_instruction)
20461                         * m_line_header->minimum_instruction_length);
20462   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20463   m_op_index = ((m_op_index + adjust)
20464                 % m_line_header->maximum_ops_per_instruction);
20465 }
20466
20467 void
20468 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20469 {
20470   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20471   CORE_ADDR addr_adj = (((m_op_index
20472                           + (adj_opcode / m_line_header->line_range))
20473                          / m_line_header->maximum_ops_per_instruction)
20474                         * m_line_header->minimum_instruction_length);
20475   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20476   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20477                 % m_line_header->maximum_ops_per_instruction);
20478
20479   int line_delta = (m_line_header->line_base
20480                     + (adj_opcode % m_line_header->line_range));
20481   advance_line (line_delta);
20482   record_line (false);
20483   m_discriminator = 0;
20484 }
20485
20486 void
20487 lnp_state_machine::handle_set_file (file_name_index file)
20488 {
20489   m_file = file;
20490
20491   const file_entry *fe = current_file ();
20492   if (fe == NULL)
20493     dwarf2_debug_line_missing_file_complaint ();
20494   else if (m_record_lines_p)
20495     {
20496       const char *dir = fe->include_dir (m_line_header);
20497
20498       m_last_subfile = m_cu->builder->get_current_subfile ();
20499       m_line_has_non_zero_discriminator = m_discriminator != 0;
20500       dwarf2_start_subfile (m_cu, fe->name, dir);
20501     }
20502 }
20503
20504 void
20505 lnp_state_machine::handle_const_add_pc ()
20506 {
20507   CORE_ADDR adjust
20508     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20509
20510   CORE_ADDR addr_adj
20511     = (((m_op_index + adjust)
20512         / m_line_header->maximum_ops_per_instruction)
20513        * m_line_header->minimum_instruction_length);
20514
20515   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20516   m_op_index = ((m_op_index + adjust)
20517                 % m_line_header->maximum_ops_per_instruction);
20518 }
20519
20520 /* Return non-zero if we should add LINE to the line number table.
20521    LINE is the line to add, LAST_LINE is the last line that was added,
20522    LAST_SUBFILE is the subfile for LAST_LINE.
20523    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20524    had a non-zero discriminator.
20525
20526    We have to be careful in the presence of discriminators.
20527    E.g., for this line:
20528
20529      for (i = 0; i < 100000; i++);
20530
20531    clang can emit four line number entries for that one line,
20532    each with a different discriminator.
20533    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20534
20535    However, we want gdb to coalesce all four entries into one.
20536    Otherwise the user could stepi into the middle of the line and
20537    gdb would get confused about whether the pc really was in the
20538    middle of the line.
20539
20540    Things are further complicated by the fact that two consecutive
20541    line number entries for the same line is a heuristic used by gcc
20542    to denote the end of the prologue.  So we can't just discard duplicate
20543    entries, we have to be selective about it.  The heuristic we use is
20544    that we only collapse consecutive entries for the same line if at least
20545    one of those entries has a non-zero discriminator.  PR 17276.
20546
20547    Note: Addresses in the line number state machine can never go backwards
20548    within one sequence, thus this coalescing is ok.  */
20549
20550 static int
20551 dwarf_record_line_p (struct dwarf2_cu *cu,
20552                      unsigned int line, unsigned int last_line,
20553                      int line_has_non_zero_discriminator,
20554                      struct subfile *last_subfile)
20555 {
20556   if (cu->builder->get_current_subfile () != last_subfile)
20557     return 1;
20558   if (line != last_line)
20559     return 1;
20560   /* Same line for the same file that we've seen already.
20561      As a last check, for pr 17276, only record the line if the line
20562      has never had a non-zero discriminator.  */
20563   if (!line_has_non_zero_discriminator)
20564     return 1;
20565   return 0;
20566 }
20567
20568 /* Use the CU's builder to record line number LINE beginning at
20569    address ADDRESS in the line table of subfile SUBFILE.  */
20570
20571 static void
20572 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20573                      unsigned int line, CORE_ADDR address,
20574                      struct dwarf2_cu *cu)
20575 {
20576   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20577
20578   if (dwarf_line_debug)
20579     {
20580       fprintf_unfiltered (gdb_stdlog,
20581                           "Recording line %u, file %s, address %s\n",
20582                           line, lbasename (subfile->name),
20583                           paddress (gdbarch, address));
20584     }
20585
20586   if (cu != nullptr)
20587     cu->builder->record_line (subfile, line, addr);
20588 }
20589
20590 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20591    Mark the end of a set of line number records.
20592    The arguments are the same as for dwarf_record_line_1.
20593    If SUBFILE is NULL the request is ignored.  */
20594
20595 static void
20596 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20597                    CORE_ADDR address, struct dwarf2_cu *cu)
20598 {
20599   if (subfile == NULL)
20600     return;
20601
20602   if (dwarf_line_debug)
20603     {
20604       fprintf_unfiltered (gdb_stdlog,
20605                           "Finishing current line, file %s, address %s\n",
20606                           lbasename (subfile->name),
20607                           paddress (gdbarch, address));
20608     }
20609
20610   dwarf_record_line_1 (gdbarch, subfile, 0, address, cu);
20611 }
20612
20613 void
20614 lnp_state_machine::record_line (bool end_sequence)
20615 {
20616   if (dwarf_line_debug)
20617     {
20618       fprintf_unfiltered (gdb_stdlog,
20619                           "Processing actual line %u: file %u,"
20620                           " address %s, is_stmt %u, discrim %u\n",
20621                           m_line, to_underlying (m_file),
20622                           paddress (m_gdbarch, m_address),
20623                           m_is_stmt, m_discriminator);
20624     }
20625
20626   file_entry *fe = current_file ();
20627
20628   if (fe == NULL)
20629     dwarf2_debug_line_missing_file_complaint ();
20630   /* For now we ignore lines not starting on an instruction boundary.
20631      But not when processing end_sequence for compatibility with the
20632      previous version of the code.  */
20633   else if (m_op_index == 0 || end_sequence)
20634     {
20635       fe->included_p = 1;
20636       if (m_record_lines_p && m_is_stmt)
20637         {
20638           if (m_last_subfile != m_cu->builder->get_current_subfile ()
20639               || end_sequence)
20640             {
20641               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
20642                                  m_currently_recording_lines ? m_cu : nullptr);
20643             }
20644
20645           if (!end_sequence)
20646             {
20647               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
20648                                        m_line_has_non_zero_discriminator,
20649                                        m_last_subfile))
20650                 {
20651                   dwarf_record_line_1 (m_gdbarch,
20652                                        m_cu->builder->get_current_subfile (),
20653                                        m_line, m_address,
20654                                        m_currently_recording_lines ? m_cu : nullptr);
20655                 }
20656               m_last_subfile = m_cu->builder->get_current_subfile ();
20657               m_last_line = m_line;
20658             }
20659         }
20660     }
20661 }
20662
20663 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
20664                                       line_header *lh, bool record_lines_p)
20665 {
20666   m_cu = cu;
20667   m_gdbarch = arch;
20668   m_record_lines_p = record_lines_p;
20669   m_line_header = lh;
20670
20671   m_currently_recording_lines = true;
20672
20673   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20674      was a line entry for it so that the backend has a chance to adjust it
20675      and also record it in case it needs it.  This is currently used by MIPS
20676      code, cf. `mips_adjust_dwarf2_line'.  */
20677   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20678   m_is_stmt = lh->default_is_stmt;
20679   m_discriminator = 0;
20680 }
20681
20682 void
20683 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20684                                        const gdb_byte *line_ptr,
20685                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20686 {
20687   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20688      the pc range of the CU.  However, we restrict the test to only ADDRESS
20689      values of zero to preserve GDB's previous behaviour which is to handle
20690      the specific case of a function being GC'd by the linker.  */
20691
20692   if (address == 0 && address < unrelocated_lowpc)
20693     {
20694       /* This line table is for a function which has been
20695          GCd by the linker.  Ignore it.  PR gdb/12528 */
20696
20697       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20698       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20699
20700       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20701                  line_offset, objfile_name (objfile));
20702       m_currently_recording_lines = false;
20703       /* Note: m_currently_recording_lines is left as false until we see
20704          DW_LNE_end_sequence.  */
20705     }
20706 }
20707
20708 /* Subroutine of dwarf_decode_lines to simplify it.
20709    Process the line number information in LH.
20710    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20711    program in order to set included_p for every referenced header.  */
20712
20713 static void
20714 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20715                       const int decode_for_pst_p, CORE_ADDR lowpc)
20716 {
20717   const gdb_byte *line_ptr, *extended_end;
20718   const gdb_byte *line_end;
20719   unsigned int bytes_read, extended_len;
20720   unsigned char op_code, extended_op;
20721   CORE_ADDR baseaddr;
20722   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20723   bfd *abfd = objfile->obfd;
20724   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20725   /* True if we're recording line info (as opposed to building partial
20726      symtabs and just interested in finding include files mentioned by
20727      the line number program).  */
20728   bool record_lines_p = !decode_for_pst_p;
20729
20730   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20731
20732   line_ptr = lh->statement_program_start;
20733   line_end = lh->statement_program_end;
20734
20735   /* Read the statement sequences until there's nothing left.  */
20736   while (line_ptr < line_end)
20737     {
20738       /* The DWARF line number program state machine.  Reset the state
20739          machine at the start of each sequence.  */
20740       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
20741       bool end_sequence = false;
20742
20743       if (record_lines_p)
20744         {
20745           /* Start a subfile for the current file of the state
20746              machine.  */
20747           const file_entry *fe = state_machine.current_file ();
20748
20749           if (fe != NULL)
20750             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
20751         }
20752
20753       /* Decode the table.  */
20754       while (line_ptr < line_end && !end_sequence)
20755         {
20756           op_code = read_1_byte (abfd, line_ptr);
20757           line_ptr += 1;
20758
20759           if (op_code >= lh->opcode_base)
20760             {
20761               /* Special opcode.  */
20762               state_machine.handle_special_opcode (op_code);
20763             }
20764           else switch (op_code)
20765             {
20766             case DW_LNS_extended_op:
20767               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20768                                                    &bytes_read);
20769               line_ptr += bytes_read;
20770               extended_end = line_ptr + extended_len;
20771               extended_op = read_1_byte (abfd, line_ptr);
20772               line_ptr += 1;
20773               switch (extended_op)
20774                 {
20775                 case DW_LNE_end_sequence:
20776                   state_machine.handle_end_sequence ();
20777                   end_sequence = true;
20778                   break;
20779                 case DW_LNE_set_address:
20780                   {
20781                     CORE_ADDR address
20782                       = read_address (abfd, line_ptr, cu, &bytes_read);
20783                     line_ptr += bytes_read;
20784
20785                     state_machine.check_line_address (cu, line_ptr,
20786                                                       lowpc - baseaddr, address);
20787                     state_machine.handle_set_address (baseaddr, address);
20788                   }
20789                   break;
20790                 case DW_LNE_define_file:
20791                   {
20792                     const char *cur_file;
20793                     unsigned int mod_time, length;
20794                     dir_index dindex;
20795
20796                     cur_file = read_direct_string (abfd, line_ptr,
20797                                                    &bytes_read);
20798                     line_ptr += bytes_read;
20799                     dindex = (dir_index)
20800                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20801                     line_ptr += bytes_read;
20802                     mod_time =
20803                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20804                     line_ptr += bytes_read;
20805                     length =
20806                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20807                     line_ptr += bytes_read;
20808                     lh->add_file_name (cur_file, dindex, mod_time, length);
20809                   }
20810                   break;
20811                 case DW_LNE_set_discriminator:
20812                   {
20813                     /* The discriminator is not interesting to the
20814                        debugger; just ignore it.  We still need to
20815                        check its value though:
20816                        if there are consecutive entries for the same
20817                        (non-prologue) line we want to coalesce them.
20818                        PR 17276.  */
20819                     unsigned int discr
20820                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20821                     line_ptr += bytes_read;
20822
20823                     state_machine.handle_set_discriminator (discr);
20824                   }
20825                   break;
20826                 default:
20827                   complaint (_("mangled .debug_line section"));
20828                   return;
20829                 }
20830               /* Make sure that we parsed the extended op correctly.  If e.g.
20831                  we expected a different address size than the producer used,
20832                  we may have read the wrong number of bytes.  */
20833               if (line_ptr != extended_end)
20834                 {
20835                   complaint (_("mangled .debug_line section"));
20836                   return;
20837                 }
20838               break;
20839             case DW_LNS_copy:
20840               state_machine.handle_copy ();
20841               break;
20842             case DW_LNS_advance_pc:
20843               {
20844                 CORE_ADDR adjust
20845                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20846                 line_ptr += bytes_read;
20847
20848                 state_machine.handle_advance_pc (adjust);
20849               }
20850               break;
20851             case DW_LNS_advance_line:
20852               {
20853                 int line_delta
20854                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20855                 line_ptr += bytes_read;
20856
20857                 state_machine.handle_advance_line (line_delta);
20858               }
20859               break;
20860             case DW_LNS_set_file:
20861               {
20862                 file_name_index file
20863                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20864                                                             &bytes_read);
20865                 line_ptr += bytes_read;
20866
20867                 state_machine.handle_set_file (file);
20868               }
20869               break;
20870             case DW_LNS_set_column:
20871               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20872               line_ptr += bytes_read;
20873               break;
20874             case DW_LNS_negate_stmt:
20875               state_machine.handle_negate_stmt ();
20876               break;
20877             case DW_LNS_set_basic_block:
20878               break;
20879             /* Add to the address register of the state machine the
20880                address increment value corresponding to special opcode
20881                255.  I.e., this value is scaled by the minimum
20882                instruction length since special opcode 255 would have
20883                scaled the increment.  */
20884             case DW_LNS_const_add_pc:
20885               state_machine.handle_const_add_pc ();
20886               break;
20887             case DW_LNS_fixed_advance_pc:
20888               {
20889                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20890                 line_ptr += 2;
20891
20892                 state_machine.handle_fixed_advance_pc (addr_adj);
20893               }
20894               break;
20895             default:
20896               {
20897                 /* Unknown standard opcode, ignore it.  */
20898                 int i;
20899
20900                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20901                   {
20902                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20903                     line_ptr += bytes_read;
20904                   }
20905               }
20906             }
20907         }
20908
20909       if (!end_sequence)
20910         dwarf2_debug_line_missing_end_sequence_complaint ();
20911
20912       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20913          in which case we still finish recording the last line).  */
20914       state_machine.record_line (true);
20915     }
20916 }
20917
20918 /* Decode the Line Number Program (LNP) for the given line_header
20919    structure and CU.  The actual information extracted and the type
20920    of structures created from the LNP depends on the value of PST.
20921
20922    1. If PST is NULL, then this procedure uses the data from the program
20923       to create all necessary symbol tables, and their linetables.
20924
20925    2. If PST is not NULL, this procedure reads the program to determine
20926       the list of files included by the unit represented by PST, and
20927       builds all the associated partial symbol tables.
20928
20929    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20930    It is used for relative paths in the line table.
20931    NOTE: When processing partial symtabs (pst != NULL),
20932    comp_dir == pst->dirname.
20933
20934    NOTE: It is important that psymtabs have the same file name (via strcmp)
20935    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20936    symtab we don't use it in the name of the psymtabs we create.
20937    E.g. expand_line_sal requires this when finding psymtabs to expand.
20938    A good testcase for this is mb-inline.exp.
20939
20940    LOWPC is the lowest address in CU (or 0 if not known).
20941
20942    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20943    for its PC<->lines mapping information.  Otherwise only the filename
20944    table is read in.  */
20945
20946 static void
20947 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20948                     struct dwarf2_cu *cu, struct partial_symtab *pst,
20949                     CORE_ADDR lowpc, int decode_mapping)
20950 {
20951   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20952   const int decode_for_pst_p = (pst != NULL);
20953
20954   if (decode_mapping)
20955     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
20956
20957   if (decode_for_pst_p)
20958     {
20959       int file_index;
20960
20961       /* Now that we're done scanning the Line Header Program, we can
20962          create the psymtab of each included file.  */
20963       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
20964         if (lh->file_names[file_index].included_p == 1)
20965           {
20966             gdb::unique_xmalloc_ptr<char> name_holder;
20967             const char *include_name =
20968               psymtab_include_file_name (lh, file_index, pst, comp_dir,
20969                                          &name_holder);
20970             if (include_name != NULL)
20971               dwarf2_create_include_psymtab (include_name, pst, objfile);
20972           }
20973     }
20974   else
20975     {
20976       /* Make sure a symtab is created for every file, even files
20977          which contain only variables (i.e. no code with associated
20978          line numbers).  */
20979       struct compunit_symtab *cust = cu->builder->get_compunit_symtab ();
20980       int i;
20981
20982       for (i = 0; i < lh->file_names.size (); i++)
20983         {
20984           file_entry &fe = lh->file_names[i];
20985
20986           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
20987
20988           if (cu->builder->get_current_subfile ()->symtab == NULL)
20989             {
20990               cu->builder->get_current_subfile ()->symtab
20991                 = allocate_symtab (cust,
20992                                    cu->builder->get_current_subfile ()->name);
20993             }
20994           fe.symtab = cu->builder->get_current_subfile ()->symtab;
20995         }
20996     }
20997 }
20998
20999 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21000    DIRNAME the name of the source directory which contains FILENAME
21001    or NULL if not known.
21002    This routine tries to keep line numbers from identical absolute and
21003    relative file names in a common subfile.
21004
21005    Using the `list' example from the GDB testsuite, which resides in
21006    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21007    of /srcdir/list0.c yields the following debugging information for list0.c:
21008
21009    DW_AT_name:          /srcdir/list0.c
21010    DW_AT_comp_dir:      /compdir
21011    files.files[0].name: list0.h
21012    files.files[0].dir:  /srcdir
21013    files.files[1].name: list0.c
21014    files.files[1].dir:  /srcdir
21015
21016    The line number information for list0.c has to end up in a single
21017    subfile, so that `break /srcdir/list0.c:1' works as expected.
21018    start_subfile will ensure that this happens provided that we pass the
21019    concatenation of files.files[1].dir and files.files[1].name as the
21020    subfile's name.  */
21021
21022 static void
21023 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21024                       const char *dirname)
21025 {
21026   char *copy = NULL;
21027
21028   /* In order not to lose the line information directory,
21029      we concatenate it to the filename when it makes sense.
21030      Note that the Dwarf3 standard says (speaking of filenames in line
21031      information): ``The directory index is ignored for file names
21032      that represent full path names''.  Thus ignoring dirname in the
21033      `else' branch below isn't an issue.  */
21034
21035   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21036     {
21037       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21038       filename = copy;
21039     }
21040
21041   cu->builder->start_subfile (filename);
21042
21043   if (copy != NULL)
21044     xfree (copy);
21045 }
21046
21047 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
21048    buildsym_compunit constructor.  */
21049
21050 static struct compunit_symtab *
21051 dwarf2_start_symtab (struct dwarf2_cu *cu,
21052                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21053 {
21054   gdb_assert (cu->builder == nullptr);
21055
21056   cu->builder.reset (new struct buildsym_compunit
21057                      (cu->per_cu->dwarf2_per_objfile->objfile,
21058                       name, comp_dir, cu->language, low_pc));
21059
21060   cu->list_in_scope = cu->builder->get_file_symbols ();
21061
21062   cu->builder->record_debugformat ("DWARF 2");
21063   cu->builder->record_producer (cu->producer);
21064
21065   cu->processing_has_namespace_info = 0;
21066
21067   return cu->builder->get_compunit_symtab ();
21068 }
21069
21070 static void
21071 var_decode_location (struct attribute *attr, struct symbol *sym,
21072                      struct dwarf2_cu *cu)
21073 {
21074   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21075   struct comp_unit_head *cu_header = &cu->header;
21076
21077   /* NOTE drow/2003-01-30: There used to be a comment and some special
21078      code here to turn a symbol with DW_AT_external and a
21079      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21080      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21081      with some versions of binutils) where shared libraries could have
21082      relocations against symbols in their debug information - the
21083      minimal symbol would have the right address, but the debug info
21084      would not.  It's no longer necessary, because we will explicitly
21085      apply relocations when we read in the debug information now.  */
21086
21087   /* A DW_AT_location attribute with no contents indicates that a
21088      variable has been optimized away.  */
21089   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21090     {
21091       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21092       return;
21093     }
21094
21095   /* Handle one degenerate form of location expression specially, to
21096      preserve GDB's previous behavior when section offsets are
21097      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21098      then mark this symbol as LOC_STATIC.  */
21099
21100   if (attr_form_is_block (attr)
21101       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21102            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21103           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21104               && (DW_BLOCK (attr)->size
21105                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21106     {
21107       unsigned int dummy;
21108
21109       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21110         SYMBOL_VALUE_ADDRESS (sym) =
21111           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21112       else
21113         SYMBOL_VALUE_ADDRESS (sym) =
21114           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21115       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21116       fixup_symbol_section (sym, objfile);
21117       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21118                                               SYMBOL_SECTION (sym));
21119       return;
21120     }
21121
21122   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21123      expression evaluator, and use LOC_COMPUTED only when necessary
21124      (i.e. when the value of a register or memory location is
21125      referenced, or a thread-local block, etc.).  Then again, it might
21126      not be worthwhile.  I'm assuming that it isn't unless performance
21127      or memory numbers show me otherwise.  */
21128
21129   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21130
21131   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21132     cu->has_loclist = 1;
21133 }
21134
21135 /* Given a pointer to a DWARF information entry, figure out if we need
21136    to make a symbol table entry for it, and if so, create a new entry
21137    and return a pointer to it.
21138    If TYPE is NULL, determine symbol type from the die, otherwise
21139    used the passed type.
21140    If SPACE is not NULL, use it to hold the new symbol.  If it is
21141    NULL, allocate a new symbol on the objfile's obstack.  */
21142
21143 static struct symbol *
21144 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21145             struct symbol *space)
21146 {
21147   struct dwarf2_per_objfile *dwarf2_per_objfile
21148     = cu->per_cu->dwarf2_per_objfile;
21149   struct objfile *objfile = dwarf2_per_objfile->objfile;
21150   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21151   struct symbol *sym = NULL;
21152   const char *name;
21153   struct attribute *attr = NULL;
21154   struct attribute *attr2 = NULL;
21155   CORE_ADDR baseaddr;
21156   struct pending **list_to_add = NULL;
21157
21158   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21159
21160   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21161
21162   name = dwarf2_name (die, cu);
21163   if (name)
21164     {
21165       const char *linkagename;
21166       int suppress_add = 0;
21167
21168       if (space)
21169         sym = space;
21170       else
21171         sym = allocate_symbol (objfile);
21172       OBJSTAT (objfile, n_syms++);
21173
21174       /* Cache this symbol's name and the name's demangled form (if any).  */
21175       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21176       linkagename = dwarf2_physname (name, die, cu);
21177       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21178
21179       /* Fortran does not have mangling standard and the mangling does differ
21180          between gfortran, iFort etc.  */
21181       if (cu->language == language_fortran
21182           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21183         symbol_set_demangled_name (&(sym->ginfo),
21184                                    dwarf2_full_name (name, die, cu),
21185                                    NULL);
21186
21187       /* Default assumptions.
21188          Use the passed type or decode it from the die.  */
21189       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21190       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21191       if (type != NULL)
21192         SYMBOL_TYPE (sym) = type;
21193       else
21194         SYMBOL_TYPE (sym) = die_type (die, cu);
21195       attr = dwarf2_attr (die,
21196                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21197                           cu);
21198       if (attr)
21199         {
21200           SYMBOL_LINE (sym) = DW_UNSND (attr);
21201         }
21202
21203       attr = dwarf2_attr (die,
21204                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21205                           cu);
21206       if (attr)
21207         {
21208           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21209           struct file_entry *fe;
21210
21211           if (cu->line_header != NULL)
21212             fe = cu->line_header->file_name_at (file_index);
21213           else
21214             fe = NULL;
21215
21216           if (fe == NULL)
21217             complaint (_("file index out of range"));
21218           else
21219             symbol_set_symtab (sym, fe->symtab);
21220         }
21221
21222       switch (die->tag)
21223         {
21224         case DW_TAG_label:
21225           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21226           if (attr)
21227             {
21228               CORE_ADDR addr;
21229
21230               addr = attr_value_as_address (attr);
21231               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21232               SYMBOL_VALUE_ADDRESS (sym) = addr;
21233             }
21234           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21235           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21236           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21237           dw2_add_symbol_to_list (sym, cu->list_in_scope);
21238           break;
21239         case DW_TAG_subprogram:
21240           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21241              finish_block.  */
21242           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21243           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21244           if ((attr2 && (DW_UNSND (attr2) != 0))
21245               || cu->language == language_ada)
21246             {
21247               /* Subprograms marked external are stored as a global symbol.
21248                  Ada subprograms, whether marked external or not, are always
21249                  stored as a global symbol, because we want to be able to
21250                  access them globally.  For instance, we want to be able
21251                  to break on a nested subprogram without having to
21252                  specify the context.  */
21253               list_to_add = cu->builder->get_global_symbols ();
21254             }
21255           else
21256             {
21257               list_to_add = cu->list_in_scope;
21258             }
21259           break;
21260         case DW_TAG_inlined_subroutine:
21261           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21262              finish_block.  */
21263           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21264           SYMBOL_INLINED (sym) = 1;
21265           list_to_add = cu->list_in_scope;
21266           break;
21267         case DW_TAG_template_value_param:
21268           suppress_add = 1;
21269           /* Fall through.  */
21270         case DW_TAG_constant:
21271         case DW_TAG_variable:
21272         case DW_TAG_member:
21273           /* Compilation with minimal debug info may result in
21274              variables with missing type entries.  Change the
21275              misleading `void' type to something sensible.  */
21276           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21277             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21278
21279           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21280           /* In the case of DW_TAG_member, we should only be called for
21281              static const members.  */
21282           if (die->tag == DW_TAG_member)
21283             {
21284               /* dwarf2_add_field uses die_is_declaration,
21285                  so we do the same.  */
21286               gdb_assert (die_is_declaration (die, cu));
21287               gdb_assert (attr);
21288             }
21289           if (attr)
21290             {
21291               dwarf2_const_value (attr, sym, cu);
21292               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21293               if (!suppress_add)
21294                 {
21295                   if (attr2 && (DW_UNSND (attr2) != 0))
21296                     list_to_add = cu->builder->get_global_symbols ();
21297                   else
21298                     list_to_add = cu->list_in_scope;
21299                 }
21300               break;
21301             }
21302           attr = dwarf2_attr (die, DW_AT_location, cu);
21303           if (attr)
21304             {
21305               var_decode_location (attr, sym, cu);
21306               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21307
21308               /* Fortran explicitly imports any global symbols to the local
21309                  scope by DW_TAG_common_block.  */
21310               if (cu->language == language_fortran && die->parent
21311                   && die->parent->tag == DW_TAG_common_block)
21312                 attr2 = NULL;
21313
21314               if (SYMBOL_CLASS (sym) == LOC_STATIC
21315                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21316                   && !dwarf2_per_objfile->has_section_at_zero)
21317                 {
21318                   /* When a static variable is eliminated by the linker,
21319                      the corresponding debug information is not stripped
21320                      out, but the variable address is set to null;
21321                      do not add such variables into symbol table.  */
21322                 }
21323               else if (attr2 && (DW_UNSND (attr2) != 0))
21324                 {
21325                   /* Workaround gfortran PR debug/40040 - it uses
21326                      DW_AT_location for variables in -fPIC libraries which may
21327                      get overriden by other libraries/executable and get
21328                      a different address.  Resolve it by the minimal symbol
21329                      which may come from inferior's executable using copy
21330                      relocation.  Make this workaround only for gfortran as for
21331                      other compilers GDB cannot guess the minimal symbol
21332                      Fortran mangling kind.  */
21333                   if (cu->language == language_fortran && die->parent
21334                       && die->parent->tag == DW_TAG_module
21335                       && cu->producer
21336                       && startswith (cu->producer, "GNU Fortran"))
21337                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21338
21339                   /* A variable with DW_AT_external is never static,
21340                      but it may be block-scoped.  */
21341                   list_to_add
21342                     = (cu->list_in_scope == cu->builder->get_file_symbols ()
21343                        ? cu->builder->get_global_symbols ()
21344                        : cu->list_in_scope);
21345                 }
21346               else
21347                 list_to_add = cu->list_in_scope;
21348             }
21349           else
21350             {
21351               /* We do not know the address of this symbol.
21352                  If it is an external symbol and we have type information
21353                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21354                  The address of the variable will then be determined from
21355                  the minimal symbol table whenever the variable is
21356                  referenced.  */
21357               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21358
21359               /* Fortran explicitly imports any global symbols to the local
21360                  scope by DW_TAG_common_block.  */
21361               if (cu->language == language_fortran && die->parent
21362                   && die->parent->tag == DW_TAG_common_block)
21363                 {
21364                   /* SYMBOL_CLASS doesn't matter here because
21365                      read_common_block is going to reset it.  */
21366                   if (!suppress_add)
21367                     list_to_add = cu->list_in_scope;
21368                 }
21369               else if (attr2 && (DW_UNSND (attr2) != 0)
21370                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21371                 {
21372                   /* A variable with DW_AT_external is never static, but it
21373                      may be block-scoped.  */
21374                   list_to_add
21375                     = (cu->list_in_scope == cu->builder->get_file_symbols ()
21376                        ? cu->builder->get_global_symbols ()
21377                        : cu->list_in_scope);
21378
21379                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21380                 }
21381               else if (!die_is_declaration (die, cu))
21382                 {
21383                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21384                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21385                   if (!suppress_add)
21386                     list_to_add = cu->list_in_scope;
21387                 }
21388             }
21389           break;
21390         case DW_TAG_formal_parameter:
21391           {
21392             /* If we are inside a function, mark this as an argument.  If
21393                not, we might be looking at an argument to an inlined function
21394                when we do not have enough information to show inlined frames;
21395                pretend it's a local variable in that case so that the user can
21396                still see it.  */
21397             struct context_stack *curr
21398               = cu->builder->get_current_context_stack ();
21399             if (curr != nullptr && curr->name != nullptr)
21400               SYMBOL_IS_ARGUMENT (sym) = 1;
21401             attr = dwarf2_attr (die, DW_AT_location, cu);
21402             if (attr)
21403               {
21404                 var_decode_location (attr, sym, cu);
21405               }
21406             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21407             if (attr)
21408               {
21409                 dwarf2_const_value (attr, sym, cu);
21410               }
21411
21412             list_to_add = cu->list_in_scope;
21413           }
21414           break;
21415         case DW_TAG_unspecified_parameters:
21416           /* From varargs functions; gdb doesn't seem to have any
21417              interest in this information, so just ignore it for now.
21418              (FIXME?) */
21419           break;
21420         case DW_TAG_template_type_param:
21421           suppress_add = 1;
21422           /* Fall through.  */
21423         case DW_TAG_class_type:
21424         case DW_TAG_interface_type:
21425         case DW_TAG_structure_type:
21426         case DW_TAG_union_type:
21427         case DW_TAG_set_type:
21428         case DW_TAG_enumeration_type:
21429           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21430           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21431
21432           {
21433             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21434                really ever be static objects: otherwise, if you try
21435                to, say, break of a class's method and you're in a file
21436                which doesn't mention that class, it won't work unless
21437                the check for all static symbols in lookup_symbol_aux
21438                saves you.  See the OtherFileClass tests in
21439                gdb.c++/namespace.exp.  */
21440
21441             if (!suppress_add)
21442               {
21443                 list_to_add
21444                   = (cu->list_in_scope == cu->builder->get_file_symbols ()
21445                      && cu->language == language_cplus
21446                      ? cu->builder->get_global_symbols ()
21447                      : cu->list_in_scope);
21448
21449                 /* The semantics of C++ state that "struct foo {
21450                    ... }" also defines a typedef for "foo".  */
21451                 if (cu->language == language_cplus
21452                     || cu->language == language_ada
21453                     || cu->language == language_d
21454                     || cu->language == language_rust)
21455                   {
21456                     /* The symbol's name is already allocated along
21457                        with this objfile, so we don't need to
21458                        duplicate it for the type.  */
21459                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21460                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21461                   }
21462               }
21463           }
21464           break;
21465         case DW_TAG_typedef:
21466           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21467           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21468           list_to_add = cu->list_in_scope;
21469           break;
21470         case DW_TAG_base_type:
21471         case DW_TAG_subrange_type:
21472           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21473           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21474           list_to_add = cu->list_in_scope;
21475           break;
21476         case DW_TAG_enumerator:
21477           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21478           if (attr)
21479             {
21480               dwarf2_const_value (attr, sym, cu);
21481             }
21482           {
21483             /* NOTE: carlton/2003-11-10: See comment above in the
21484                DW_TAG_class_type, etc. block.  */
21485
21486             list_to_add
21487               = (cu->list_in_scope == cu->builder->get_file_symbols ()
21488                  && cu->language == language_cplus
21489                  ? cu->builder->get_global_symbols ()
21490                  : cu->list_in_scope);
21491           }
21492           break;
21493         case DW_TAG_imported_declaration:
21494         case DW_TAG_namespace:
21495           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21496           list_to_add = cu->builder->get_global_symbols ();
21497           break;
21498         case DW_TAG_module:
21499           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21500           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21501           list_to_add = cu->builder->get_global_symbols ();
21502           break;
21503         case DW_TAG_common_block:
21504           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21505           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21506           dw2_add_symbol_to_list (sym, cu->list_in_scope);
21507           break;
21508         default:
21509           /* Not a tag we recognize.  Hopefully we aren't processing
21510              trash data, but since we must specifically ignore things
21511              we don't recognize, there is nothing else we should do at
21512              this point.  */
21513           complaint (_("unsupported tag: '%s'"),
21514                      dwarf_tag_name (die->tag));
21515           break;
21516         }
21517
21518       if (suppress_add)
21519         {
21520           sym->hash_next = objfile->template_symbols;
21521           objfile->template_symbols = sym;
21522           list_to_add = NULL;
21523         }
21524
21525       if (list_to_add != NULL)
21526         dw2_add_symbol_to_list (sym, list_to_add);
21527
21528       /* For the benefit of old versions of GCC, check for anonymous
21529          namespaces based on the demangled name.  */
21530       if (!cu->processing_has_namespace_info
21531           && cu->language == language_cplus)
21532         cp_scan_for_anonymous_namespaces (cu->builder.get (), sym, objfile);
21533     }
21534   return (sym);
21535 }
21536
21537 /* Given an attr with a DW_FORM_dataN value in host byte order,
21538    zero-extend it as appropriate for the symbol's type.  The DWARF
21539    standard (v4) is not entirely clear about the meaning of using
21540    DW_FORM_dataN for a constant with a signed type, where the type is
21541    wider than the data.  The conclusion of a discussion on the DWARF
21542    list was that this is unspecified.  We choose to always zero-extend
21543    because that is the interpretation long in use by GCC.  */
21544
21545 static gdb_byte *
21546 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21547                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21548 {
21549   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21550   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21551                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21552   LONGEST l = DW_UNSND (attr);
21553
21554   if (bits < sizeof (*value) * 8)
21555     {
21556       l &= ((LONGEST) 1 << bits) - 1;
21557       *value = l;
21558     }
21559   else if (bits == sizeof (*value) * 8)
21560     *value = l;
21561   else
21562     {
21563       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21564       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21565       return bytes;
21566     }
21567
21568   return NULL;
21569 }
21570
21571 /* Read a constant value from an attribute.  Either set *VALUE, or if
21572    the value does not fit in *VALUE, set *BYTES - either already
21573    allocated on the objfile obstack, or newly allocated on OBSTACK,
21574    or, set *BATON, if we translated the constant to a location
21575    expression.  */
21576
21577 static void
21578 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21579                          const char *name, struct obstack *obstack,
21580                          struct dwarf2_cu *cu,
21581                          LONGEST *value, const gdb_byte **bytes,
21582                          struct dwarf2_locexpr_baton **baton)
21583 {
21584   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21585   struct comp_unit_head *cu_header = &cu->header;
21586   struct dwarf_block *blk;
21587   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21588                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21589
21590   *value = 0;
21591   *bytes = NULL;
21592   *baton = NULL;
21593
21594   switch (attr->form)
21595     {
21596     case DW_FORM_addr:
21597     case DW_FORM_GNU_addr_index:
21598       {
21599         gdb_byte *data;
21600
21601         if (TYPE_LENGTH (type) != cu_header->addr_size)
21602           dwarf2_const_value_length_mismatch_complaint (name,
21603                                                         cu_header->addr_size,
21604                                                         TYPE_LENGTH (type));
21605         /* Symbols of this form are reasonably rare, so we just
21606            piggyback on the existing location code rather than writing
21607            a new implementation of symbol_computed_ops.  */
21608         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21609         (*baton)->per_cu = cu->per_cu;
21610         gdb_assert ((*baton)->per_cu);
21611
21612         (*baton)->size = 2 + cu_header->addr_size;
21613         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21614         (*baton)->data = data;
21615
21616         data[0] = DW_OP_addr;
21617         store_unsigned_integer (&data[1], cu_header->addr_size,
21618                                 byte_order, DW_ADDR (attr));
21619         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21620       }
21621       break;
21622     case DW_FORM_string:
21623     case DW_FORM_strp:
21624     case DW_FORM_GNU_str_index:
21625     case DW_FORM_GNU_strp_alt:
21626       /* DW_STRING is already allocated on the objfile obstack, point
21627          directly to it.  */
21628       *bytes = (const gdb_byte *) DW_STRING (attr);
21629       break;
21630     case DW_FORM_block1:
21631     case DW_FORM_block2:
21632     case DW_FORM_block4:
21633     case DW_FORM_block:
21634     case DW_FORM_exprloc:
21635     case DW_FORM_data16:
21636       blk = DW_BLOCK (attr);
21637       if (TYPE_LENGTH (type) != blk->size)
21638         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21639                                                       TYPE_LENGTH (type));
21640       *bytes = blk->data;
21641       break;
21642
21643       /* The DW_AT_const_value attributes are supposed to carry the
21644          symbol's value "represented as it would be on the target
21645          architecture."  By the time we get here, it's already been
21646          converted to host endianness, so we just need to sign- or
21647          zero-extend it as appropriate.  */
21648     case DW_FORM_data1:
21649       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21650       break;
21651     case DW_FORM_data2:
21652       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21653       break;
21654     case DW_FORM_data4:
21655       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21656       break;
21657     case DW_FORM_data8:
21658       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21659       break;
21660
21661     case DW_FORM_sdata:
21662     case DW_FORM_implicit_const:
21663       *value = DW_SND (attr);
21664       break;
21665
21666     case DW_FORM_udata:
21667       *value = DW_UNSND (attr);
21668       break;
21669
21670     default:
21671       complaint (_("unsupported const value attribute form: '%s'"),
21672                  dwarf_form_name (attr->form));
21673       *value = 0;
21674       break;
21675     }
21676 }
21677
21678
21679 /* Copy constant value from an attribute to a symbol.  */
21680
21681 static void
21682 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21683                     struct dwarf2_cu *cu)
21684 {
21685   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21686   LONGEST value;
21687   const gdb_byte *bytes;
21688   struct dwarf2_locexpr_baton *baton;
21689
21690   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21691                            SYMBOL_PRINT_NAME (sym),
21692                            &objfile->objfile_obstack, cu,
21693                            &value, &bytes, &baton);
21694
21695   if (baton != NULL)
21696     {
21697       SYMBOL_LOCATION_BATON (sym) = baton;
21698       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21699     }
21700   else if (bytes != NULL)
21701      {
21702       SYMBOL_VALUE_BYTES (sym) = bytes;
21703       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21704     }
21705   else
21706     {
21707       SYMBOL_VALUE (sym) = value;
21708       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21709     }
21710 }
21711
21712 /* Return the type of the die in question using its DW_AT_type attribute.  */
21713
21714 static struct type *
21715 die_type (struct die_info *die, struct dwarf2_cu *cu)
21716 {
21717   struct attribute *type_attr;
21718
21719   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21720   if (!type_attr)
21721     {
21722       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21723       /* A missing DW_AT_type represents a void type.  */
21724       return objfile_type (objfile)->builtin_void;
21725     }
21726
21727   return lookup_die_type (die, type_attr, cu);
21728 }
21729
21730 /* True iff CU's producer generates GNAT Ada auxiliary information
21731    that allows to find parallel types through that information instead
21732    of having to do expensive parallel lookups by type name.  */
21733
21734 static int
21735 need_gnat_info (struct dwarf2_cu *cu)
21736 {
21737   /* Assume that the Ada compiler was GNAT, which always produces
21738      the auxiliary information.  */
21739   return (cu->language == language_ada);
21740 }
21741
21742 /* Return the auxiliary type of the die in question using its
21743    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21744    attribute is not present.  */
21745
21746 static struct type *
21747 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21748 {
21749   struct attribute *type_attr;
21750
21751   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21752   if (!type_attr)
21753     return NULL;
21754
21755   return lookup_die_type (die, type_attr, cu);
21756 }
21757
21758 /* If DIE has a descriptive_type attribute, then set the TYPE's
21759    descriptive type accordingly.  */
21760
21761 static void
21762 set_descriptive_type (struct type *type, struct die_info *die,
21763                       struct dwarf2_cu *cu)
21764 {
21765   struct type *descriptive_type = die_descriptive_type (die, cu);
21766
21767   if (descriptive_type)
21768     {
21769       ALLOCATE_GNAT_AUX_TYPE (type);
21770       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21771     }
21772 }
21773
21774 /* Return the containing type of the die in question using its
21775    DW_AT_containing_type attribute.  */
21776
21777 static struct type *
21778 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21779 {
21780   struct attribute *type_attr;
21781   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21782
21783   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21784   if (!type_attr)
21785     error (_("Dwarf Error: Problem turning containing type into gdb type "
21786              "[in module %s]"), objfile_name (objfile));
21787
21788   return lookup_die_type (die, type_attr, cu);
21789 }
21790
21791 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21792
21793 static struct type *
21794 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21795 {
21796   struct dwarf2_per_objfile *dwarf2_per_objfile
21797     = cu->per_cu->dwarf2_per_objfile;
21798   struct objfile *objfile = dwarf2_per_objfile->objfile;
21799   char *message, *saved;
21800
21801   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
21802                         objfile_name (objfile),
21803                         sect_offset_str (cu->header.sect_off),
21804                         sect_offset_str (die->sect_off));
21805   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21806                                   message, strlen (message));
21807   xfree (message);
21808
21809   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21810 }
21811
21812 /* Look up the type of DIE in CU using its type attribute ATTR.
21813    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21814    DW_AT_containing_type.
21815    If there is no type substitute an error marker.  */
21816
21817 static struct type *
21818 lookup_die_type (struct die_info *die, const struct attribute *attr,
21819                  struct dwarf2_cu *cu)
21820 {
21821   struct dwarf2_per_objfile *dwarf2_per_objfile
21822     = cu->per_cu->dwarf2_per_objfile;
21823   struct objfile *objfile = dwarf2_per_objfile->objfile;
21824   struct type *this_type;
21825
21826   gdb_assert (attr->name == DW_AT_type
21827               || attr->name == DW_AT_GNAT_descriptive_type
21828               || attr->name == DW_AT_containing_type);
21829
21830   /* First see if we have it cached.  */
21831
21832   if (attr->form == DW_FORM_GNU_ref_alt)
21833     {
21834       struct dwarf2_per_cu_data *per_cu;
21835       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21836
21837       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21838                                                  dwarf2_per_objfile);
21839       this_type = get_die_type_at_offset (sect_off, per_cu);
21840     }
21841   else if (attr_form_is_ref (attr))
21842     {
21843       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21844
21845       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21846     }
21847   else if (attr->form == DW_FORM_ref_sig8)
21848     {
21849       ULONGEST signature = DW_SIGNATURE (attr);
21850
21851       return get_signatured_type (die, signature, cu);
21852     }
21853   else
21854     {
21855       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
21856                    " at %s [in module %s]"),
21857                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21858                  objfile_name (objfile));
21859       return build_error_marker_type (cu, die);
21860     }
21861
21862   /* If not cached we need to read it in.  */
21863
21864   if (this_type == NULL)
21865     {
21866       struct die_info *type_die = NULL;
21867       struct dwarf2_cu *type_cu = cu;
21868
21869       if (attr_form_is_ref (attr))
21870         type_die = follow_die_ref (die, attr, &type_cu);
21871       if (type_die == NULL)
21872         return build_error_marker_type (cu, die);
21873       /* If we find the type now, it's probably because the type came
21874          from an inter-CU reference and the type's CU got expanded before
21875          ours.  */
21876       this_type = read_type_die (type_die, type_cu);
21877     }
21878
21879   /* If we still don't have a type use an error marker.  */
21880
21881   if (this_type == NULL)
21882     return build_error_marker_type (cu, die);
21883
21884   return this_type;
21885 }
21886
21887 /* Return the type in DIE, CU.
21888    Returns NULL for invalid types.
21889
21890    This first does a lookup in die_type_hash,
21891    and only reads the die in if necessary.
21892
21893    NOTE: This can be called when reading in partial or full symbols.  */
21894
21895 static struct type *
21896 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21897 {
21898   struct type *this_type;
21899
21900   this_type = get_die_type (die, cu);
21901   if (this_type)
21902     return this_type;
21903
21904   return read_type_die_1 (die, cu);
21905 }
21906
21907 /* Read the type in DIE, CU.
21908    Returns NULL for invalid types.  */
21909
21910 static struct type *
21911 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21912 {
21913   struct type *this_type = NULL;
21914
21915   switch (die->tag)
21916     {
21917     case DW_TAG_class_type:
21918     case DW_TAG_interface_type:
21919     case DW_TAG_structure_type:
21920     case DW_TAG_union_type:
21921       this_type = read_structure_type (die, cu);
21922       break;
21923     case DW_TAG_enumeration_type:
21924       this_type = read_enumeration_type (die, cu);
21925       break;
21926     case DW_TAG_subprogram:
21927     case DW_TAG_subroutine_type:
21928     case DW_TAG_inlined_subroutine:
21929       this_type = read_subroutine_type (die, cu);
21930       break;
21931     case DW_TAG_array_type:
21932       this_type = read_array_type (die, cu);
21933       break;
21934     case DW_TAG_set_type:
21935       this_type = read_set_type (die, cu);
21936       break;
21937     case DW_TAG_pointer_type:
21938       this_type = read_tag_pointer_type (die, cu);
21939       break;
21940     case DW_TAG_ptr_to_member_type:
21941       this_type = read_tag_ptr_to_member_type (die, cu);
21942       break;
21943     case DW_TAG_reference_type:
21944       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21945       break;
21946     case DW_TAG_rvalue_reference_type:
21947       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21948       break;
21949     case DW_TAG_const_type:
21950       this_type = read_tag_const_type (die, cu);
21951       break;
21952     case DW_TAG_volatile_type:
21953       this_type = read_tag_volatile_type (die, cu);
21954       break;
21955     case DW_TAG_restrict_type:
21956       this_type = read_tag_restrict_type (die, cu);
21957       break;
21958     case DW_TAG_string_type:
21959       this_type = read_tag_string_type (die, cu);
21960       break;
21961     case DW_TAG_typedef:
21962       this_type = read_typedef (die, cu);
21963       break;
21964     case DW_TAG_subrange_type:
21965       this_type = read_subrange_type (die, cu);
21966       break;
21967     case DW_TAG_base_type:
21968       this_type = read_base_type (die, cu);
21969       break;
21970     case DW_TAG_unspecified_type:
21971       this_type = read_unspecified_type (die, cu);
21972       break;
21973     case DW_TAG_namespace:
21974       this_type = read_namespace_type (die, cu);
21975       break;
21976     case DW_TAG_module:
21977       this_type = read_module_type (die, cu);
21978       break;
21979     case DW_TAG_atomic_type:
21980       this_type = read_tag_atomic_type (die, cu);
21981       break;
21982     default:
21983       complaint (_("unexpected tag in read_type_die: '%s'"),
21984                  dwarf_tag_name (die->tag));
21985       break;
21986     }
21987
21988   return this_type;
21989 }
21990
21991 /* See if we can figure out if the class lives in a namespace.  We do
21992    this by looking for a member function; its demangled name will
21993    contain namespace info, if there is any.
21994    Return the computed name or NULL.
21995    Space for the result is allocated on the objfile's obstack.
21996    This is the full-die version of guess_partial_die_structure_name.
21997    In this case we know DIE has no useful parent.  */
21998
21999 static char *
22000 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22001 {
22002   struct die_info *spec_die;
22003   struct dwarf2_cu *spec_cu;
22004   struct die_info *child;
22005   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22006
22007   spec_cu = cu;
22008   spec_die = die_specification (die, &spec_cu);
22009   if (spec_die != NULL)
22010     {
22011       die = spec_die;
22012       cu = spec_cu;
22013     }
22014
22015   for (child = die->child;
22016        child != NULL;
22017        child = child->sibling)
22018     {
22019       if (child->tag == DW_TAG_subprogram)
22020         {
22021           const char *linkage_name = dw2_linkage_name (child, cu);
22022
22023           if (linkage_name != NULL)
22024             {
22025               char *actual_name
22026                 = language_class_name_from_physname (cu->language_defn,
22027                                                      linkage_name);
22028               char *name = NULL;
22029
22030               if (actual_name != NULL)
22031                 {
22032                   const char *die_name = dwarf2_name (die, cu);
22033
22034                   if (die_name != NULL
22035                       && strcmp (die_name, actual_name) != 0)
22036                     {
22037                       /* Strip off the class name from the full name.
22038                          We want the prefix.  */
22039                       int die_name_len = strlen (die_name);
22040                       int actual_name_len = strlen (actual_name);
22041
22042                       /* Test for '::' as a sanity check.  */
22043                       if (actual_name_len > die_name_len + 2
22044                           && actual_name[actual_name_len
22045                                          - die_name_len - 1] == ':')
22046                         name = (char *) obstack_copy0 (
22047                           &objfile->per_bfd->storage_obstack,
22048                           actual_name, actual_name_len - die_name_len - 2);
22049                     }
22050                 }
22051               xfree (actual_name);
22052               return name;
22053             }
22054         }
22055     }
22056
22057   return NULL;
22058 }
22059
22060 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22061    prefix part in such case.  See
22062    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22063
22064 static const char *
22065 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22066 {
22067   struct attribute *attr;
22068   const char *base;
22069
22070   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22071       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22072     return NULL;
22073
22074   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22075     return NULL;
22076
22077   attr = dw2_linkage_name_attr (die, cu);
22078   if (attr == NULL || DW_STRING (attr) == NULL)
22079     return NULL;
22080
22081   /* dwarf2_name had to be already called.  */
22082   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22083
22084   /* Strip the base name, keep any leading namespaces/classes.  */
22085   base = strrchr (DW_STRING (attr), ':');
22086   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22087     return "";
22088
22089   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22090   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22091                                  DW_STRING (attr),
22092                                  &base[-1] - DW_STRING (attr));
22093 }
22094
22095 /* Return the name of the namespace/class that DIE is defined within,
22096    or "" if we can't tell.  The caller should not xfree the result.
22097
22098    For example, if we're within the method foo() in the following
22099    code:
22100
22101    namespace N {
22102      class C {
22103        void foo () {
22104        }
22105      };
22106    }
22107
22108    then determine_prefix on foo's die will return "N::C".  */
22109
22110 static const char *
22111 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22112 {
22113   struct dwarf2_per_objfile *dwarf2_per_objfile
22114     = cu->per_cu->dwarf2_per_objfile;
22115   struct die_info *parent, *spec_die;
22116   struct dwarf2_cu *spec_cu;
22117   struct type *parent_type;
22118   const char *retval;
22119
22120   if (cu->language != language_cplus
22121       && cu->language != language_fortran && cu->language != language_d
22122       && cu->language != language_rust)
22123     return "";
22124
22125   retval = anonymous_struct_prefix (die, cu);
22126   if (retval)
22127     return retval;
22128
22129   /* We have to be careful in the presence of DW_AT_specification.
22130      For example, with GCC 3.4, given the code
22131
22132      namespace N {
22133        void foo() {
22134          // Definition of N::foo.
22135        }
22136      }
22137
22138      then we'll have a tree of DIEs like this:
22139
22140      1: DW_TAG_compile_unit
22141        2: DW_TAG_namespace        // N
22142          3: DW_TAG_subprogram     // declaration of N::foo
22143        4: DW_TAG_subprogram       // definition of N::foo
22144             DW_AT_specification   // refers to die #3
22145
22146      Thus, when processing die #4, we have to pretend that we're in
22147      the context of its DW_AT_specification, namely the contex of die
22148      #3.  */
22149   spec_cu = cu;
22150   spec_die = die_specification (die, &spec_cu);
22151   if (spec_die == NULL)
22152     parent = die->parent;
22153   else
22154     {
22155       parent = spec_die->parent;
22156       cu = spec_cu;
22157     }
22158
22159   if (parent == NULL)
22160     return "";
22161   else if (parent->building_fullname)
22162     {
22163       const char *name;
22164       const char *parent_name;
22165
22166       /* It has been seen on RealView 2.2 built binaries,
22167          DW_TAG_template_type_param types actually _defined_ as
22168          children of the parent class:
22169
22170          enum E {};
22171          template class <class Enum> Class{};
22172          Class<enum E> class_e;
22173
22174          1: DW_TAG_class_type (Class)
22175            2: DW_TAG_enumeration_type (E)
22176              3: DW_TAG_enumerator (enum1:0)
22177              3: DW_TAG_enumerator (enum2:1)
22178              ...
22179            2: DW_TAG_template_type_param
22180               DW_AT_type  DW_FORM_ref_udata (E)
22181
22182          Besides being broken debug info, it can put GDB into an
22183          infinite loop.  Consider:
22184
22185          When we're building the full name for Class<E>, we'll start
22186          at Class, and go look over its template type parameters,
22187          finding E.  We'll then try to build the full name of E, and
22188          reach here.  We're now trying to build the full name of E,
22189          and look over the parent DIE for containing scope.  In the
22190          broken case, if we followed the parent DIE of E, we'd again
22191          find Class, and once again go look at its template type
22192          arguments, etc., etc.  Simply don't consider such parent die
22193          as source-level parent of this die (it can't be, the language
22194          doesn't allow it), and break the loop here.  */
22195       name = dwarf2_name (die, cu);
22196       parent_name = dwarf2_name (parent, cu);
22197       complaint (_("template param type '%s' defined within parent '%s'"),
22198                  name ? name : "<unknown>",
22199                  parent_name ? parent_name : "<unknown>");
22200       return "";
22201     }
22202   else
22203     switch (parent->tag)
22204       {
22205       case DW_TAG_namespace:
22206         parent_type = read_type_die (parent, cu);
22207         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22208            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22209            Work around this problem here.  */
22210         if (cu->language == language_cplus
22211             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22212           return "";
22213         /* We give a name to even anonymous namespaces.  */
22214         return TYPE_NAME (parent_type);
22215       case DW_TAG_class_type:
22216       case DW_TAG_interface_type:
22217       case DW_TAG_structure_type:
22218       case DW_TAG_union_type:
22219       case DW_TAG_module:
22220         parent_type = read_type_die (parent, cu);
22221         if (TYPE_NAME (parent_type) != NULL)
22222           return TYPE_NAME (parent_type);
22223         else
22224           /* An anonymous structure is only allowed non-static data
22225              members; no typedefs, no member functions, et cetera.
22226              So it does not need a prefix.  */
22227           return "";
22228       case DW_TAG_compile_unit:
22229       case DW_TAG_partial_unit:
22230         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22231         if (cu->language == language_cplus
22232             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22233             && die->child != NULL
22234             && (die->tag == DW_TAG_class_type
22235                 || die->tag == DW_TAG_structure_type
22236                 || die->tag == DW_TAG_union_type))
22237           {
22238             char *name = guess_full_die_structure_name (die, cu);
22239             if (name != NULL)
22240               return name;
22241           }
22242         return "";
22243       case DW_TAG_enumeration_type:
22244         parent_type = read_type_die (parent, cu);
22245         if (TYPE_DECLARED_CLASS (parent_type))
22246           {
22247             if (TYPE_NAME (parent_type) != NULL)
22248               return TYPE_NAME (parent_type);
22249             return "";
22250           }
22251         /* Fall through.  */
22252       default:
22253         return determine_prefix (parent, cu);
22254       }
22255 }
22256
22257 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22258    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22259    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22260    an obconcat, otherwise allocate storage for the result.  The CU argument is
22261    used to determine the language and hence, the appropriate separator.  */
22262
22263 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22264
22265 static char *
22266 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22267                  int physname, struct dwarf2_cu *cu)
22268 {
22269   const char *lead = "";
22270   const char *sep;
22271
22272   if (suffix == NULL || suffix[0] == '\0'
22273       || prefix == NULL || prefix[0] == '\0')
22274     sep = "";
22275   else if (cu->language == language_d)
22276     {
22277       /* For D, the 'main' function could be defined in any module, but it
22278          should never be prefixed.  */
22279       if (strcmp (suffix, "D main") == 0)
22280         {
22281           prefix = "";
22282           sep = "";
22283         }
22284       else
22285         sep = ".";
22286     }
22287   else if (cu->language == language_fortran && physname)
22288     {
22289       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22290          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22291
22292       lead = "__";
22293       sep = "_MOD_";
22294     }
22295   else
22296     sep = "::";
22297
22298   if (prefix == NULL)
22299     prefix = "";
22300   if (suffix == NULL)
22301     suffix = "";
22302
22303   if (obs == NULL)
22304     {
22305       char *retval
22306         = ((char *)
22307            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22308
22309       strcpy (retval, lead);
22310       strcat (retval, prefix);
22311       strcat (retval, sep);
22312       strcat (retval, suffix);
22313       return retval;
22314     }
22315   else
22316     {
22317       /* We have an obstack.  */
22318       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22319     }
22320 }
22321
22322 /* Return sibling of die, NULL if no sibling.  */
22323
22324 static struct die_info *
22325 sibling_die (struct die_info *die)
22326 {
22327   return die->sibling;
22328 }
22329
22330 /* Get name of a die, return NULL if not found.  */
22331
22332 static const char *
22333 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22334                           struct obstack *obstack)
22335 {
22336   if (name && cu->language == language_cplus)
22337     {
22338       std::string canon_name = cp_canonicalize_string (name);
22339
22340       if (!canon_name.empty ())
22341         {
22342           if (canon_name != name)
22343             name = (const char *) obstack_copy0 (obstack,
22344                                                  canon_name.c_str (),
22345                                                  canon_name.length ());
22346         }
22347     }
22348
22349   return name;
22350 }
22351
22352 /* Get name of a die, return NULL if not found.
22353    Anonymous namespaces are converted to their magic string.  */
22354
22355 static const char *
22356 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22357 {
22358   struct attribute *attr;
22359   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22360
22361   attr = dwarf2_attr (die, DW_AT_name, cu);
22362   if ((!attr || !DW_STRING (attr))
22363       && die->tag != DW_TAG_namespace
22364       && die->tag != DW_TAG_class_type
22365       && die->tag != DW_TAG_interface_type
22366       && die->tag != DW_TAG_structure_type
22367       && die->tag != DW_TAG_union_type)
22368     return NULL;
22369
22370   switch (die->tag)
22371     {
22372     case DW_TAG_compile_unit:
22373     case DW_TAG_partial_unit:
22374       /* Compilation units have a DW_AT_name that is a filename, not
22375          a source language identifier.  */
22376     case DW_TAG_enumeration_type:
22377     case DW_TAG_enumerator:
22378       /* These tags always have simple identifiers already; no need
22379          to canonicalize them.  */
22380       return DW_STRING (attr);
22381
22382     case DW_TAG_namespace:
22383       if (attr != NULL && DW_STRING (attr) != NULL)
22384         return DW_STRING (attr);
22385       return CP_ANONYMOUS_NAMESPACE_STR;
22386
22387     case DW_TAG_class_type:
22388     case DW_TAG_interface_type:
22389     case DW_TAG_structure_type:
22390     case DW_TAG_union_type:
22391       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22392          structures or unions.  These were of the form "._%d" in GCC 4.1,
22393          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22394          and GCC 4.4.  We work around this problem by ignoring these.  */
22395       if (attr && DW_STRING (attr)
22396           && (startswith (DW_STRING (attr), "._")
22397               || startswith (DW_STRING (attr), "<anonymous")))
22398         return NULL;
22399
22400       /* GCC might emit a nameless typedef that has a linkage name.  See
22401          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22402       if (!attr || DW_STRING (attr) == NULL)
22403         {
22404           char *demangled = NULL;
22405
22406           attr = dw2_linkage_name_attr (die, cu);
22407           if (attr == NULL || DW_STRING (attr) == NULL)
22408             return NULL;
22409
22410           /* Avoid demangling DW_STRING (attr) the second time on a second
22411              call for the same DIE.  */
22412           if (!DW_STRING_IS_CANONICAL (attr))
22413             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22414
22415           if (demangled)
22416             {
22417               const char *base;
22418
22419               /* FIXME: we already did this for the partial symbol... */
22420               DW_STRING (attr)
22421                 = ((const char *)
22422                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22423                                   demangled, strlen (demangled)));
22424               DW_STRING_IS_CANONICAL (attr) = 1;
22425               xfree (demangled);
22426
22427               /* Strip any leading namespaces/classes, keep only the base name.
22428                  DW_AT_name for named DIEs does not contain the prefixes.  */
22429               base = strrchr (DW_STRING (attr), ':');
22430               if (base && base > DW_STRING (attr) && base[-1] == ':')
22431                 return &base[1];
22432               else
22433                 return DW_STRING (attr);
22434             }
22435         }
22436       break;
22437
22438     default:
22439       break;
22440     }
22441
22442   if (!DW_STRING_IS_CANONICAL (attr))
22443     {
22444       DW_STRING (attr)
22445         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22446                                     &objfile->per_bfd->storage_obstack);
22447       DW_STRING_IS_CANONICAL (attr) = 1;
22448     }
22449   return DW_STRING (attr);
22450 }
22451
22452 /* Return the die that this die in an extension of, or NULL if there
22453    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22454    containing the return value on output.  */
22455
22456 static struct die_info *
22457 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22458 {
22459   struct attribute *attr;
22460
22461   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22462   if (attr == NULL)
22463     return NULL;
22464
22465   return follow_die_ref (die, attr, ext_cu);
22466 }
22467
22468 /* Convert a DIE tag into its string name.  */
22469
22470 static const char *
22471 dwarf_tag_name (unsigned tag)
22472 {
22473   const char *name = get_DW_TAG_name (tag);
22474
22475   if (name == NULL)
22476     return "DW_TAG_<unknown>";
22477
22478   return name;
22479 }
22480
22481 /* Convert a DWARF attribute code into its string name.  */
22482
22483 static const char *
22484 dwarf_attr_name (unsigned attr)
22485 {
22486   const char *name;
22487
22488 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22489   if (attr == DW_AT_MIPS_fde)
22490     return "DW_AT_MIPS_fde";
22491 #else
22492   if (attr == DW_AT_HP_block_index)
22493     return "DW_AT_HP_block_index";
22494 #endif
22495
22496   name = get_DW_AT_name (attr);
22497
22498   if (name == NULL)
22499     return "DW_AT_<unknown>";
22500
22501   return name;
22502 }
22503
22504 /* Convert a DWARF value form code into its string name.  */
22505
22506 static const char *
22507 dwarf_form_name (unsigned form)
22508 {
22509   const char *name = get_DW_FORM_name (form);
22510
22511   if (name == NULL)
22512     return "DW_FORM_<unknown>";
22513
22514   return name;
22515 }
22516
22517 static const char *
22518 dwarf_bool_name (unsigned mybool)
22519 {
22520   if (mybool)
22521     return "TRUE";
22522   else
22523     return "FALSE";
22524 }
22525
22526 /* Convert a DWARF type code into its string name.  */
22527
22528 static const char *
22529 dwarf_type_encoding_name (unsigned enc)
22530 {
22531   const char *name = get_DW_ATE_name (enc);
22532
22533   if (name == NULL)
22534     return "DW_ATE_<unknown>";
22535
22536   return name;
22537 }
22538
22539 static void
22540 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22541 {
22542   unsigned int i;
22543
22544   print_spaces (indent, f);
22545   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22546                       dwarf_tag_name (die->tag), die->abbrev,
22547                       sect_offset_str (die->sect_off));
22548
22549   if (die->parent != NULL)
22550     {
22551       print_spaces (indent, f);
22552       fprintf_unfiltered (f, "  parent at offset: %s\n",
22553                           sect_offset_str (die->parent->sect_off));
22554     }
22555
22556   print_spaces (indent, f);
22557   fprintf_unfiltered (f, "  has children: %s\n",
22558            dwarf_bool_name (die->child != NULL));
22559
22560   print_spaces (indent, f);
22561   fprintf_unfiltered (f, "  attributes:\n");
22562
22563   for (i = 0; i < die->num_attrs; ++i)
22564     {
22565       print_spaces (indent, f);
22566       fprintf_unfiltered (f, "    %s (%s) ",
22567                dwarf_attr_name (die->attrs[i].name),
22568                dwarf_form_name (die->attrs[i].form));
22569
22570       switch (die->attrs[i].form)
22571         {
22572         case DW_FORM_addr:
22573         case DW_FORM_GNU_addr_index:
22574           fprintf_unfiltered (f, "address: ");
22575           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22576           break;
22577         case DW_FORM_block2:
22578         case DW_FORM_block4:
22579         case DW_FORM_block:
22580         case DW_FORM_block1:
22581           fprintf_unfiltered (f, "block: size %s",
22582                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22583           break;
22584         case DW_FORM_exprloc:
22585           fprintf_unfiltered (f, "expression: size %s",
22586                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22587           break;
22588         case DW_FORM_data16:
22589           fprintf_unfiltered (f, "constant of 16 bytes");
22590           break;
22591         case DW_FORM_ref_addr:
22592           fprintf_unfiltered (f, "ref address: ");
22593           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22594           break;
22595         case DW_FORM_GNU_ref_alt:
22596           fprintf_unfiltered (f, "alt ref address: ");
22597           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22598           break;
22599         case DW_FORM_ref1:
22600         case DW_FORM_ref2:
22601         case DW_FORM_ref4:
22602         case DW_FORM_ref8:
22603         case DW_FORM_ref_udata:
22604           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22605                               (long) (DW_UNSND (&die->attrs[i])));
22606           break;
22607         case DW_FORM_data1:
22608         case DW_FORM_data2:
22609         case DW_FORM_data4:
22610         case DW_FORM_data8:
22611         case DW_FORM_udata:
22612         case DW_FORM_sdata:
22613           fprintf_unfiltered (f, "constant: %s",
22614                               pulongest (DW_UNSND (&die->attrs[i])));
22615           break;
22616         case DW_FORM_sec_offset:
22617           fprintf_unfiltered (f, "section offset: %s",
22618                               pulongest (DW_UNSND (&die->attrs[i])));
22619           break;
22620         case DW_FORM_ref_sig8:
22621           fprintf_unfiltered (f, "signature: %s",
22622                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22623           break;
22624         case DW_FORM_string:
22625         case DW_FORM_strp:
22626         case DW_FORM_line_strp:
22627         case DW_FORM_GNU_str_index:
22628         case DW_FORM_GNU_strp_alt:
22629           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22630                    DW_STRING (&die->attrs[i])
22631                    ? DW_STRING (&die->attrs[i]) : "",
22632                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22633           break;
22634         case DW_FORM_flag:
22635           if (DW_UNSND (&die->attrs[i]))
22636             fprintf_unfiltered (f, "flag: TRUE");
22637           else
22638             fprintf_unfiltered (f, "flag: FALSE");
22639           break;
22640         case DW_FORM_flag_present:
22641           fprintf_unfiltered (f, "flag: TRUE");
22642           break;
22643         case DW_FORM_indirect:
22644           /* The reader will have reduced the indirect form to
22645              the "base form" so this form should not occur.  */
22646           fprintf_unfiltered (f, 
22647                               "unexpected attribute form: DW_FORM_indirect");
22648           break;
22649         case DW_FORM_implicit_const:
22650           fprintf_unfiltered (f, "constant: %s",
22651                               plongest (DW_SND (&die->attrs[i])));
22652           break;
22653         default:
22654           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22655                    die->attrs[i].form);
22656           break;
22657         }
22658       fprintf_unfiltered (f, "\n");
22659     }
22660 }
22661
22662 static void
22663 dump_die_for_error (struct die_info *die)
22664 {
22665   dump_die_shallow (gdb_stderr, 0, die);
22666 }
22667
22668 static void
22669 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22670 {
22671   int indent = level * 4;
22672
22673   gdb_assert (die != NULL);
22674
22675   if (level >= max_level)
22676     return;
22677
22678   dump_die_shallow (f, indent, die);
22679
22680   if (die->child != NULL)
22681     {
22682       print_spaces (indent, f);
22683       fprintf_unfiltered (f, "  Children:");
22684       if (level + 1 < max_level)
22685         {
22686           fprintf_unfiltered (f, "\n");
22687           dump_die_1 (f, level + 1, max_level, die->child);
22688         }
22689       else
22690         {
22691           fprintf_unfiltered (f,
22692                               " [not printed, max nesting level reached]\n");
22693         }
22694     }
22695
22696   if (die->sibling != NULL && level > 0)
22697     {
22698       dump_die_1 (f, level, max_level, die->sibling);
22699     }
22700 }
22701
22702 /* This is called from the pdie macro in gdbinit.in.
22703    It's not static so gcc will keep a copy callable from gdb.  */
22704
22705 void
22706 dump_die (struct die_info *die, int max_level)
22707 {
22708   dump_die_1 (gdb_stdlog, 0, max_level, die);
22709 }
22710
22711 static void
22712 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22713 {
22714   void **slot;
22715
22716   slot = htab_find_slot_with_hash (cu->die_hash, die,
22717                                    to_underlying (die->sect_off),
22718                                    INSERT);
22719
22720   *slot = die;
22721 }
22722
22723 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22724    required kind.  */
22725
22726 static sect_offset
22727 dwarf2_get_ref_die_offset (const struct attribute *attr)
22728 {
22729   if (attr_form_is_ref (attr))
22730     return (sect_offset) DW_UNSND (attr);
22731
22732   complaint (_("unsupported die ref attribute form: '%s'"),
22733              dwarf_form_name (attr->form));
22734   return {};
22735 }
22736
22737 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22738  * the value held by the attribute is not constant.  */
22739
22740 static LONGEST
22741 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22742 {
22743   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22744     return DW_SND (attr);
22745   else if (attr->form == DW_FORM_udata
22746            || attr->form == DW_FORM_data1
22747            || attr->form == DW_FORM_data2
22748            || attr->form == DW_FORM_data4
22749            || attr->form == DW_FORM_data8)
22750     return DW_UNSND (attr);
22751   else
22752     {
22753       /* For DW_FORM_data16 see attr_form_is_constant.  */
22754       complaint (_("Attribute value is not a constant (%s)"),
22755                  dwarf_form_name (attr->form));
22756       return default_value;
22757     }
22758 }
22759
22760 /* Follow reference or signature attribute ATTR of SRC_DIE.
22761    On entry *REF_CU is the CU of SRC_DIE.
22762    On exit *REF_CU is the CU of the result.  */
22763
22764 static struct die_info *
22765 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22766                        struct dwarf2_cu **ref_cu)
22767 {
22768   struct die_info *die;
22769
22770   if (attr_form_is_ref (attr))
22771     die = follow_die_ref (src_die, attr, ref_cu);
22772   else if (attr->form == DW_FORM_ref_sig8)
22773     die = follow_die_sig (src_die, attr, ref_cu);
22774   else
22775     {
22776       dump_die_for_error (src_die);
22777       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22778              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22779     }
22780
22781   return die;
22782 }
22783
22784 /* Follow reference OFFSET.
22785    On entry *REF_CU is the CU of the source die referencing OFFSET.
22786    On exit *REF_CU is the CU of the result.
22787    Returns NULL if OFFSET is invalid.  */
22788
22789 static struct die_info *
22790 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22791                    struct dwarf2_cu **ref_cu)
22792 {
22793   struct die_info temp_die;
22794   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22795   struct dwarf2_per_objfile *dwarf2_per_objfile
22796     = cu->per_cu->dwarf2_per_objfile;
22797
22798   gdb_assert (cu->per_cu != NULL);
22799
22800   target_cu = cu;
22801
22802   if (cu->per_cu->is_debug_types)
22803     {
22804       /* .debug_types CUs cannot reference anything outside their CU.
22805          If they need to, they have to reference a signatured type via
22806          DW_FORM_ref_sig8.  */
22807       if (!offset_in_cu_p (&cu->header, sect_off))
22808         return NULL;
22809     }
22810   else if (offset_in_dwz != cu->per_cu->is_dwz
22811            || !offset_in_cu_p (&cu->header, sect_off))
22812     {
22813       struct dwarf2_per_cu_data *per_cu;
22814
22815       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22816                                                  dwarf2_per_objfile);
22817
22818       /* If necessary, add it to the queue and load its DIEs.  */
22819       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22820         load_full_comp_unit (per_cu, false, cu->language);
22821
22822       target_cu = per_cu->cu;
22823     }
22824   else if (cu->dies == NULL)
22825     {
22826       /* We're loading full DIEs during partial symbol reading.  */
22827       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22828       load_full_comp_unit (cu->per_cu, false, language_minimal);
22829     }
22830
22831   *ref_cu = target_cu;
22832   temp_die.sect_off = sect_off;
22833   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22834                                                   &temp_die,
22835                                                   to_underlying (sect_off));
22836 }
22837
22838 /* Follow reference attribute ATTR of SRC_DIE.
22839    On entry *REF_CU is the CU of SRC_DIE.
22840    On exit *REF_CU is the CU of the result.  */
22841
22842 static struct die_info *
22843 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22844                 struct dwarf2_cu **ref_cu)
22845 {
22846   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22847   struct dwarf2_cu *cu = *ref_cu;
22848   struct die_info *die;
22849
22850   die = follow_die_offset (sect_off,
22851                            (attr->form == DW_FORM_GNU_ref_alt
22852                             || cu->per_cu->is_dwz),
22853                            ref_cu);
22854   if (!die)
22855     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22856            "at %s [in module %s]"),
22857            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22858            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22859
22860   return die;
22861 }
22862
22863 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22864    Returned value is intended for DW_OP_call*.  Returned
22865    dwarf2_locexpr_baton->data has lifetime of
22866    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22867
22868 struct dwarf2_locexpr_baton
22869 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22870                                struct dwarf2_per_cu_data *per_cu,
22871                                CORE_ADDR (*get_frame_pc) (void *baton),
22872                                void *baton)
22873 {
22874   struct dwarf2_cu *cu;
22875   struct die_info *die;
22876   struct attribute *attr;
22877   struct dwarf2_locexpr_baton retval;
22878   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22879   struct objfile *objfile = dwarf2_per_objfile->objfile;
22880
22881   if (per_cu->cu == NULL)
22882     load_cu (per_cu, false);
22883   cu = per_cu->cu;
22884   if (cu == NULL)
22885     {
22886       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22887          Instead just throw an error, not much else we can do.  */
22888       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22889              sect_offset_str (sect_off), objfile_name (objfile));
22890     }
22891
22892   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22893   if (!die)
22894     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22895            sect_offset_str (sect_off), objfile_name (objfile));
22896
22897   attr = dwarf2_attr (die, DW_AT_location, cu);
22898   if (!attr)
22899     {
22900       /* DWARF: "If there is no such attribute, then there is no effect.".
22901          DATA is ignored if SIZE is 0.  */
22902
22903       retval.data = NULL;
22904       retval.size = 0;
22905     }
22906   else if (attr_form_is_section_offset (attr))
22907     {
22908       struct dwarf2_loclist_baton loclist_baton;
22909       CORE_ADDR pc = (*get_frame_pc) (baton);
22910       size_t size;
22911
22912       fill_in_loclist_baton (cu, &loclist_baton, attr);
22913
22914       retval.data = dwarf2_find_location_expression (&loclist_baton,
22915                                                      &size, pc);
22916       retval.size = size;
22917     }
22918   else
22919     {
22920       if (!attr_form_is_block (attr))
22921         error (_("Dwarf Error: DIE at %s referenced in module %s "
22922                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22923                sect_offset_str (sect_off), objfile_name (objfile));
22924
22925       retval.data = DW_BLOCK (attr)->data;
22926       retval.size = DW_BLOCK (attr)->size;
22927     }
22928   retval.per_cu = cu->per_cu;
22929
22930   age_cached_comp_units (dwarf2_per_objfile);
22931
22932   return retval;
22933 }
22934
22935 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
22936    offset.  */
22937
22938 struct dwarf2_locexpr_baton
22939 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
22940                              struct dwarf2_per_cu_data *per_cu,
22941                              CORE_ADDR (*get_frame_pc) (void *baton),
22942                              void *baton)
22943 {
22944   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
22945
22946   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
22947 }
22948
22949 /* Write a constant of a given type as target-ordered bytes into
22950    OBSTACK.  */
22951
22952 static const gdb_byte *
22953 write_constant_as_bytes (struct obstack *obstack,
22954                          enum bfd_endian byte_order,
22955                          struct type *type,
22956                          ULONGEST value,
22957                          LONGEST *len)
22958 {
22959   gdb_byte *result;
22960
22961   *len = TYPE_LENGTH (type);
22962   result = (gdb_byte *) obstack_alloc (obstack, *len);
22963   store_unsigned_integer (result, *len, byte_order, value);
22964
22965   return result;
22966 }
22967
22968 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
22969    pointer to the constant bytes and set LEN to the length of the
22970    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
22971    does not have a DW_AT_const_value, return NULL.  */
22972
22973 const gdb_byte *
22974 dwarf2_fetch_constant_bytes (sect_offset sect_off,
22975                              struct dwarf2_per_cu_data *per_cu,
22976                              struct obstack *obstack,
22977                              LONGEST *len)
22978 {
22979   struct dwarf2_cu *cu;
22980   struct die_info *die;
22981   struct attribute *attr;
22982   const gdb_byte *result = NULL;
22983   struct type *type;
22984   LONGEST value;
22985   enum bfd_endian byte_order;
22986   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
22987
22988   if (per_cu->cu == NULL)
22989     load_cu (per_cu, false);
22990   cu = per_cu->cu;
22991   if (cu == NULL)
22992     {
22993       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22994          Instead just throw an error, not much else we can do.  */
22995       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22996              sect_offset_str (sect_off), objfile_name (objfile));
22997     }
22998
22999   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23000   if (!die)
23001     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23002            sect_offset_str (sect_off), objfile_name (objfile));
23003
23004   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23005   if (attr == NULL)
23006     return NULL;
23007
23008   byte_order = (bfd_big_endian (objfile->obfd)
23009                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23010
23011   switch (attr->form)
23012     {
23013     case DW_FORM_addr:
23014     case DW_FORM_GNU_addr_index:
23015       {
23016         gdb_byte *tem;
23017
23018         *len = cu->header.addr_size;
23019         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23020         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23021         result = tem;
23022       }
23023       break;
23024     case DW_FORM_string:
23025     case DW_FORM_strp:
23026     case DW_FORM_GNU_str_index:
23027     case DW_FORM_GNU_strp_alt:
23028       /* DW_STRING is already allocated on the objfile obstack, point
23029          directly to it.  */
23030       result = (const gdb_byte *) DW_STRING (attr);
23031       *len = strlen (DW_STRING (attr));
23032       break;
23033     case DW_FORM_block1:
23034     case DW_FORM_block2:
23035     case DW_FORM_block4:
23036     case DW_FORM_block:
23037     case DW_FORM_exprloc:
23038     case DW_FORM_data16:
23039       result = DW_BLOCK (attr)->data;
23040       *len = DW_BLOCK (attr)->size;
23041       break;
23042
23043       /* The DW_AT_const_value attributes are supposed to carry the
23044          symbol's value "represented as it would be on the target
23045          architecture."  By the time we get here, it's already been
23046          converted to host endianness, so we just need to sign- or
23047          zero-extend it as appropriate.  */
23048     case DW_FORM_data1:
23049       type = die_type (die, cu);
23050       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23051       if (result == NULL)
23052         result = write_constant_as_bytes (obstack, byte_order,
23053                                           type, value, len);
23054       break;
23055     case DW_FORM_data2:
23056       type = die_type (die, cu);
23057       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23058       if (result == NULL)
23059         result = write_constant_as_bytes (obstack, byte_order,
23060                                           type, value, len);
23061       break;
23062     case DW_FORM_data4:
23063       type = die_type (die, cu);
23064       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23065       if (result == NULL)
23066         result = write_constant_as_bytes (obstack, byte_order,
23067                                           type, value, len);
23068       break;
23069     case DW_FORM_data8:
23070       type = die_type (die, cu);
23071       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23072       if (result == NULL)
23073         result = write_constant_as_bytes (obstack, byte_order,
23074                                           type, value, len);
23075       break;
23076
23077     case DW_FORM_sdata:
23078     case DW_FORM_implicit_const:
23079       type = die_type (die, cu);
23080       result = write_constant_as_bytes (obstack, byte_order,
23081                                         type, DW_SND (attr), len);
23082       break;
23083
23084     case DW_FORM_udata:
23085       type = die_type (die, cu);
23086       result = write_constant_as_bytes (obstack, byte_order,
23087                                         type, DW_UNSND (attr), len);
23088       break;
23089
23090     default:
23091       complaint (_("unsupported const value attribute form: '%s'"),
23092                  dwarf_form_name (attr->form));
23093       break;
23094     }
23095
23096   return result;
23097 }
23098
23099 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23100    valid type for this die is found.  */
23101
23102 struct type *
23103 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23104                                 struct dwarf2_per_cu_data *per_cu)
23105 {
23106   struct dwarf2_cu *cu;
23107   struct die_info *die;
23108
23109   if (per_cu->cu == NULL)
23110     load_cu (per_cu, false);
23111   cu = per_cu->cu;
23112   if (!cu)
23113     return NULL;
23114
23115   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23116   if (!die)
23117     return NULL;
23118
23119   return die_type (die, cu);
23120 }
23121
23122 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23123    PER_CU.  */
23124
23125 struct type *
23126 dwarf2_get_die_type (cu_offset die_offset,
23127                      struct dwarf2_per_cu_data *per_cu)
23128 {
23129   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23130   return get_die_type_at_offset (die_offset_sect, per_cu);
23131 }
23132
23133 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23134    On entry *REF_CU is the CU of SRC_DIE.
23135    On exit *REF_CU is the CU of the result.
23136    Returns NULL if the referenced DIE isn't found.  */
23137
23138 static struct die_info *
23139 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23140                   struct dwarf2_cu **ref_cu)
23141 {
23142   struct die_info temp_die;
23143   struct dwarf2_cu *sig_cu;
23144   struct die_info *die;
23145
23146   /* While it might be nice to assert sig_type->type == NULL here,
23147      we can get here for DW_AT_imported_declaration where we need
23148      the DIE not the type.  */
23149
23150   /* If necessary, add it to the queue and load its DIEs.  */
23151
23152   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23153     read_signatured_type (sig_type);
23154
23155   sig_cu = sig_type->per_cu.cu;
23156   gdb_assert (sig_cu != NULL);
23157   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23158   temp_die.sect_off = sig_type->type_offset_in_section;
23159   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23160                                                  to_underlying (temp_die.sect_off));
23161   if (die)
23162     {
23163       struct dwarf2_per_objfile *dwarf2_per_objfile
23164         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23165
23166       /* For .gdb_index version 7 keep track of included TUs.
23167          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23168       if (dwarf2_per_objfile->index_table != NULL
23169           && dwarf2_per_objfile->index_table->version <= 7)
23170         {
23171           VEC_safe_push (dwarf2_per_cu_ptr,
23172                          (*ref_cu)->per_cu->imported_symtabs,
23173                          sig_cu->per_cu);
23174         }
23175
23176       *ref_cu = sig_cu;
23177       return die;
23178     }
23179
23180   return NULL;
23181 }
23182
23183 /* Follow signatured type referenced by ATTR in SRC_DIE.
23184    On entry *REF_CU is the CU of SRC_DIE.
23185    On exit *REF_CU is the CU of the result.
23186    The result is the DIE of the type.
23187    If the referenced type cannot be found an error is thrown.  */
23188
23189 static struct die_info *
23190 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23191                 struct dwarf2_cu **ref_cu)
23192 {
23193   ULONGEST signature = DW_SIGNATURE (attr);
23194   struct signatured_type *sig_type;
23195   struct die_info *die;
23196
23197   gdb_assert (attr->form == DW_FORM_ref_sig8);
23198
23199   sig_type = lookup_signatured_type (*ref_cu, signature);
23200   /* sig_type will be NULL if the signatured type is missing from
23201      the debug info.  */
23202   if (sig_type == NULL)
23203     {
23204       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23205                " from DIE at %s [in module %s]"),
23206              hex_string (signature), sect_offset_str (src_die->sect_off),
23207              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23208     }
23209
23210   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23211   if (die == NULL)
23212     {
23213       dump_die_for_error (src_die);
23214       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23215                " from DIE at %s [in module %s]"),
23216              hex_string (signature), sect_offset_str (src_die->sect_off),
23217              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23218     }
23219
23220   return die;
23221 }
23222
23223 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23224    reading in and processing the type unit if necessary.  */
23225
23226 static struct type *
23227 get_signatured_type (struct die_info *die, ULONGEST signature,
23228                      struct dwarf2_cu *cu)
23229 {
23230   struct dwarf2_per_objfile *dwarf2_per_objfile
23231     = cu->per_cu->dwarf2_per_objfile;
23232   struct signatured_type *sig_type;
23233   struct dwarf2_cu *type_cu;
23234   struct die_info *type_die;
23235   struct type *type;
23236
23237   sig_type = lookup_signatured_type (cu, signature);
23238   /* sig_type will be NULL if the signatured type is missing from
23239      the debug info.  */
23240   if (sig_type == NULL)
23241     {
23242       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23243                    " from DIE at %s [in module %s]"),
23244                  hex_string (signature), sect_offset_str (die->sect_off),
23245                  objfile_name (dwarf2_per_objfile->objfile));
23246       return build_error_marker_type (cu, die);
23247     }
23248
23249   /* If we already know the type we're done.  */
23250   if (sig_type->type != NULL)
23251     return sig_type->type;
23252
23253   type_cu = cu;
23254   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23255   if (type_die != NULL)
23256     {
23257       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23258          is created.  This is important, for example, because for c++ classes
23259          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23260       type = read_type_die (type_die, type_cu);
23261       if (type == NULL)
23262         {
23263           complaint (_("Dwarf Error: Cannot build signatured type %s"
23264                        " referenced from DIE at %s [in module %s]"),
23265                      hex_string (signature), sect_offset_str (die->sect_off),
23266                      objfile_name (dwarf2_per_objfile->objfile));
23267           type = build_error_marker_type (cu, die);
23268         }
23269     }
23270   else
23271     {
23272       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23273                    " from DIE at %s [in module %s]"),
23274                  hex_string (signature), sect_offset_str (die->sect_off),
23275                  objfile_name (dwarf2_per_objfile->objfile));
23276       type = build_error_marker_type (cu, die);
23277     }
23278   sig_type->type = type;
23279
23280   return type;
23281 }
23282
23283 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23284    reading in and processing the type unit if necessary.  */
23285
23286 static struct type *
23287 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23288                           struct dwarf2_cu *cu) /* ARI: editCase function */
23289 {
23290   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23291   if (attr_form_is_ref (attr))
23292     {
23293       struct dwarf2_cu *type_cu = cu;
23294       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23295
23296       return read_type_die (type_die, type_cu);
23297     }
23298   else if (attr->form == DW_FORM_ref_sig8)
23299     {
23300       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23301     }
23302   else
23303     {
23304       struct dwarf2_per_objfile *dwarf2_per_objfile
23305         = cu->per_cu->dwarf2_per_objfile;
23306
23307       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23308                    " at %s [in module %s]"),
23309                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23310                  objfile_name (dwarf2_per_objfile->objfile));
23311       return build_error_marker_type (cu, die);
23312     }
23313 }
23314
23315 /* Load the DIEs associated with type unit PER_CU into memory.  */
23316
23317 static void
23318 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23319 {
23320   struct signatured_type *sig_type;
23321
23322   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23323   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23324
23325   /* We have the per_cu, but we need the signatured_type.
23326      Fortunately this is an easy translation.  */
23327   gdb_assert (per_cu->is_debug_types);
23328   sig_type = (struct signatured_type *) per_cu;
23329
23330   gdb_assert (per_cu->cu == NULL);
23331
23332   read_signatured_type (sig_type);
23333
23334   gdb_assert (per_cu->cu != NULL);
23335 }
23336
23337 /* die_reader_func for read_signatured_type.
23338    This is identical to load_full_comp_unit_reader,
23339    but is kept separate for now.  */
23340
23341 static void
23342 read_signatured_type_reader (const struct die_reader_specs *reader,
23343                              const gdb_byte *info_ptr,
23344                              struct die_info *comp_unit_die,
23345                              int has_children,
23346                              void *data)
23347 {
23348   struct dwarf2_cu *cu = reader->cu;
23349
23350   gdb_assert (cu->die_hash == NULL);
23351   cu->die_hash =
23352     htab_create_alloc_ex (cu->header.length / 12,
23353                           die_hash,
23354                           die_eq,
23355                           NULL,
23356                           &cu->comp_unit_obstack,
23357                           hashtab_obstack_allocate,
23358                           dummy_obstack_deallocate);
23359
23360   if (has_children)
23361     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23362                                                   &info_ptr, comp_unit_die);
23363   cu->dies = comp_unit_die;
23364   /* comp_unit_die is not stored in die_hash, no need.  */
23365
23366   /* We try not to read any attributes in this function, because not
23367      all CUs needed for references have been loaded yet, and symbol
23368      table processing isn't initialized.  But we have to set the CU language,
23369      or we won't be able to build types correctly.
23370      Similarly, if we do not read the producer, we can not apply
23371      producer-specific interpretation.  */
23372   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23373 }
23374
23375 /* Read in a signatured type and build its CU and DIEs.
23376    If the type is a stub for the real type in a DWO file,
23377    read in the real type from the DWO file as well.  */
23378
23379 static void
23380 read_signatured_type (struct signatured_type *sig_type)
23381 {
23382   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23383
23384   gdb_assert (per_cu->is_debug_types);
23385   gdb_assert (per_cu->cu == NULL);
23386
23387   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23388                            read_signatured_type_reader, NULL);
23389   sig_type->per_cu.tu_read = 1;
23390 }
23391
23392 /* Decode simple location descriptions.
23393    Given a pointer to a dwarf block that defines a location, compute
23394    the location and return the value.
23395
23396    NOTE drow/2003-11-18: This function is called in two situations
23397    now: for the address of static or global variables (partial symbols
23398    only) and for offsets into structures which are expected to be
23399    (more or less) constant.  The partial symbol case should go away,
23400    and only the constant case should remain.  That will let this
23401    function complain more accurately.  A few special modes are allowed
23402    without complaint for global variables (for instance, global
23403    register values and thread-local values).
23404
23405    A location description containing no operations indicates that the
23406    object is optimized out.  The return value is 0 for that case.
23407    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23408    callers will only want a very basic result and this can become a
23409    complaint.
23410
23411    Note that stack[0] is unused except as a default error return.  */
23412
23413 static CORE_ADDR
23414 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23415 {
23416   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23417   size_t i;
23418   size_t size = blk->size;
23419   const gdb_byte *data = blk->data;
23420   CORE_ADDR stack[64];
23421   int stacki;
23422   unsigned int bytes_read, unsnd;
23423   gdb_byte op;
23424
23425   i = 0;
23426   stacki = 0;
23427   stack[stacki] = 0;
23428   stack[++stacki] = 0;
23429
23430   while (i < size)
23431     {
23432       op = data[i++];
23433       switch (op)
23434         {
23435         case DW_OP_lit0:
23436         case DW_OP_lit1:
23437         case DW_OP_lit2:
23438         case DW_OP_lit3:
23439         case DW_OP_lit4:
23440         case DW_OP_lit5:
23441         case DW_OP_lit6:
23442         case DW_OP_lit7:
23443         case DW_OP_lit8:
23444         case DW_OP_lit9:
23445         case DW_OP_lit10:
23446         case DW_OP_lit11:
23447         case DW_OP_lit12:
23448         case DW_OP_lit13:
23449         case DW_OP_lit14:
23450         case DW_OP_lit15:
23451         case DW_OP_lit16:
23452         case DW_OP_lit17:
23453         case DW_OP_lit18:
23454         case DW_OP_lit19:
23455         case DW_OP_lit20:
23456         case DW_OP_lit21:
23457         case DW_OP_lit22:
23458         case DW_OP_lit23:
23459         case DW_OP_lit24:
23460         case DW_OP_lit25:
23461         case DW_OP_lit26:
23462         case DW_OP_lit27:
23463         case DW_OP_lit28:
23464         case DW_OP_lit29:
23465         case DW_OP_lit30:
23466         case DW_OP_lit31:
23467           stack[++stacki] = op - DW_OP_lit0;
23468           break;
23469
23470         case DW_OP_reg0:
23471         case DW_OP_reg1:
23472         case DW_OP_reg2:
23473         case DW_OP_reg3:
23474         case DW_OP_reg4:
23475         case DW_OP_reg5:
23476         case DW_OP_reg6:
23477         case DW_OP_reg7:
23478         case DW_OP_reg8:
23479         case DW_OP_reg9:
23480         case DW_OP_reg10:
23481         case DW_OP_reg11:
23482         case DW_OP_reg12:
23483         case DW_OP_reg13:
23484         case DW_OP_reg14:
23485         case DW_OP_reg15:
23486         case DW_OP_reg16:
23487         case DW_OP_reg17:
23488         case DW_OP_reg18:
23489         case DW_OP_reg19:
23490         case DW_OP_reg20:
23491         case DW_OP_reg21:
23492         case DW_OP_reg22:
23493         case DW_OP_reg23:
23494         case DW_OP_reg24:
23495         case DW_OP_reg25:
23496         case DW_OP_reg26:
23497         case DW_OP_reg27:
23498         case DW_OP_reg28:
23499         case DW_OP_reg29:
23500         case DW_OP_reg30:
23501         case DW_OP_reg31:
23502           stack[++stacki] = op - DW_OP_reg0;
23503           if (i < size)
23504             dwarf2_complex_location_expr_complaint ();
23505           break;
23506
23507         case DW_OP_regx:
23508           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23509           i += bytes_read;
23510           stack[++stacki] = unsnd;
23511           if (i < size)
23512             dwarf2_complex_location_expr_complaint ();
23513           break;
23514
23515         case DW_OP_addr:
23516           stack[++stacki] = read_address (objfile->obfd, &data[i],
23517                                           cu, &bytes_read);
23518           i += bytes_read;
23519           break;
23520
23521         case DW_OP_const1u:
23522           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23523           i += 1;
23524           break;
23525
23526         case DW_OP_const1s:
23527           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23528           i += 1;
23529           break;
23530
23531         case DW_OP_const2u:
23532           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23533           i += 2;
23534           break;
23535
23536         case DW_OP_const2s:
23537           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23538           i += 2;
23539           break;
23540
23541         case DW_OP_const4u:
23542           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23543           i += 4;
23544           break;
23545
23546         case DW_OP_const4s:
23547           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23548           i += 4;
23549           break;
23550
23551         case DW_OP_const8u:
23552           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23553           i += 8;
23554           break;
23555
23556         case DW_OP_constu:
23557           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23558                                                   &bytes_read);
23559           i += bytes_read;
23560           break;
23561
23562         case DW_OP_consts:
23563           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23564           i += bytes_read;
23565           break;
23566
23567         case DW_OP_dup:
23568           stack[stacki + 1] = stack[stacki];
23569           stacki++;
23570           break;
23571
23572         case DW_OP_plus:
23573           stack[stacki - 1] += stack[stacki];
23574           stacki--;
23575           break;
23576
23577         case DW_OP_plus_uconst:
23578           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23579                                                  &bytes_read);
23580           i += bytes_read;
23581           break;
23582
23583         case DW_OP_minus:
23584           stack[stacki - 1] -= stack[stacki];
23585           stacki--;
23586           break;
23587
23588         case DW_OP_deref:
23589           /* If we're not the last op, then we definitely can't encode
23590              this using GDB's address_class enum.  This is valid for partial
23591              global symbols, although the variable's address will be bogus
23592              in the psymtab.  */
23593           if (i < size)
23594             dwarf2_complex_location_expr_complaint ();
23595           break;
23596
23597         case DW_OP_GNU_push_tls_address:
23598         case DW_OP_form_tls_address:
23599           /* The top of the stack has the offset from the beginning
23600              of the thread control block at which the variable is located.  */
23601           /* Nothing should follow this operator, so the top of stack would
23602              be returned.  */
23603           /* This is valid for partial global symbols, but the variable's
23604              address will be bogus in the psymtab.  Make it always at least
23605              non-zero to not look as a variable garbage collected by linker
23606              which have DW_OP_addr 0.  */
23607           if (i < size)
23608             dwarf2_complex_location_expr_complaint ();
23609           stack[stacki]++;
23610           break;
23611
23612         case DW_OP_GNU_uninit:
23613           break;
23614
23615         case DW_OP_GNU_addr_index:
23616         case DW_OP_GNU_const_index:
23617           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23618                                                          &bytes_read);
23619           i += bytes_read;
23620           break;
23621
23622         default:
23623           {
23624             const char *name = get_DW_OP_name (op);
23625
23626             if (name)
23627               complaint (_("unsupported stack op: '%s'"),
23628                          name);
23629             else
23630               complaint (_("unsupported stack op: '%02x'"),
23631                          op);
23632           }
23633
23634           return (stack[stacki]);
23635         }
23636
23637       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23638          outside of the allocated space.  Also enforce minimum>0.  */
23639       if (stacki >= ARRAY_SIZE (stack) - 1)
23640         {
23641           complaint (_("location description stack overflow"));
23642           return 0;
23643         }
23644
23645       if (stacki <= 0)
23646         {
23647           complaint (_("location description stack underflow"));
23648           return 0;
23649         }
23650     }
23651   return (stack[stacki]);
23652 }
23653
23654 /* memory allocation interface */
23655
23656 static struct dwarf_block *
23657 dwarf_alloc_block (struct dwarf2_cu *cu)
23658 {
23659   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23660 }
23661
23662 static struct die_info *
23663 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23664 {
23665   struct die_info *die;
23666   size_t size = sizeof (struct die_info);
23667
23668   if (num_attrs > 1)
23669     size += (num_attrs - 1) * sizeof (struct attribute);
23670
23671   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23672   memset (die, 0, sizeof (struct die_info));
23673   return (die);
23674 }
23675
23676 \f
23677 /* Macro support.  */
23678
23679 /* Return file name relative to the compilation directory of file number I in
23680    *LH's file name table.  The result is allocated using xmalloc; the caller is
23681    responsible for freeing it.  */
23682
23683 static char *
23684 file_file_name (int file, struct line_header *lh)
23685 {
23686   /* Is the file number a valid index into the line header's file name
23687      table?  Remember that file numbers start with one, not zero.  */
23688   if (1 <= file && file <= lh->file_names.size ())
23689     {
23690       const file_entry &fe = lh->file_names[file - 1];
23691
23692       if (!IS_ABSOLUTE_PATH (fe.name))
23693         {
23694           const char *dir = fe.include_dir (lh);
23695           if (dir != NULL)
23696             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23697         }
23698       return xstrdup (fe.name);
23699     }
23700   else
23701     {
23702       /* The compiler produced a bogus file number.  We can at least
23703          record the macro definitions made in the file, even if we
23704          won't be able to find the file by name.  */
23705       char fake_name[80];
23706
23707       xsnprintf (fake_name, sizeof (fake_name),
23708                  "<bad macro file number %d>", file);
23709
23710       complaint (_("bad file number in macro information (%d)"),
23711                  file);
23712
23713       return xstrdup (fake_name);
23714     }
23715 }
23716
23717 /* Return the full name of file number I in *LH's file name table.
23718    Use COMP_DIR as the name of the current directory of the
23719    compilation.  The result is allocated using xmalloc; the caller is
23720    responsible for freeing it.  */
23721 static char *
23722 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23723 {
23724   /* Is the file number a valid index into the line header's file name
23725      table?  Remember that file numbers start with one, not zero.  */
23726   if (1 <= file && file <= lh->file_names.size ())
23727     {
23728       char *relative = file_file_name (file, lh);
23729
23730       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23731         return relative;
23732       return reconcat (relative, comp_dir, SLASH_STRING,
23733                        relative, (char *) NULL);
23734     }
23735   else
23736     return file_file_name (file, lh);
23737 }
23738
23739
23740 static struct macro_source_file *
23741 macro_start_file (struct dwarf2_cu *cu,
23742                   int file, int line,
23743                   struct macro_source_file *current_file,
23744                   struct line_header *lh)
23745 {
23746   /* File name relative to the compilation directory of this source file.  */
23747   char *file_name = file_file_name (file, lh);
23748
23749   if (! current_file)
23750     {
23751       /* Note: We don't create a macro table for this compilation unit
23752          at all until we actually get a filename.  */
23753       struct macro_table *macro_table = cu->builder->get_macro_table ();
23754
23755       /* If we have no current file, then this must be the start_file
23756          directive for the compilation unit's main source file.  */
23757       current_file = macro_set_main (macro_table, file_name);
23758       macro_define_special (macro_table);
23759     }
23760   else
23761     current_file = macro_include (current_file, line, file_name);
23762
23763   xfree (file_name);
23764
23765   return current_file;
23766 }
23767
23768 static const char *
23769 consume_improper_spaces (const char *p, const char *body)
23770 {
23771   if (*p == ' ')
23772     {
23773       complaint (_("macro definition contains spaces "
23774                    "in formal argument list:\n`%s'"),
23775                  body);
23776
23777       while (*p == ' ')
23778         p++;
23779     }
23780
23781   return p;
23782 }
23783
23784
23785 static void
23786 parse_macro_definition (struct macro_source_file *file, int line,
23787                         const char *body)
23788 {
23789   const char *p;
23790
23791   /* The body string takes one of two forms.  For object-like macro
23792      definitions, it should be:
23793
23794         <macro name> " " <definition>
23795
23796      For function-like macro definitions, it should be:
23797
23798         <macro name> "() " <definition>
23799      or
23800         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23801
23802      Spaces may appear only where explicitly indicated, and in the
23803      <definition>.
23804
23805      The Dwarf 2 spec says that an object-like macro's name is always
23806      followed by a space, but versions of GCC around March 2002 omit
23807      the space when the macro's definition is the empty string.
23808
23809      The Dwarf 2 spec says that there should be no spaces between the
23810      formal arguments in a function-like macro's formal argument list,
23811      but versions of GCC around March 2002 include spaces after the
23812      commas.  */
23813
23814
23815   /* Find the extent of the macro name.  The macro name is terminated
23816      by either a space or null character (for an object-like macro) or
23817      an opening paren (for a function-like macro).  */
23818   for (p = body; *p; p++)
23819     if (*p == ' ' || *p == '(')
23820       break;
23821
23822   if (*p == ' ' || *p == '\0')
23823     {
23824       /* It's an object-like macro.  */
23825       int name_len = p - body;
23826       char *name = savestring (body, name_len);
23827       const char *replacement;
23828
23829       if (*p == ' ')
23830         replacement = body + name_len + 1;
23831       else
23832         {
23833           dwarf2_macro_malformed_definition_complaint (body);
23834           replacement = body + name_len;
23835         }
23836
23837       macro_define_object (file, line, name, replacement);
23838
23839       xfree (name);
23840     }
23841   else if (*p == '(')
23842     {
23843       /* It's a function-like macro.  */
23844       char *name = savestring (body, p - body);
23845       int argc = 0;
23846       int argv_size = 1;
23847       char **argv = XNEWVEC (char *, argv_size);
23848
23849       p++;
23850
23851       p = consume_improper_spaces (p, body);
23852
23853       /* Parse the formal argument list.  */
23854       while (*p && *p != ')')
23855         {
23856           /* Find the extent of the current argument name.  */
23857           const char *arg_start = p;
23858
23859           while (*p && *p != ',' && *p != ')' && *p != ' ')
23860             p++;
23861
23862           if (! *p || p == arg_start)
23863             dwarf2_macro_malformed_definition_complaint (body);
23864           else
23865             {
23866               /* Make sure argv has room for the new argument.  */
23867               if (argc >= argv_size)
23868                 {
23869                   argv_size *= 2;
23870                   argv = XRESIZEVEC (char *, argv, argv_size);
23871                 }
23872
23873               argv[argc++] = savestring (arg_start, p - arg_start);
23874             }
23875
23876           p = consume_improper_spaces (p, body);
23877
23878           /* Consume the comma, if present.  */
23879           if (*p == ',')
23880             {
23881               p++;
23882
23883               p = consume_improper_spaces (p, body);
23884             }
23885         }
23886
23887       if (*p == ')')
23888         {
23889           p++;
23890
23891           if (*p == ' ')
23892             /* Perfectly formed definition, no complaints.  */
23893             macro_define_function (file, line, name,
23894                                    argc, (const char **) argv,
23895                                    p + 1);
23896           else if (*p == '\0')
23897             {
23898               /* Complain, but do define it.  */
23899               dwarf2_macro_malformed_definition_complaint (body);
23900               macro_define_function (file, line, name,
23901                                      argc, (const char **) argv,
23902                                      p);
23903             }
23904           else
23905             /* Just complain.  */
23906             dwarf2_macro_malformed_definition_complaint (body);
23907         }
23908       else
23909         /* Just complain.  */
23910         dwarf2_macro_malformed_definition_complaint (body);
23911
23912       xfree (name);
23913       {
23914         int i;
23915
23916         for (i = 0; i < argc; i++)
23917           xfree (argv[i]);
23918       }
23919       xfree (argv);
23920     }
23921   else
23922     dwarf2_macro_malformed_definition_complaint (body);
23923 }
23924
23925 /* Skip some bytes from BYTES according to the form given in FORM.
23926    Returns the new pointer.  */
23927
23928 static const gdb_byte *
23929 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23930                  enum dwarf_form form,
23931                  unsigned int offset_size,
23932                  struct dwarf2_section_info *section)
23933 {
23934   unsigned int bytes_read;
23935
23936   switch (form)
23937     {
23938     case DW_FORM_data1:
23939     case DW_FORM_flag:
23940       ++bytes;
23941       break;
23942
23943     case DW_FORM_data2:
23944       bytes += 2;
23945       break;
23946
23947     case DW_FORM_data4:
23948       bytes += 4;
23949       break;
23950
23951     case DW_FORM_data8:
23952       bytes += 8;
23953       break;
23954
23955     case DW_FORM_data16:
23956       bytes += 16;
23957       break;
23958
23959     case DW_FORM_string:
23960       read_direct_string (abfd, bytes, &bytes_read);
23961       bytes += bytes_read;
23962       break;
23963
23964     case DW_FORM_sec_offset:
23965     case DW_FORM_strp:
23966     case DW_FORM_GNU_strp_alt:
23967       bytes += offset_size;
23968       break;
23969
23970     case DW_FORM_block:
23971       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
23972       bytes += bytes_read;
23973       break;
23974
23975     case DW_FORM_block1:
23976       bytes += 1 + read_1_byte (abfd, bytes);
23977       break;
23978     case DW_FORM_block2:
23979       bytes += 2 + read_2_bytes (abfd, bytes);
23980       break;
23981     case DW_FORM_block4:
23982       bytes += 4 + read_4_bytes (abfd, bytes);
23983       break;
23984
23985     case DW_FORM_sdata:
23986     case DW_FORM_udata:
23987     case DW_FORM_GNU_addr_index:
23988     case DW_FORM_GNU_str_index:
23989       bytes = gdb_skip_leb128 (bytes, buffer_end);
23990       if (bytes == NULL)
23991         {
23992           dwarf2_section_buffer_overflow_complaint (section);
23993           return NULL;
23994         }
23995       break;
23996
23997     case DW_FORM_implicit_const:
23998       break;
23999
24000     default:
24001       {
24002         complaint (_("invalid form 0x%x in `%s'"),
24003                    form, get_section_name (section));
24004         return NULL;
24005       }
24006     }
24007
24008   return bytes;
24009 }
24010
24011 /* A helper for dwarf_decode_macros that handles skipping an unknown
24012    opcode.  Returns an updated pointer to the macro data buffer; or,
24013    on error, issues a complaint and returns NULL.  */
24014
24015 static const gdb_byte *
24016 skip_unknown_opcode (unsigned int opcode,
24017                      const gdb_byte **opcode_definitions,
24018                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24019                      bfd *abfd,
24020                      unsigned int offset_size,
24021                      struct dwarf2_section_info *section)
24022 {
24023   unsigned int bytes_read, i;
24024   unsigned long arg;
24025   const gdb_byte *defn;
24026
24027   if (opcode_definitions[opcode] == NULL)
24028     {
24029       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
24030                  opcode);
24031       return NULL;
24032     }
24033
24034   defn = opcode_definitions[opcode];
24035   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24036   defn += bytes_read;
24037
24038   for (i = 0; i < arg; ++i)
24039     {
24040       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24041                                  (enum dwarf_form) defn[i], offset_size,
24042                                  section);
24043       if (mac_ptr == NULL)
24044         {
24045           /* skip_form_bytes already issued the complaint.  */
24046           return NULL;
24047         }
24048     }
24049
24050   return mac_ptr;
24051 }
24052
24053 /* A helper function which parses the header of a macro section.
24054    If the macro section is the extended (for now called "GNU") type,
24055    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24056    the header, or issues a complaint and returns NULL on error.  */
24057
24058 static const gdb_byte *
24059 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24060                           bfd *abfd,
24061                           const gdb_byte *mac_ptr,
24062                           unsigned int *offset_size,
24063                           int section_is_gnu)
24064 {
24065   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24066
24067   if (section_is_gnu)
24068     {
24069       unsigned int version, flags;
24070
24071       version = read_2_bytes (abfd, mac_ptr);
24072       if (version != 4 && version != 5)
24073         {
24074           complaint (_("unrecognized version `%d' in .debug_macro section"),
24075                      version);
24076           return NULL;
24077         }
24078       mac_ptr += 2;
24079
24080       flags = read_1_byte (abfd, mac_ptr);
24081       ++mac_ptr;
24082       *offset_size = (flags & 1) ? 8 : 4;
24083
24084       if ((flags & 2) != 0)
24085         /* We don't need the line table offset.  */
24086         mac_ptr += *offset_size;
24087
24088       /* Vendor opcode descriptions.  */
24089       if ((flags & 4) != 0)
24090         {
24091           unsigned int i, count;
24092
24093           count = read_1_byte (abfd, mac_ptr);
24094           ++mac_ptr;
24095           for (i = 0; i < count; ++i)
24096             {
24097               unsigned int opcode, bytes_read;
24098               unsigned long arg;
24099
24100               opcode = read_1_byte (abfd, mac_ptr);
24101               ++mac_ptr;
24102               opcode_definitions[opcode] = mac_ptr;
24103               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24104               mac_ptr += bytes_read;
24105               mac_ptr += arg;
24106             }
24107         }
24108     }
24109
24110   return mac_ptr;
24111 }
24112
24113 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24114    including DW_MACRO_import.  */
24115
24116 static void
24117 dwarf_decode_macro_bytes (struct dwarf2_cu *cu,
24118                           bfd *abfd,
24119                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24120                           struct macro_source_file *current_file,
24121                           struct line_header *lh,
24122                           struct dwarf2_section_info *section,
24123                           int section_is_gnu, int section_is_dwz,
24124                           unsigned int offset_size,
24125                           htab_t include_hash)
24126 {
24127   struct dwarf2_per_objfile *dwarf2_per_objfile
24128     = cu->per_cu->dwarf2_per_objfile;
24129   struct objfile *objfile = dwarf2_per_objfile->objfile;
24130   enum dwarf_macro_record_type macinfo_type;
24131   int at_commandline;
24132   const gdb_byte *opcode_definitions[256];
24133
24134   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24135                                       &offset_size, section_is_gnu);
24136   if (mac_ptr == NULL)
24137     {
24138       /* We already issued a complaint.  */
24139       return;
24140     }
24141
24142   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24143      GDB is still reading the definitions from command line.  First
24144      DW_MACINFO_start_file will need to be ignored as it was already executed
24145      to create CURRENT_FILE for the main source holding also the command line
24146      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24147      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24148
24149   at_commandline = 1;
24150
24151   do
24152     {
24153       /* Do we at least have room for a macinfo type byte?  */
24154       if (mac_ptr >= mac_end)
24155         {
24156           dwarf2_section_buffer_overflow_complaint (section);
24157           break;
24158         }
24159
24160       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24161       mac_ptr++;
24162
24163       /* Note that we rely on the fact that the corresponding GNU and
24164          DWARF constants are the same.  */
24165       DIAGNOSTIC_PUSH
24166       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24167       switch (macinfo_type)
24168         {
24169           /* A zero macinfo type indicates the end of the macro
24170              information.  */
24171         case 0:
24172           break;
24173
24174         case DW_MACRO_define:
24175         case DW_MACRO_undef:
24176         case DW_MACRO_define_strp:
24177         case DW_MACRO_undef_strp:
24178         case DW_MACRO_define_sup:
24179         case DW_MACRO_undef_sup:
24180           {
24181             unsigned int bytes_read;
24182             int line;
24183             const char *body;
24184             int is_define;
24185
24186             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24187             mac_ptr += bytes_read;
24188
24189             if (macinfo_type == DW_MACRO_define
24190                 || macinfo_type == DW_MACRO_undef)
24191               {
24192                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24193                 mac_ptr += bytes_read;
24194               }
24195             else
24196               {
24197                 LONGEST str_offset;
24198
24199                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24200                 mac_ptr += offset_size;
24201
24202                 if (macinfo_type == DW_MACRO_define_sup
24203                     || macinfo_type == DW_MACRO_undef_sup
24204                     || section_is_dwz)
24205                   {
24206                     struct dwz_file *dwz
24207                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24208
24209                     body = read_indirect_string_from_dwz (objfile,
24210                                                           dwz, str_offset);
24211                   }
24212                 else
24213                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24214                                                          abfd, str_offset);
24215               }
24216
24217             is_define = (macinfo_type == DW_MACRO_define
24218                          || macinfo_type == DW_MACRO_define_strp
24219                          || macinfo_type == DW_MACRO_define_sup);
24220             if (! current_file)
24221               {
24222                 /* DWARF violation as no main source is present.  */
24223                 complaint (_("debug info with no main source gives macro %s "
24224                              "on line %d: %s"),
24225                            is_define ? _("definition") : _("undefinition"),
24226                            line, body);
24227                 break;
24228               }
24229             if ((line == 0 && !at_commandline)
24230                 || (line != 0 && at_commandline))
24231               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24232                          at_commandline ? _("command-line") : _("in-file"),
24233                          is_define ? _("definition") : _("undefinition"),
24234                          line == 0 ? _("zero") : _("non-zero"), line, body);
24235
24236             if (is_define)
24237               parse_macro_definition (current_file, line, body);
24238             else
24239               {
24240                 gdb_assert (macinfo_type == DW_MACRO_undef
24241                             || macinfo_type == DW_MACRO_undef_strp
24242                             || macinfo_type == DW_MACRO_undef_sup);
24243                 macro_undef (current_file, line, body);
24244               }
24245           }
24246           break;
24247
24248         case DW_MACRO_start_file:
24249           {
24250             unsigned int bytes_read;
24251             int line, file;
24252
24253             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24254             mac_ptr += bytes_read;
24255             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24256             mac_ptr += bytes_read;
24257
24258             if ((line == 0 && !at_commandline)
24259                 || (line != 0 && at_commandline))
24260               complaint (_("debug info gives source %d included "
24261                            "from %s at %s line %d"),
24262                          file, at_commandline ? _("command-line") : _("file"),
24263                          line == 0 ? _("zero") : _("non-zero"), line);
24264
24265             if (at_commandline)
24266               {
24267                 /* This DW_MACRO_start_file was executed in the
24268                    pass one.  */
24269                 at_commandline = 0;
24270               }
24271             else
24272               current_file = macro_start_file (cu, file, line, current_file,
24273                                                lh);
24274           }
24275           break;
24276
24277         case DW_MACRO_end_file:
24278           if (! current_file)
24279             complaint (_("macro debug info has an unmatched "
24280                          "`close_file' directive"));
24281           else
24282             {
24283               current_file = current_file->included_by;
24284               if (! current_file)
24285                 {
24286                   enum dwarf_macro_record_type next_type;
24287
24288                   /* GCC circa March 2002 doesn't produce the zero
24289                      type byte marking the end of the compilation
24290                      unit.  Complain if it's not there, but exit no
24291                      matter what.  */
24292
24293                   /* Do we at least have room for a macinfo type byte?  */
24294                   if (mac_ptr >= mac_end)
24295                     {
24296                       dwarf2_section_buffer_overflow_complaint (section);
24297                       return;
24298                     }
24299
24300                   /* We don't increment mac_ptr here, so this is just
24301                      a look-ahead.  */
24302                   next_type
24303                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24304                                                                   mac_ptr);
24305                   if (next_type != 0)
24306                     complaint (_("no terminating 0-type entry for "
24307                                  "macros in `.debug_macinfo' section"));
24308
24309                   return;
24310                 }
24311             }
24312           break;
24313
24314         case DW_MACRO_import:
24315         case DW_MACRO_import_sup:
24316           {
24317             LONGEST offset;
24318             void **slot;
24319             bfd *include_bfd = abfd;
24320             struct dwarf2_section_info *include_section = section;
24321             const gdb_byte *include_mac_end = mac_end;
24322             int is_dwz = section_is_dwz;
24323             const gdb_byte *new_mac_ptr;
24324
24325             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24326             mac_ptr += offset_size;
24327
24328             if (macinfo_type == DW_MACRO_import_sup)
24329               {
24330                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24331
24332                 dwarf2_read_section (objfile, &dwz->macro);
24333
24334                 include_section = &dwz->macro;
24335                 include_bfd = get_section_bfd_owner (include_section);
24336                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24337                 is_dwz = 1;
24338               }
24339
24340             new_mac_ptr = include_section->buffer + offset;
24341             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24342
24343             if (*slot != NULL)
24344               {
24345                 /* This has actually happened; see
24346                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24347                 complaint (_("recursive DW_MACRO_import in "
24348                              ".debug_macro section"));
24349               }
24350             else
24351               {
24352                 *slot = (void *) new_mac_ptr;
24353
24354                 dwarf_decode_macro_bytes (cu, include_bfd, new_mac_ptr,
24355                                           include_mac_end, current_file, lh,
24356                                           section, section_is_gnu, is_dwz,
24357                                           offset_size, include_hash);
24358
24359                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24360               }
24361           }
24362           break;
24363
24364         case DW_MACINFO_vendor_ext:
24365           if (!section_is_gnu)
24366             {
24367               unsigned int bytes_read;
24368
24369               /* This reads the constant, but since we don't recognize
24370                  any vendor extensions, we ignore it.  */
24371               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24372               mac_ptr += bytes_read;
24373               read_direct_string (abfd, mac_ptr, &bytes_read);
24374               mac_ptr += bytes_read;
24375
24376               /* We don't recognize any vendor extensions.  */
24377               break;
24378             }
24379           /* FALLTHROUGH */
24380
24381         default:
24382           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24383                                          mac_ptr, mac_end, abfd, offset_size,
24384                                          section);
24385           if (mac_ptr == NULL)
24386             return;
24387           break;
24388         }
24389       DIAGNOSTIC_POP
24390     } while (macinfo_type != 0);
24391 }
24392
24393 static void
24394 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24395                      int section_is_gnu)
24396 {
24397   struct dwarf2_per_objfile *dwarf2_per_objfile
24398     = cu->per_cu->dwarf2_per_objfile;
24399   struct objfile *objfile = dwarf2_per_objfile->objfile;
24400   struct line_header *lh = cu->line_header;
24401   bfd *abfd;
24402   const gdb_byte *mac_ptr, *mac_end;
24403   struct macro_source_file *current_file = 0;
24404   enum dwarf_macro_record_type macinfo_type;
24405   unsigned int offset_size = cu->header.offset_size;
24406   const gdb_byte *opcode_definitions[256];
24407   void **slot;
24408   struct dwarf2_section_info *section;
24409   const char *section_name;
24410
24411   if (cu->dwo_unit != NULL)
24412     {
24413       if (section_is_gnu)
24414         {
24415           section = &cu->dwo_unit->dwo_file->sections.macro;
24416           section_name = ".debug_macro.dwo";
24417         }
24418       else
24419         {
24420           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24421           section_name = ".debug_macinfo.dwo";
24422         }
24423     }
24424   else
24425     {
24426       if (section_is_gnu)
24427         {
24428           section = &dwarf2_per_objfile->macro;
24429           section_name = ".debug_macro";
24430         }
24431       else
24432         {
24433           section = &dwarf2_per_objfile->macinfo;
24434           section_name = ".debug_macinfo";
24435         }
24436     }
24437
24438   dwarf2_read_section (objfile, section);
24439   if (section->buffer == NULL)
24440     {
24441       complaint (_("missing %s section"), section_name);
24442       return;
24443     }
24444   abfd = get_section_bfd_owner (section);
24445
24446   /* First pass: Find the name of the base filename.
24447      This filename is needed in order to process all macros whose definition
24448      (or undefinition) comes from the command line.  These macros are defined
24449      before the first DW_MACINFO_start_file entry, and yet still need to be
24450      associated to the base file.
24451
24452      To determine the base file name, we scan the macro definitions until we
24453      reach the first DW_MACINFO_start_file entry.  We then initialize
24454      CURRENT_FILE accordingly so that any macro definition found before the
24455      first DW_MACINFO_start_file can still be associated to the base file.  */
24456
24457   mac_ptr = section->buffer + offset;
24458   mac_end = section->buffer + section->size;
24459
24460   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24461                                       &offset_size, section_is_gnu);
24462   if (mac_ptr == NULL)
24463     {
24464       /* We already issued a complaint.  */
24465       return;
24466     }
24467
24468   do
24469     {
24470       /* Do we at least have room for a macinfo type byte?  */
24471       if (mac_ptr >= mac_end)
24472         {
24473           /* Complaint is printed during the second pass as GDB will probably
24474              stop the first pass earlier upon finding
24475              DW_MACINFO_start_file.  */
24476           break;
24477         }
24478
24479       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24480       mac_ptr++;
24481
24482       /* Note that we rely on the fact that the corresponding GNU and
24483          DWARF constants are the same.  */
24484       DIAGNOSTIC_PUSH
24485       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24486       switch (macinfo_type)
24487         {
24488           /* A zero macinfo type indicates the end of the macro
24489              information.  */
24490         case 0:
24491           break;
24492
24493         case DW_MACRO_define:
24494         case DW_MACRO_undef:
24495           /* Only skip the data by MAC_PTR.  */
24496           {
24497             unsigned int bytes_read;
24498
24499             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24500             mac_ptr += bytes_read;
24501             read_direct_string (abfd, mac_ptr, &bytes_read);
24502             mac_ptr += bytes_read;
24503           }
24504           break;
24505
24506         case DW_MACRO_start_file:
24507           {
24508             unsigned int bytes_read;
24509             int line, file;
24510
24511             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24512             mac_ptr += bytes_read;
24513             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24514             mac_ptr += bytes_read;
24515
24516             current_file = macro_start_file (cu, file, line, current_file, lh);
24517           }
24518           break;
24519
24520         case DW_MACRO_end_file:
24521           /* No data to skip by MAC_PTR.  */
24522           break;
24523
24524         case DW_MACRO_define_strp:
24525         case DW_MACRO_undef_strp:
24526         case DW_MACRO_define_sup:
24527         case DW_MACRO_undef_sup:
24528           {
24529             unsigned int bytes_read;
24530
24531             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24532             mac_ptr += bytes_read;
24533             mac_ptr += offset_size;
24534           }
24535           break;
24536
24537         case DW_MACRO_import:
24538         case DW_MACRO_import_sup:
24539           /* Note that, according to the spec, a transparent include
24540              chain cannot call DW_MACRO_start_file.  So, we can just
24541              skip this opcode.  */
24542           mac_ptr += offset_size;
24543           break;
24544
24545         case DW_MACINFO_vendor_ext:
24546           /* Only skip the data by MAC_PTR.  */
24547           if (!section_is_gnu)
24548             {
24549               unsigned int bytes_read;
24550
24551               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24552               mac_ptr += bytes_read;
24553               read_direct_string (abfd, mac_ptr, &bytes_read);
24554               mac_ptr += bytes_read;
24555             }
24556           /* FALLTHROUGH */
24557
24558         default:
24559           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24560                                          mac_ptr, mac_end, abfd, offset_size,
24561                                          section);
24562           if (mac_ptr == NULL)
24563             return;
24564           break;
24565         }
24566       DIAGNOSTIC_POP
24567     } while (macinfo_type != 0 && current_file == NULL);
24568
24569   /* Second pass: Process all entries.
24570
24571      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24572      command-line macro definitions/undefinitions.  This flag is unset when we
24573      reach the first DW_MACINFO_start_file entry.  */
24574
24575   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24576                                            htab_eq_pointer,
24577                                            NULL, xcalloc, xfree));
24578   mac_ptr = section->buffer + offset;
24579   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24580   *slot = (void *) mac_ptr;
24581   dwarf_decode_macro_bytes (cu, abfd, mac_ptr, mac_end,
24582                             current_file, lh, section,
24583                             section_is_gnu, 0, offset_size,
24584                             include_hash.get ());
24585 }
24586
24587 /* Check if the attribute's form is a DW_FORM_block*
24588    if so return true else false.  */
24589
24590 static int
24591 attr_form_is_block (const struct attribute *attr)
24592 {
24593   return (attr == NULL ? 0 :
24594       attr->form == DW_FORM_block1
24595       || attr->form == DW_FORM_block2
24596       || attr->form == DW_FORM_block4
24597       || attr->form == DW_FORM_block
24598       || attr->form == DW_FORM_exprloc);
24599 }
24600
24601 /* Return non-zero if ATTR's value is a section offset --- classes
24602    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24603    You may use DW_UNSND (attr) to retrieve such offsets.
24604
24605    Section 7.5.4, "Attribute Encodings", explains that no attribute
24606    may have a value that belongs to more than one of these classes; it
24607    would be ambiguous if we did, because we use the same forms for all
24608    of them.  */
24609
24610 static int
24611 attr_form_is_section_offset (const struct attribute *attr)
24612 {
24613   return (attr->form == DW_FORM_data4
24614           || attr->form == DW_FORM_data8
24615           || attr->form == DW_FORM_sec_offset);
24616 }
24617
24618 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24619    zero otherwise.  When this function returns true, you can apply
24620    dwarf2_get_attr_constant_value to it.
24621
24622    However, note that for some attributes you must check
24623    attr_form_is_section_offset before using this test.  DW_FORM_data4
24624    and DW_FORM_data8 are members of both the constant class, and of
24625    the classes that contain offsets into other debug sections
24626    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24627    that, if an attribute's can be either a constant or one of the
24628    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24629    taken as section offsets, not constants.
24630
24631    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24632    cannot handle that.  */
24633
24634 static int
24635 attr_form_is_constant (const struct attribute *attr)
24636 {
24637   switch (attr->form)
24638     {
24639     case DW_FORM_sdata:
24640     case DW_FORM_udata:
24641     case DW_FORM_data1:
24642     case DW_FORM_data2:
24643     case DW_FORM_data4:
24644     case DW_FORM_data8:
24645     case DW_FORM_implicit_const:
24646       return 1;
24647     default:
24648       return 0;
24649     }
24650 }
24651
24652
24653 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24654    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24655
24656 static int
24657 attr_form_is_ref (const struct attribute *attr)
24658 {
24659   switch (attr->form)
24660     {
24661     case DW_FORM_ref_addr:
24662     case DW_FORM_ref1:
24663     case DW_FORM_ref2:
24664     case DW_FORM_ref4:
24665     case DW_FORM_ref8:
24666     case DW_FORM_ref_udata:
24667     case DW_FORM_GNU_ref_alt:
24668       return 1;
24669     default:
24670       return 0;
24671     }
24672 }
24673
24674 /* Return the .debug_loc section to use for CU.
24675    For DWO files use .debug_loc.dwo.  */
24676
24677 static struct dwarf2_section_info *
24678 cu_debug_loc_section (struct dwarf2_cu *cu)
24679 {
24680   struct dwarf2_per_objfile *dwarf2_per_objfile
24681     = cu->per_cu->dwarf2_per_objfile;
24682
24683   if (cu->dwo_unit)
24684     {
24685       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24686       
24687       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24688     }
24689   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24690                                   : &dwarf2_per_objfile->loc);
24691 }
24692
24693 /* A helper function that fills in a dwarf2_loclist_baton.  */
24694
24695 static void
24696 fill_in_loclist_baton (struct dwarf2_cu *cu,
24697                        struct dwarf2_loclist_baton *baton,
24698                        const struct attribute *attr)
24699 {
24700   struct dwarf2_per_objfile *dwarf2_per_objfile
24701     = cu->per_cu->dwarf2_per_objfile;
24702   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24703
24704   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24705
24706   baton->per_cu = cu->per_cu;
24707   gdb_assert (baton->per_cu);
24708   /* We don't know how long the location list is, but make sure we
24709      don't run off the edge of the section.  */
24710   baton->size = section->size - DW_UNSND (attr);
24711   baton->data = section->buffer + DW_UNSND (attr);
24712   baton->base_address = cu->base_address;
24713   baton->from_dwo = cu->dwo_unit != NULL;
24714 }
24715
24716 static void
24717 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24718                              struct dwarf2_cu *cu, int is_block)
24719 {
24720   struct dwarf2_per_objfile *dwarf2_per_objfile
24721     = cu->per_cu->dwarf2_per_objfile;
24722   struct objfile *objfile = dwarf2_per_objfile->objfile;
24723   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24724
24725   if (attr_form_is_section_offset (attr)
24726       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24727          the section.  If so, fall through to the complaint in the
24728          other branch.  */
24729       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24730     {
24731       struct dwarf2_loclist_baton *baton;
24732
24733       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24734
24735       fill_in_loclist_baton (cu, baton, attr);
24736
24737       if (cu->base_known == 0)
24738         complaint (_("Location list used without "
24739                      "specifying the CU base address."));
24740
24741       SYMBOL_ACLASS_INDEX (sym) = (is_block
24742                                    ? dwarf2_loclist_block_index
24743                                    : dwarf2_loclist_index);
24744       SYMBOL_LOCATION_BATON (sym) = baton;
24745     }
24746   else
24747     {
24748       struct dwarf2_locexpr_baton *baton;
24749
24750       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24751       baton->per_cu = cu->per_cu;
24752       gdb_assert (baton->per_cu);
24753
24754       if (attr_form_is_block (attr))
24755         {
24756           /* Note that we're just copying the block's data pointer
24757              here, not the actual data.  We're still pointing into the
24758              info_buffer for SYM's objfile; right now we never release
24759              that buffer, but when we do clean up properly this may
24760              need to change.  */
24761           baton->size = DW_BLOCK (attr)->size;
24762           baton->data = DW_BLOCK (attr)->data;
24763         }
24764       else
24765         {
24766           dwarf2_invalid_attrib_class_complaint ("location description",
24767                                                  SYMBOL_NATURAL_NAME (sym));
24768           baton->size = 0;
24769         }
24770
24771       SYMBOL_ACLASS_INDEX (sym) = (is_block
24772                                    ? dwarf2_locexpr_block_index
24773                                    : dwarf2_locexpr_index);
24774       SYMBOL_LOCATION_BATON (sym) = baton;
24775     }
24776 }
24777
24778 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24779    came from a separate debuginfo file, then the master objfile is
24780    returned.  */
24781
24782 struct objfile *
24783 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24784 {
24785   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24786
24787   /* Return the master objfile, so that we can report and look up the
24788      correct file containing this variable.  */
24789   if (objfile->separate_debug_objfile_backlink)
24790     objfile = objfile->separate_debug_objfile_backlink;
24791
24792   return objfile;
24793 }
24794
24795 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24796    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24797    CU_HEADERP first.  */
24798
24799 static const struct comp_unit_head *
24800 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24801                        struct dwarf2_per_cu_data *per_cu)
24802 {
24803   const gdb_byte *info_ptr;
24804
24805   if (per_cu->cu)
24806     return &per_cu->cu->header;
24807
24808   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24809
24810   memset (cu_headerp, 0, sizeof (*cu_headerp));
24811   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24812                        rcuh_kind::COMPILE);
24813
24814   return cu_headerp;
24815 }
24816
24817 /* Return the address size given in the compilation unit header for CU.  */
24818
24819 int
24820 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24821 {
24822   struct comp_unit_head cu_header_local;
24823   const struct comp_unit_head *cu_headerp;
24824
24825   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24826
24827   return cu_headerp->addr_size;
24828 }
24829
24830 /* Return the offset size given in the compilation unit header for CU.  */
24831
24832 int
24833 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24834 {
24835   struct comp_unit_head cu_header_local;
24836   const struct comp_unit_head *cu_headerp;
24837
24838   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24839
24840   return cu_headerp->offset_size;
24841 }
24842
24843 /* See its dwarf2loc.h declaration.  */
24844
24845 int
24846 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24847 {
24848   struct comp_unit_head cu_header_local;
24849   const struct comp_unit_head *cu_headerp;
24850
24851   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24852
24853   if (cu_headerp->version == 2)
24854     return cu_headerp->addr_size;
24855   else
24856     return cu_headerp->offset_size;
24857 }
24858
24859 /* Return the text offset of the CU.  The returned offset comes from
24860    this CU's objfile.  If this objfile came from a separate debuginfo
24861    file, then the offset may be different from the corresponding
24862    offset in the parent objfile.  */
24863
24864 CORE_ADDR
24865 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24866 {
24867   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24868
24869   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24870 }
24871
24872 /* Return DWARF version number of PER_CU.  */
24873
24874 short
24875 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24876 {
24877   return per_cu->dwarf_version;
24878 }
24879
24880 /* Locate the .debug_info compilation unit from CU's objfile which contains
24881    the DIE at OFFSET.  Raises an error on failure.  */
24882
24883 static struct dwarf2_per_cu_data *
24884 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24885                                   unsigned int offset_in_dwz,
24886                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24887 {
24888   struct dwarf2_per_cu_data *this_cu;
24889   int low, high;
24890   const sect_offset *cu_off;
24891
24892   low = 0;
24893   high = dwarf2_per_objfile->all_comp_units.size () - 1;
24894   while (high > low)
24895     {
24896       struct dwarf2_per_cu_data *mid_cu;
24897       int mid = low + (high - low) / 2;
24898
24899       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24900       cu_off = &mid_cu->sect_off;
24901       if (mid_cu->is_dwz > offset_in_dwz
24902           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24903         high = mid;
24904       else
24905         low = mid + 1;
24906     }
24907   gdb_assert (low == high);
24908   this_cu = dwarf2_per_objfile->all_comp_units[low];
24909   cu_off = &this_cu->sect_off;
24910   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24911     {
24912       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24913         error (_("Dwarf Error: could not find partial DIE containing "
24914                "offset %s [in module %s]"),
24915                sect_offset_str (sect_off),
24916                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
24917
24918       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24919                   <= sect_off);
24920       return dwarf2_per_objfile->all_comp_units[low-1];
24921     }
24922   else
24923     {
24924       this_cu = dwarf2_per_objfile->all_comp_units[low];
24925       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
24926           && sect_off >= this_cu->sect_off + this_cu->length)
24927         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
24928       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24929       return this_cu;
24930     }
24931 }
24932
24933 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24934
24935 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
24936   : per_cu (per_cu_),
24937     mark (0),
24938     has_loclist (0),
24939     checked_producer (0),
24940     producer_is_gxx_lt_4_6 (0),
24941     producer_is_gcc_lt_4_3 (0),
24942     producer_is_icc_lt_14 (0),
24943     processing_has_namespace_info (0)
24944 {
24945   per_cu->cu = this;
24946 }
24947
24948 /* Destroy a dwarf2_cu.  */
24949
24950 dwarf2_cu::~dwarf2_cu ()
24951 {
24952   per_cu->cu = NULL;
24953 }
24954
24955 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24956
24957 static void
24958 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24959                        enum language pretend_language)
24960 {
24961   struct attribute *attr;
24962
24963   /* Set the language we're debugging.  */
24964   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24965   if (attr)
24966     set_cu_language (DW_UNSND (attr), cu);
24967   else
24968     {
24969       cu->language = pretend_language;
24970       cu->language_defn = language_def (cu->language);
24971     }
24972
24973   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24974 }
24975
24976 /* Increase the age counter on each cached compilation unit, and free
24977    any that are too old.  */
24978
24979 static void
24980 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
24981 {
24982   struct dwarf2_per_cu_data *per_cu, **last_chain;
24983
24984   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
24985   per_cu = dwarf2_per_objfile->read_in_chain;
24986   while (per_cu != NULL)
24987     {
24988       per_cu->cu->last_used ++;
24989       if (per_cu->cu->last_used <= dwarf_max_cache_age)
24990         dwarf2_mark (per_cu->cu);
24991       per_cu = per_cu->cu->read_in_chain;
24992     }
24993
24994   per_cu = dwarf2_per_objfile->read_in_chain;
24995   last_chain = &dwarf2_per_objfile->read_in_chain;
24996   while (per_cu != NULL)
24997     {
24998       struct dwarf2_per_cu_data *next_cu;
24999
25000       next_cu = per_cu->cu->read_in_chain;
25001
25002       if (!per_cu->cu->mark)
25003         {
25004           delete per_cu->cu;
25005           *last_chain = next_cu;
25006         }
25007       else
25008         last_chain = &per_cu->cu->read_in_chain;
25009
25010       per_cu = next_cu;
25011     }
25012 }
25013
25014 /* Remove a single compilation unit from the cache.  */
25015
25016 static void
25017 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25018 {
25019   struct dwarf2_per_cu_data *per_cu, **last_chain;
25020   struct dwarf2_per_objfile *dwarf2_per_objfile
25021     = target_per_cu->dwarf2_per_objfile;
25022
25023   per_cu = dwarf2_per_objfile->read_in_chain;
25024   last_chain = &dwarf2_per_objfile->read_in_chain;
25025   while (per_cu != NULL)
25026     {
25027       struct dwarf2_per_cu_data *next_cu;
25028
25029       next_cu = per_cu->cu->read_in_chain;
25030
25031       if (per_cu == target_per_cu)
25032         {
25033           delete per_cu->cu;
25034           per_cu->cu = NULL;
25035           *last_chain = next_cu;
25036           break;
25037         }
25038       else
25039         last_chain = &per_cu->cu->read_in_chain;
25040
25041       per_cu = next_cu;
25042     }
25043 }
25044
25045 /* Cleanup function for the dwarf2_per_objfile data.  */
25046
25047 static void
25048 dwarf2_free_objfile (struct objfile *objfile, void *datum)
25049 {
25050   struct dwarf2_per_objfile *dwarf2_per_objfile
25051     = static_cast<struct dwarf2_per_objfile *> (datum);
25052
25053   delete dwarf2_per_objfile;
25054 }
25055
25056 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25057    We store these in a hash table separate from the DIEs, and preserve them
25058    when the DIEs are flushed out of cache.
25059
25060    The CU "per_cu" pointer is needed because offset alone is not enough to
25061    uniquely identify the type.  A file may have multiple .debug_types sections,
25062    or the type may come from a DWO file.  Furthermore, while it's more logical
25063    to use per_cu->section+offset, with Fission the section with the data is in
25064    the DWO file but we don't know that section at the point we need it.
25065    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25066    because we can enter the lookup routine, get_die_type_at_offset, from
25067    outside this file, and thus won't necessarily have PER_CU->cu.
25068    Fortunately, PER_CU is stable for the life of the objfile.  */
25069
25070 struct dwarf2_per_cu_offset_and_type
25071 {
25072   const struct dwarf2_per_cu_data *per_cu;
25073   sect_offset sect_off;
25074   struct type *type;
25075 };
25076
25077 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25078
25079 static hashval_t
25080 per_cu_offset_and_type_hash (const void *item)
25081 {
25082   const struct dwarf2_per_cu_offset_and_type *ofs
25083     = (const struct dwarf2_per_cu_offset_and_type *) item;
25084
25085   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25086 }
25087
25088 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25089
25090 static int
25091 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25092 {
25093   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25094     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25095   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25096     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25097
25098   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25099           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25100 }
25101
25102 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25103    table if necessary.  For convenience, return TYPE.
25104
25105    The DIEs reading must have careful ordering to:
25106     * Not cause infite loops trying to read in DIEs as a prerequisite for
25107       reading current DIE.
25108     * Not trying to dereference contents of still incompletely read in types
25109       while reading in other DIEs.
25110     * Enable referencing still incompletely read in types just by a pointer to
25111       the type without accessing its fields.
25112
25113    Therefore caller should follow these rules:
25114      * Try to fetch any prerequisite types we may need to build this DIE type
25115        before building the type and calling set_die_type.
25116      * After building type call set_die_type for current DIE as soon as
25117        possible before fetching more types to complete the current type.
25118      * Make the type as complete as possible before fetching more types.  */
25119
25120 static struct type *
25121 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25122 {
25123   struct dwarf2_per_objfile *dwarf2_per_objfile
25124     = cu->per_cu->dwarf2_per_objfile;
25125   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25126   struct objfile *objfile = dwarf2_per_objfile->objfile;
25127   struct attribute *attr;
25128   struct dynamic_prop prop;
25129
25130   /* For Ada types, make sure that the gnat-specific data is always
25131      initialized (if not already set).  There are a few types where
25132      we should not be doing so, because the type-specific area is
25133      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25134      where the type-specific area is used to store the floatformat).
25135      But this is not a problem, because the gnat-specific information
25136      is actually not needed for these types.  */
25137   if (need_gnat_info (cu)
25138       && TYPE_CODE (type) != TYPE_CODE_FUNC
25139       && TYPE_CODE (type) != TYPE_CODE_FLT
25140       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25141       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25142       && TYPE_CODE (type) != TYPE_CODE_METHOD
25143       && !HAVE_GNAT_AUX_INFO (type))
25144     INIT_GNAT_SPECIFIC (type);
25145
25146   /* Read DW_AT_allocated and set in type.  */
25147   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25148   if (attr_form_is_block (attr))
25149     {
25150       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25151         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25152     }
25153   else if (attr != NULL)
25154     {
25155       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25156                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25157                  sect_offset_str (die->sect_off));
25158     }
25159
25160   /* Read DW_AT_associated and set in type.  */
25161   attr = dwarf2_attr (die, DW_AT_associated, cu);
25162   if (attr_form_is_block (attr))
25163     {
25164       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25165         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25166     }
25167   else if (attr != NULL)
25168     {
25169       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25170                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25171                  sect_offset_str (die->sect_off));
25172     }
25173
25174   /* Read DW_AT_data_location and set in type.  */
25175   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25176   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25177     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25178
25179   if (dwarf2_per_objfile->die_type_hash == NULL)
25180     {
25181       dwarf2_per_objfile->die_type_hash =
25182         htab_create_alloc_ex (127,
25183                               per_cu_offset_and_type_hash,
25184                               per_cu_offset_and_type_eq,
25185                               NULL,
25186                               &objfile->objfile_obstack,
25187                               hashtab_obstack_allocate,
25188                               dummy_obstack_deallocate);
25189     }
25190
25191   ofs.per_cu = cu->per_cu;
25192   ofs.sect_off = die->sect_off;
25193   ofs.type = type;
25194   slot = (struct dwarf2_per_cu_offset_and_type **)
25195     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25196   if (*slot)
25197     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25198                sect_offset_str (die->sect_off));
25199   *slot = XOBNEW (&objfile->objfile_obstack,
25200                   struct dwarf2_per_cu_offset_and_type);
25201   **slot = ofs;
25202   return type;
25203 }
25204
25205 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25206    or return NULL if the die does not have a saved type.  */
25207
25208 static struct type *
25209 get_die_type_at_offset (sect_offset sect_off,
25210                         struct dwarf2_per_cu_data *per_cu)
25211 {
25212   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25213   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25214
25215   if (dwarf2_per_objfile->die_type_hash == NULL)
25216     return NULL;
25217
25218   ofs.per_cu = per_cu;
25219   ofs.sect_off = sect_off;
25220   slot = ((struct dwarf2_per_cu_offset_and_type *)
25221           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25222   if (slot)
25223     return slot->type;
25224   else
25225     return NULL;
25226 }
25227
25228 /* Look up the type for DIE in CU in die_type_hash,
25229    or return NULL if DIE does not have a saved type.  */
25230
25231 static struct type *
25232 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25233 {
25234   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25235 }
25236
25237 /* Add a dependence relationship from CU to REF_PER_CU.  */
25238
25239 static void
25240 dwarf2_add_dependence (struct dwarf2_cu *cu,
25241                        struct dwarf2_per_cu_data *ref_per_cu)
25242 {
25243   void **slot;
25244
25245   if (cu->dependencies == NULL)
25246     cu->dependencies
25247       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25248                               NULL, &cu->comp_unit_obstack,
25249                               hashtab_obstack_allocate,
25250                               dummy_obstack_deallocate);
25251
25252   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25253   if (*slot == NULL)
25254     *slot = ref_per_cu;
25255 }
25256
25257 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25258    Set the mark field in every compilation unit in the
25259    cache that we must keep because we are keeping CU.  */
25260
25261 static int
25262 dwarf2_mark_helper (void **slot, void *data)
25263 {
25264   struct dwarf2_per_cu_data *per_cu;
25265
25266   per_cu = (struct dwarf2_per_cu_data *) *slot;
25267
25268   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25269      reading of the chain.  As such dependencies remain valid it is not much
25270      useful to track and undo them during QUIT cleanups.  */
25271   if (per_cu->cu == NULL)
25272     return 1;
25273
25274   if (per_cu->cu->mark)
25275     return 1;
25276   per_cu->cu->mark = 1;
25277
25278   if (per_cu->cu->dependencies != NULL)
25279     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25280
25281   return 1;
25282 }
25283
25284 /* Set the mark field in CU and in every other compilation unit in the
25285    cache that we must keep because we are keeping CU.  */
25286
25287 static void
25288 dwarf2_mark (struct dwarf2_cu *cu)
25289 {
25290   if (cu->mark)
25291     return;
25292   cu->mark = 1;
25293   if (cu->dependencies != NULL)
25294     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25295 }
25296
25297 static void
25298 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25299 {
25300   while (per_cu)
25301     {
25302       per_cu->cu->mark = 0;
25303       per_cu = per_cu->cu->read_in_chain;
25304     }
25305 }
25306
25307 /* Trivial hash function for partial_die_info: the hash value of a DIE
25308    is its offset in .debug_info for this objfile.  */
25309
25310 static hashval_t
25311 partial_die_hash (const void *item)
25312 {
25313   const struct partial_die_info *part_die
25314     = (const struct partial_die_info *) item;
25315
25316   return to_underlying (part_die->sect_off);
25317 }
25318
25319 /* Trivial comparison function for partial_die_info structures: two DIEs
25320    are equal if they have the same offset.  */
25321
25322 static int
25323 partial_die_eq (const void *item_lhs, const void *item_rhs)
25324 {
25325   const struct partial_die_info *part_die_lhs
25326     = (const struct partial_die_info *) item_lhs;
25327   const struct partial_die_info *part_die_rhs
25328     = (const struct partial_die_info *) item_rhs;
25329
25330   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25331 }
25332
25333 static struct cmd_list_element *set_dwarf_cmdlist;
25334 static struct cmd_list_element *show_dwarf_cmdlist;
25335
25336 static void
25337 set_dwarf_cmd (const char *args, int from_tty)
25338 {
25339   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25340              gdb_stdout);
25341 }
25342
25343 static void
25344 show_dwarf_cmd (const char *args, int from_tty)
25345 {
25346   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25347 }
25348
25349 int dwarf_always_disassemble;
25350
25351 static void
25352 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25353                                struct cmd_list_element *c, const char *value)
25354 {
25355   fprintf_filtered (file,
25356                     _("Whether to always disassemble "
25357                       "DWARF expressions is %s.\n"),
25358                     value);
25359 }
25360
25361 static void
25362 show_check_physname (struct ui_file *file, int from_tty,
25363                      struct cmd_list_element *c, const char *value)
25364 {
25365   fprintf_filtered (file,
25366                     _("Whether to check \"physname\" is %s.\n"),
25367                     value);
25368 }
25369
25370 void
25371 _initialize_dwarf2_read (void)
25372 {
25373   dwarf2_objfile_data_key
25374     = register_objfile_data_with_cleanup (nullptr, dwarf2_free_objfile);
25375
25376   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25377 Set DWARF specific variables.\n\
25378 Configure DWARF variables such as the cache size"),
25379                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25380                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25381
25382   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25383 Show DWARF specific variables\n\
25384 Show DWARF variables such as the cache size"),
25385                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25386                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25387
25388   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25389                             &dwarf_max_cache_age, _("\
25390 Set the upper bound on the age of cached DWARF compilation units."), _("\
25391 Show the upper bound on the age of cached DWARF compilation units."), _("\
25392 A higher limit means that cached compilation units will be stored\n\
25393 in memory longer, and more total memory will be used.  Zero disables\n\
25394 caching, which can slow down startup."),
25395                             NULL,
25396                             show_dwarf_max_cache_age,
25397                             &set_dwarf_cmdlist,
25398                             &show_dwarf_cmdlist);
25399
25400   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25401                            &dwarf_always_disassemble, _("\
25402 Set whether `info address' always disassembles DWARF expressions."), _("\
25403 Show whether `info address' always disassembles DWARF expressions."), _("\
25404 When enabled, DWARF expressions are always printed in an assembly-like\n\
25405 syntax.  When disabled, expressions will be printed in a more\n\
25406 conversational style, when possible."),
25407                            NULL,
25408                            show_dwarf_always_disassemble,
25409                            &set_dwarf_cmdlist,
25410                            &show_dwarf_cmdlist);
25411
25412   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25413 Set debugging of the DWARF reader."), _("\
25414 Show debugging of the DWARF reader."), _("\
25415 When enabled (non-zero), debugging messages are printed during DWARF\n\
25416 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25417 information.  A value greater than 1 provides more verbose information."),
25418                             NULL,
25419                             NULL,
25420                             &setdebuglist, &showdebuglist);
25421
25422   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25423 Set debugging of the DWARF DIE reader."), _("\
25424 Show debugging of the DWARF DIE reader."), _("\
25425 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25426 The value is the maximum depth to print."),
25427                              NULL,
25428                              NULL,
25429                              &setdebuglist, &showdebuglist);
25430
25431   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25432 Set debugging of the dwarf line reader."), _("\
25433 Show debugging of the dwarf line reader."), _("\
25434 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25435 A value of 1 (one) provides basic information.\n\
25436 A value greater than 1 provides more verbose information."),
25437                              NULL,
25438                              NULL,
25439                              &setdebuglist, &showdebuglist);
25440
25441   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25442 Set cross-checking of \"physname\" code against demangler."), _("\
25443 Show cross-checking of \"physname\" code against demangler."), _("\
25444 When enabled, GDB's internal \"physname\" code is checked against\n\
25445 the demangler."),
25446                            NULL, show_check_physname,
25447                            &setdebuglist, &showdebuglist);
25448
25449   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25450                            no_class, &use_deprecated_index_sections, _("\
25451 Set whether to use deprecated gdb_index sections."), _("\
25452 Show whether to use deprecated gdb_index sections."), _("\
25453 When enabled, deprecated .gdb_index sections are used anyway.\n\
25454 Normally they are ignored either because of a missing feature or\n\
25455 performance issue.\n\
25456 Warning: This option must be enabled before gdb reads the file."),
25457                            NULL,
25458                            NULL,
25459                            &setlist, &showlist);
25460
25461   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25462                                                         &dwarf2_locexpr_funcs);
25463   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25464                                                         &dwarf2_loclist_funcs);
25465
25466   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25467                                         &dwarf2_block_frame_base_locexpr_funcs);
25468   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25469                                         &dwarf2_block_frame_base_loclist_funcs);
25470
25471 #if GDB_SELF_TEST
25472   selftests::register_test ("dw2_expand_symtabs_matching",
25473                             selftests::dw2_expand_symtabs_matching::run_test);
25474 #endif
25475 }