e4b621d159c5ada50b9c3646bbdf68c66d7fd42c
[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) - baseaddr;
3181       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - 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                    - baseaddr);
3341           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
3342                  - baseaddr);
3343           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3344         }
3345     }
3346
3347   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3348                                                     &objfile->objfile_obstack);
3349 }
3350
3351 /* Find a slot in the mapped index INDEX for the object named NAME.
3352    If NAME is found, set *VEC_OUT to point to the CU vector in the
3353    constant pool and return true.  If NAME cannot be found, return
3354    false.  */
3355
3356 static bool
3357 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3358                           offset_type **vec_out)
3359 {
3360   offset_type hash;
3361   offset_type slot, step;
3362   int (*cmp) (const char *, const char *);
3363
3364   gdb::unique_xmalloc_ptr<char> without_params;
3365   if (current_language->la_language == language_cplus
3366       || current_language->la_language == language_fortran
3367       || current_language->la_language == language_d)
3368     {
3369       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3370          not contain any.  */
3371
3372       if (strchr (name, '(') != NULL)
3373         {
3374           without_params = cp_remove_params (name);
3375
3376           if (without_params != NULL)
3377             name = without_params.get ();
3378         }
3379     }
3380
3381   /* Index version 4 did not support case insensitive searches.  But the
3382      indices for case insensitive languages are built in lowercase, therefore
3383      simulate our NAME being searched is also lowercased.  */
3384   hash = mapped_index_string_hash ((index->version == 4
3385                                     && case_sensitivity == case_sensitive_off
3386                                     ? 5 : index->version),
3387                                    name);
3388
3389   slot = hash & (index->symbol_table.size () - 1);
3390   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3391   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3392
3393   for (;;)
3394     {
3395       const char *str;
3396
3397       const auto &bucket = index->symbol_table[slot];
3398       if (bucket.name == 0 && bucket.vec == 0)
3399         return false;
3400
3401       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3402       if (!cmp (name, str))
3403         {
3404           *vec_out = (offset_type *) (index->constant_pool
3405                                       + MAYBE_SWAP (bucket.vec));
3406           return true;
3407         }
3408
3409       slot = (slot + step) & (index->symbol_table.size () - 1);
3410     }
3411 }
3412
3413 /* A helper function that reads the .gdb_index from SECTION and fills
3414    in MAP.  FILENAME is the name of the file containing the section;
3415    it is used for error reporting.  DEPRECATED_OK is true if it is
3416    ok to use deprecated sections.
3417
3418    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3419    out parameters that are filled in with information about the CU and
3420    TU lists in the section.
3421
3422    Returns 1 if all went well, 0 otherwise.  */
3423
3424 static bool
3425 read_gdb_index_from_section (struct objfile *objfile,
3426                              const char *filename,
3427                              bool deprecated_ok,
3428                              struct dwarf2_section_info *section,
3429                              struct mapped_index *map,
3430                              const gdb_byte **cu_list,
3431                              offset_type *cu_list_elements,
3432                              const gdb_byte **types_list,
3433                              offset_type *types_list_elements)
3434 {
3435   const gdb_byte *addr;
3436   offset_type version;
3437   offset_type *metadata;
3438   int i;
3439
3440   if (dwarf2_section_empty_p (section))
3441     return 0;
3442
3443   /* Older elfutils strip versions could keep the section in the main
3444      executable while splitting it for the separate debug info file.  */
3445   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3446     return 0;
3447
3448   dwarf2_read_section (objfile, section);
3449
3450   addr = section->buffer;
3451   /* Version check.  */
3452   version = MAYBE_SWAP (*(offset_type *) addr);
3453   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3454      causes the index to behave very poorly for certain requests.  Version 3
3455      contained incomplete addrmap.  So, it seems better to just ignore such
3456      indices.  */
3457   if (version < 4)
3458     {
3459       static int warning_printed = 0;
3460       if (!warning_printed)
3461         {
3462           warning (_("Skipping obsolete .gdb_index section in %s."),
3463                    filename);
3464           warning_printed = 1;
3465         }
3466       return 0;
3467     }
3468   /* Index version 4 uses a different hash function than index version
3469      5 and later.
3470
3471      Versions earlier than 6 did not emit psymbols for inlined
3472      functions.  Using these files will cause GDB not to be able to
3473      set breakpoints on inlined functions by name, so we ignore these
3474      indices unless the user has done
3475      "set use-deprecated-index-sections on".  */
3476   if (version < 6 && !deprecated_ok)
3477     {
3478       static int warning_printed = 0;
3479       if (!warning_printed)
3480         {
3481           warning (_("\
3482 Skipping deprecated .gdb_index section in %s.\n\
3483 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3484 to use the section anyway."),
3485                    filename);
3486           warning_printed = 1;
3487         }
3488       return 0;
3489     }
3490   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3491      of the TU (for symbols coming from TUs),
3492      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3493      Plus gold-generated indices can have duplicate entries for global symbols,
3494      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3495      These are just performance bugs, and we can't distinguish gdb-generated
3496      indices from gold-generated ones, so issue no warning here.  */
3497
3498   /* Indexes with higher version than the one supported by GDB may be no
3499      longer backward compatible.  */
3500   if (version > 8)
3501     return 0;
3502
3503   map->version = version;
3504
3505   metadata = (offset_type *) (addr + sizeof (offset_type));
3506
3507   i = 0;
3508   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3509   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3510                        / 8);
3511   ++i;
3512
3513   *types_list = addr + MAYBE_SWAP (metadata[i]);
3514   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3515                            - MAYBE_SWAP (metadata[i]))
3516                           / 8);
3517   ++i;
3518
3519   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3520   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3521   map->address_table
3522     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3523   ++i;
3524
3525   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3526   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3527   map->symbol_table
3528     = gdb::array_view<mapped_index::symbol_table_slot>
3529        ((mapped_index::symbol_table_slot *) symbol_table,
3530         (mapped_index::symbol_table_slot *) symbol_table_end);
3531
3532   ++i;
3533   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3534
3535   return 1;
3536 }
3537
3538 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3539    elements of all the CUs and return 1.  Otherwise, return 0.  */
3540
3541 static int
3542 dwarf2_read_gdb_index (struct dwarf2_per_objfile *dwarf2_per_objfile)
3543 {
3544   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3545   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3546   struct dwz_file *dwz;
3547   struct objfile *objfile = dwarf2_per_objfile->objfile;
3548
3549   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3550   if (!read_gdb_index_from_section (objfile, objfile_name (objfile),
3551                                     use_deprecated_index_sections,
3552                                     &dwarf2_per_objfile->gdb_index, map.get (),
3553                                     &cu_list, &cu_list_elements,
3554                                     &types_list, &types_list_elements))
3555     return 0;
3556
3557   /* Don't use the index if it's empty.  */
3558   if (map->symbol_table.empty ())
3559     return 0;
3560
3561   /* If there is a .dwz file, read it so we can get its CU list as
3562      well.  */
3563   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3564   if (dwz != NULL)
3565     {
3566       struct mapped_index dwz_map;
3567       const gdb_byte *dwz_types_ignore;
3568       offset_type dwz_types_elements_ignore;
3569
3570       if (!read_gdb_index_from_section (objfile,
3571                                         bfd_get_filename (dwz->dwz_bfd), 1,
3572                                         &dwz->gdb_index, &dwz_map,
3573                                         &dwz_list, &dwz_list_elements,
3574                                         &dwz_types_ignore,
3575                                         &dwz_types_elements_ignore))
3576         {
3577           warning (_("could not read '.gdb_index' section from %s; skipping"),
3578                    bfd_get_filename (dwz->dwz_bfd));
3579           return 0;
3580         }
3581     }
3582
3583   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3584                          dwz_list, dwz_list_elements);
3585
3586   if (types_list_elements)
3587     {
3588       struct dwarf2_section_info *section;
3589
3590       /* We can only handle a single .debug_types when we have an
3591          index.  */
3592       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3593         return 0;
3594
3595       section = VEC_index (dwarf2_section_info_def,
3596                            dwarf2_per_objfile->types, 0);
3597
3598       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3599                                                types_list, types_list_elements);
3600     }
3601
3602   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3603
3604   dwarf2_per_objfile->index_table = std::move (map);
3605   dwarf2_per_objfile->using_index = 1;
3606   dwarf2_per_objfile->quick_file_names_table =
3607     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3608
3609   return 1;
3610 }
3611
3612 /* die_reader_func for dw2_get_file_names.  */
3613
3614 static void
3615 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3616                            const gdb_byte *info_ptr,
3617                            struct die_info *comp_unit_die,
3618                            int has_children,
3619                            void *data)
3620 {
3621   struct dwarf2_cu *cu = reader->cu;
3622   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3623   struct dwarf2_per_objfile *dwarf2_per_objfile
3624     = cu->per_cu->dwarf2_per_objfile;
3625   struct objfile *objfile = dwarf2_per_objfile->objfile;
3626   struct dwarf2_per_cu_data *lh_cu;
3627   struct attribute *attr;
3628   int i;
3629   void **slot;
3630   struct quick_file_names *qfn;
3631
3632   gdb_assert (! this_cu->is_debug_types);
3633
3634   /* Our callers never want to match partial units -- instead they
3635      will match the enclosing full CU.  */
3636   if (comp_unit_die->tag == DW_TAG_partial_unit)
3637     {
3638       this_cu->v.quick->no_file_data = 1;
3639       return;
3640     }
3641
3642   lh_cu = this_cu;
3643   slot = NULL;
3644
3645   line_header_up lh;
3646   sect_offset line_offset {};
3647
3648   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3649   if (attr)
3650     {
3651       struct quick_file_names find_entry;
3652
3653       line_offset = (sect_offset) DW_UNSND (attr);
3654
3655       /* We may have already read in this line header (TU line header sharing).
3656          If we have we're done.  */
3657       find_entry.hash.dwo_unit = cu->dwo_unit;
3658       find_entry.hash.line_sect_off = line_offset;
3659       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3660                              &find_entry, INSERT);
3661       if (*slot != NULL)
3662         {
3663           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3664           return;
3665         }
3666
3667       lh = dwarf_decode_line_header (line_offset, cu);
3668     }
3669   if (lh == NULL)
3670     {
3671       lh_cu->v.quick->no_file_data = 1;
3672       return;
3673     }
3674
3675   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3676   qfn->hash.dwo_unit = cu->dwo_unit;
3677   qfn->hash.line_sect_off = line_offset;
3678   gdb_assert (slot != NULL);
3679   *slot = qfn;
3680
3681   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3682
3683   qfn->num_file_names = lh->file_names.size ();
3684   qfn->file_names =
3685     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3686   for (i = 0; i < lh->file_names.size (); ++i)
3687     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3688   qfn->real_names = NULL;
3689
3690   lh_cu->v.quick->file_names = qfn;
3691 }
3692
3693 /* A helper for the "quick" functions which attempts to read the line
3694    table for THIS_CU.  */
3695
3696 static struct quick_file_names *
3697 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3698 {
3699   /* This should never be called for TUs.  */
3700   gdb_assert (! this_cu->is_debug_types);
3701   /* Nor type unit groups.  */
3702   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3703
3704   if (this_cu->v.quick->file_names != NULL)
3705     return this_cu->v.quick->file_names;
3706   /* If we know there is no line data, no point in looking again.  */
3707   if (this_cu->v.quick->no_file_data)
3708     return NULL;
3709
3710   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3711
3712   if (this_cu->v.quick->no_file_data)
3713     return NULL;
3714   return this_cu->v.quick->file_names;
3715 }
3716
3717 /* A helper for the "quick" functions which computes and caches the
3718    real path for a given file name from the line table.  */
3719
3720 static const char *
3721 dw2_get_real_path (struct objfile *objfile,
3722                    struct quick_file_names *qfn, int index)
3723 {
3724   if (qfn->real_names == NULL)
3725     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3726                                       qfn->num_file_names, const char *);
3727
3728   if (qfn->real_names[index] == NULL)
3729     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3730
3731   return qfn->real_names[index];
3732 }
3733
3734 static struct symtab *
3735 dw2_find_last_source_symtab (struct objfile *objfile)
3736 {
3737   struct dwarf2_per_objfile *dwarf2_per_objfile
3738     = get_dwarf2_per_objfile (objfile);
3739   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3740   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3741
3742   if (cust == NULL)
3743     return NULL;
3744
3745   return compunit_primary_filetab (cust);
3746 }
3747
3748 /* Traversal function for dw2_forget_cached_source_info.  */
3749
3750 static int
3751 dw2_free_cached_file_names (void **slot, void *info)
3752 {
3753   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3754
3755   if (file_data->real_names)
3756     {
3757       int i;
3758
3759       for (i = 0; i < file_data->num_file_names; ++i)
3760         {
3761           xfree ((void*) file_data->real_names[i]);
3762           file_data->real_names[i] = NULL;
3763         }
3764     }
3765
3766   return 1;
3767 }
3768
3769 static void
3770 dw2_forget_cached_source_info (struct objfile *objfile)
3771 {
3772   struct dwarf2_per_objfile *dwarf2_per_objfile
3773     = get_dwarf2_per_objfile (objfile);
3774
3775   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3776                           dw2_free_cached_file_names, NULL);
3777 }
3778
3779 /* Helper function for dw2_map_symtabs_matching_filename that expands
3780    the symtabs and calls the iterator.  */
3781
3782 static int
3783 dw2_map_expand_apply (struct objfile *objfile,
3784                       struct dwarf2_per_cu_data *per_cu,
3785                       const char *name, const char *real_path,
3786                       gdb::function_view<bool (symtab *)> callback)
3787 {
3788   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3789
3790   /* Don't visit already-expanded CUs.  */
3791   if (per_cu->v.quick->compunit_symtab)
3792     return 0;
3793
3794   /* This may expand more than one symtab, and we want to iterate over
3795      all of them.  */
3796   dw2_instantiate_symtab (per_cu, false);
3797
3798   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3799                                     last_made, callback);
3800 }
3801
3802 /* Implementation of the map_symtabs_matching_filename method.  */
3803
3804 static bool
3805 dw2_map_symtabs_matching_filename
3806   (struct objfile *objfile, const char *name, const char *real_path,
3807    gdb::function_view<bool (symtab *)> callback)
3808 {
3809   const char *name_basename = lbasename (name);
3810   struct dwarf2_per_objfile *dwarf2_per_objfile
3811     = get_dwarf2_per_objfile (objfile);
3812
3813   /* The rule is CUs specify all the files, including those used by
3814      any TU, so there's no need to scan TUs here.  */
3815
3816   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3817     {
3818       /* We only need to look at symtabs not already expanded.  */
3819       if (per_cu->v.quick->compunit_symtab)
3820         continue;
3821
3822       quick_file_names *file_data = dw2_get_file_names (per_cu);
3823       if (file_data == NULL)
3824         continue;
3825
3826       for (int j = 0; j < file_data->num_file_names; ++j)
3827         {
3828           const char *this_name = file_data->file_names[j];
3829           const char *this_real_name;
3830
3831           if (compare_filenames_for_search (this_name, name))
3832             {
3833               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3834                                         callback))
3835                 return true;
3836               continue;
3837             }
3838
3839           /* Before we invoke realpath, which can get expensive when many
3840              files are involved, do a quick comparison of the basenames.  */
3841           if (! basenames_may_differ
3842               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3843             continue;
3844
3845           this_real_name = dw2_get_real_path (objfile, file_data, j);
3846           if (compare_filenames_for_search (this_real_name, name))
3847             {
3848               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3849                                         callback))
3850                 return true;
3851               continue;
3852             }
3853
3854           if (real_path != NULL)
3855             {
3856               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3857               gdb_assert (IS_ABSOLUTE_PATH (name));
3858               if (this_real_name != NULL
3859                   && FILENAME_CMP (real_path, this_real_name) == 0)
3860                 {
3861                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3862                                             callback))
3863                     return true;
3864                   continue;
3865                 }
3866             }
3867         }
3868     }
3869
3870   return false;
3871 }
3872
3873 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3874
3875 struct dw2_symtab_iterator
3876 {
3877   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3878   struct dwarf2_per_objfile *dwarf2_per_objfile;
3879   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3880   int want_specific_block;
3881   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3882      Unused if !WANT_SPECIFIC_BLOCK.  */
3883   int block_index;
3884   /* The kind of symbol we're looking for.  */
3885   domain_enum domain;
3886   /* The list of CUs from the index entry of the symbol,
3887      or NULL if not found.  */
3888   offset_type *vec;
3889   /* The next element in VEC to look at.  */
3890   int next;
3891   /* The number of elements in VEC, or zero if there is no match.  */
3892   int length;
3893   /* Have we seen a global version of the symbol?
3894      If so we can ignore all further global instances.
3895      This is to work around gold/15646, inefficient gold-generated
3896      indices.  */
3897   int global_seen;
3898 };
3899
3900 /* Initialize the index symtab iterator ITER.
3901    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3902    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3903
3904 static void
3905 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3906                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3907                       int want_specific_block,
3908                       int block_index,
3909                       domain_enum domain,
3910                       const char *name)
3911 {
3912   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3913   iter->want_specific_block = want_specific_block;
3914   iter->block_index = block_index;
3915   iter->domain = domain;
3916   iter->next = 0;
3917   iter->global_seen = 0;
3918
3919   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3920
3921   /* index is NULL if OBJF_READNOW.  */
3922   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3923     iter->length = MAYBE_SWAP (*iter->vec);
3924   else
3925     {
3926       iter->vec = NULL;
3927       iter->length = 0;
3928     }
3929 }
3930
3931 /* Return the next matching CU or NULL if there are no more.  */
3932
3933 static struct dwarf2_per_cu_data *
3934 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3935 {
3936   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3937
3938   for ( ; iter->next < iter->length; ++iter->next)
3939     {
3940       offset_type cu_index_and_attrs =
3941         MAYBE_SWAP (iter->vec[iter->next + 1]);
3942       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3943       int want_static = iter->block_index != GLOBAL_BLOCK;
3944       /* This value is only valid for index versions >= 7.  */
3945       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3946       gdb_index_symbol_kind symbol_kind =
3947         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3948       /* Only check the symbol attributes if they're present.
3949          Indices prior to version 7 don't record them,
3950          and indices >= 7 may elide them for certain symbols
3951          (gold does this).  */
3952       int attrs_valid =
3953         (dwarf2_per_objfile->index_table->version >= 7
3954          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3955
3956       /* Don't crash on bad data.  */
3957       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3958                        + dwarf2_per_objfile->all_type_units.size ()))
3959         {
3960           complaint (_(".gdb_index entry has bad CU index"
3961                        " [in module %s]"),
3962                      objfile_name (dwarf2_per_objfile->objfile));
3963           continue;
3964         }
3965
3966       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3967
3968       /* Skip if already read in.  */
3969       if (per_cu->v.quick->compunit_symtab)
3970         continue;
3971
3972       /* Check static vs global.  */
3973       if (attrs_valid)
3974         {
3975           if (iter->want_specific_block
3976               && want_static != is_static)
3977             continue;
3978           /* Work around gold/15646.  */
3979           if (!is_static && iter->global_seen)
3980             continue;
3981           if (!is_static)
3982             iter->global_seen = 1;
3983         }
3984
3985       /* Only check the symbol's kind if it has one.  */
3986       if (attrs_valid)
3987         {
3988           switch (iter->domain)
3989             {
3990             case VAR_DOMAIN:
3991               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3992                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3993                   /* Some types are also in VAR_DOMAIN.  */
3994                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3995                 continue;
3996               break;
3997             case STRUCT_DOMAIN:
3998               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3999                 continue;
4000               break;
4001             case LABEL_DOMAIN:
4002               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4003                 continue;
4004               break;
4005             default:
4006               break;
4007             }
4008         }
4009
4010       ++iter->next;
4011       return per_cu;
4012     }
4013
4014   return NULL;
4015 }
4016
4017 static struct compunit_symtab *
4018 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4019                    const char *name, domain_enum domain)
4020 {
4021   struct compunit_symtab *stab_best = NULL;
4022   struct dwarf2_per_objfile *dwarf2_per_objfile
4023     = get_dwarf2_per_objfile (objfile);
4024
4025   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4026
4027   struct dw2_symtab_iterator iter;
4028   struct dwarf2_per_cu_data *per_cu;
4029
4030   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4031
4032   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4033     {
4034       struct symbol *sym, *with_opaque = NULL;
4035       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
4036       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4037       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4038
4039       sym = block_find_symbol (block, name, domain,
4040                                block_find_non_opaque_type_preferred,
4041                                &with_opaque);
4042
4043       /* Some caution must be observed with overloaded functions
4044          and methods, since the index will not contain any overload
4045          information (but NAME might contain it).  */
4046
4047       if (sym != NULL
4048           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4049         return stab;
4050       if (with_opaque != NULL
4051           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4052         stab_best = stab;
4053
4054       /* Keep looking through other CUs.  */
4055     }
4056
4057   return stab_best;
4058 }
4059
4060 static void
4061 dw2_print_stats (struct objfile *objfile)
4062 {
4063   struct dwarf2_per_objfile *dwarf2_per_objfile
4064     = get_dwarf2_per_objfile (objfile);
4065   int total = (dwarf2_per_objfile->all_comp_units.size ()
4066                + dwarf2_per_objfile->all_type_units.size ());
4067   int count = 0;
4068
4069   for (int i = 0; i < total; ++i)
4070     {
4071       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4072
4073       if (!per_cu->v.quick->compunit_symtab)
4074         ++count;
4075     }
4076   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4077   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4078 }
4079
4080 /* This dumps minimal information about the index.
4081    It is called via "mt print objfiles".
4082    One use is to verify .gdb_index has been loaded by the
4083    gdb.dwarf2/gdb-index.exp testcase.  */
4084
4085 static void
4086 dw2_dump (struct objfile *objfile)
4087 {
4088   struct dwarf2_per_objfile *dwarf2_per_objfile
4089     = get_dwarf2_per_objfile (objfile);
4090
4091   gdb_assert (dwarf2_per_objfile->using_index);
4092   printf_filtered (".gdb_index:");
4093   if (dwarf2_per_objfile->index_table != NULL)
4094     {
4095       printf_filtered (" version %d\n",
4096                        dwarf2_per_objfile->index_table->version);
4097     }
4098   else
4099     printf_filtered (" faked for \"readnow\"\n");
4100   printf_filtered ("\n");
4101 }
4102
4103 static void
4104 dw2_expand_symtabs_for_function (struct objfile *objfile,
4105                                  const char *func_name)
4106 {
4107   struct dwarf2_per_objfile *dwarf2_per_objfile
4108     = get_dwarf2_per_objfile (objfile);
4109
4110   struct dw2_symtab_iterator iter;
4111   struct dwarf2_per_cu_data *per_cu;
4112
4113   /* Note: It doesn't matter what we pass for block_index here.  */
4114   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4115                         func_name);
4116
4117   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4118     dw2_instantiate_symtab (per_cu, false);
4119
4120 }
4121
4122 static void
4123 dw2_expand_all_symtabs (struct objfile *objfile)
4124 {
4125   struct dwarf2_per_objfile *dwarf2_per_objfile
4126     = get_dwarf2_per_objfile (objfile);
4127   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4128                      + dwarf2_per_objfile->all_type_units.size ());
4129
4130   for (int i = 0; i < total_units; ++i)
4131     {
4132       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4133
4134       /* We don't want to directly expand a partial CU, because if we
4135          read it with the wrong language, then assertion failures can
4136          be triggered later on.  See PR symtab/23010.  So, tell
4137          dw2_instantiate_symtab to skip partial CUs -- any important
4138          partial CU will be read via DW_TAG_imported_unit anyway.  */
4139       dw2_instantiate_symtab (per_cu, true);
4140     }
4141 }
4142
4143 static void
4144 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4145                                   const char *fullname)
4146 {
4147   struct dwarf2_per_objfile *dwarf2_per_objfile
4148     = get_dwarf2_per_objfile (objfile);
4149
4150   /* We don't need to consider type units here.
4151      This is only called for examining code, e.g. expand_line_sal.
4152      There can be an order of magnitude (or more) more type units
4153      than comp units, and we avoid them if we can.  */
4154
4155   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4156     {
4157       /* We only need to look at symtabs not already expanded.  */
4158       if (per_cu->v.quick->compunit_symtab)
4159         continue;
4160
4161       quick_file_names *file_data = dw2_get_file_names (per_cu);
4162       if (file_data == NULL)
4163         continue;
4164
4165       for (int j = 0; j < file_data->num_file_names; ++j)
4166         {
4167           const char *this_fullname = file_data->file_names[j];
4168
4169           if (filename_cmp (this_fullname, fullname) == 0)
4170             {
4171               dw2_instantiate_symtab (per_cu, false);
4172               break;
4173             }
4174         }
4175     }
4176 }
4177
4178 static void
4179 dw2_map_matching_symbols (struct objfile *objfile,
4180                           const char * name, domain_enum domain,
4181                           int global,
4182                           int (*callback) (struct block *,
4183                                            struct symbol *, void *),
4184                           void *data, symbol_name_match_type match,
4185                           symbol_compare_ftype *ordered_compare)
4186 {
4187   /* Currently unimplemented; used for Ada.  The function can be called if the
4188      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4189      does not look for non-Ada symbols this function should just return.  */
4190 }
4191
4192 /* Symbol name matcher for .gdb_index names.
4193
4194    Symbol names in .gdb_index have a few particularities:
4195
4196    - There's no indication of which is the language of each symbol.
4197
4198      Since each language has its own symbol name matching algorithm,
4199      and we don't know which language is the right one, we must match
4200      each symbol against all languages.  This would be a potential
4201      performance problem if it were not mitigated by the
4202      mapped_index::name_components lookup table, which significantly
4203      reduces the number of times we need to call into this matcher,
4204      making it a non-issue.
4205
4206    - Symbol names in the index have no overload (parameter)
4207      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4208      appear as "foo" in the index, for example.
4209
4210      This means that the lookup names passed to the symbol name
4211      matcher functions must have no parameter information either
4212      because (e.g.) symbol search name "foo" does not match
4213      lookup-name "foo(int)" [while swapping search name for lookup
4214      name would match].
4215 */
4216 class gdb_index_symbol_name_matcher
4217 {
4218 public:
4219   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4220   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4221
4222   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4223      Returns true if any matcher matches.  */
4224   bool matches (const char *symbol_name);
4225
4226 private:
4227   /* A reference to the lookup name we're matching against.  */
4228   const lookup_name_info &m_lookup_name;
4229
4230   /* A vector holding all the different symbol name matchers, for all
4231      languages.  */
4232   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4233 };
4234
4235 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4236   (const lookup_name_info &lookup_name)
4237     : m_lookup_name (lookup_name)
4238 {
4239   /* Prepare the vector of comparison functions upfront, to avoid
4240      doing the same work for each symbol.  Care is taken to avoid
4241      matching with the same matcher more than once if/when multiple
4242      languages use the same matcher function.  */
4243   auto &matchers = m_symbol_name_matcher_funcs;
4244   matchers.reserve (nr_languages);
4245
4246   matchers.push_back (default_symbol_name_matcher);
4247
4248   for (int i = 0; i < nr_languages; i++)
4249     {
4250       const language_defn *lang = language_def ((enum language) i);
4251       symbol_name_matcher_ftype *name_matcher
4252         = get_symbol_name_matcher (lang, m_lookup_name);
4253
4254       /* Don't insert the same comparison routine more than once.
4255          Note that we do this linear walk instead of a seemingly
4256          cheaper sorted insert, or use a std::set or something like
4257          that, because relative order of function addresses is not
4258          stable.  This is not a problem in practice because the number
4259          of supported languages is low, and the cost here is tiny
4260          compared to the number of searches we'll do afterwards using
4261          this object.  */
4262       if (name_matcher != default_symbol_name_matcher
4263           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4264               == matchers.end ()))
4265         matchers.push_back (name_matcher);
4266     }
4267 }
4268
4269 bool
4270 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4271 {
4272   for (auto matches_name : m_symbol_name_matcher_funcs)
4273     if (matches_name (symbol_name, m_lookup_name, NULL))
4274       return true;
4275
4276   return false;
4277 }
4278
4279 /* Starting from a search name, return the string that finds the upper
4280    bound of all strings that start with SEARCH_NAME in a sorted name
4281    list.  Returns the empty string to indicate that the upper bound is
4282    the end of the list.  */
4283
4284 static std::string
4285 make_sort_after_prefix_name (const char *search_name)
4286 {
4287   /* When looking to complete "func", we find the upper bound of all
4288      symbols that start with "func" by looking for where we'd insert
4289      the closest string that would follow "func" in lexicographical
4290      order.  Usually, that's "func"-with-last-character-incremented,
4291      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4292      will be UTF-8 multi-byte sequences, but we can't be certain.
4293      Especially mind the 0xff character, which is a valid character in
4294      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4295      rule out compilers allowing it in identifiers.  Note that
4296      conveniently, strcmp/strcasecmp are specified to compare
4297      characters interpreted as unsigned char.  So what we do is treat
4298      the whole string as a base 256 number composed of a sequence of
4299      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4300      to 0, and carries 1 to the following more-significant position.
4301      If the very first character in SEARCH_NAME ends up incremented
4302      and carries/overflows, then the upper bound is the end of the
4303      list.  The string after the empty string is also the empty
4304      string.
4305
4306      Some examples of this operation:
4307
4308        SEARCH_NAME  => "+1" RESULT
4309
4310        "abc"              => "abd"
4311        "ab\xff"           => "ac"
4312        "\xff" "a" "\xff"  => "\xff" "b"
4313        "\xff"             => ""
4314        "\xff\xff"         => ""
4315        ""                 => ""
4316
4317      Then, with these symbols for example:
4318
4319       func
4320       func1
4321       fund
4322
4323      completing "func" looks for symbols between "func" and
4324      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4325      which finds "func" and "func1", but not "fund".
4326
4327      And with:
4328
4329       funcÿ     (Latin1 'ÿ' [0xff])
4330       funcÿ1
4331       fund
4332
4333      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4334      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4335
4336      And with:
4337
4338       ÿÿ        (Latin1 'ÿ' [0xff])
4339       ÿÿ1
4340
4341      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4342      the end of the list.
4343   */
4344   std::string after = search_name;
4345   while (!after.empty () && (unsigned char) after.back () == 0xff)
4346     after.pop_back ();
4347   if (!after.empty ())
4348     after.back () = (unsigned char) after.back () + 1;
4349   return after;
4350 }
4351
4352 /* See declaration.  */
4353
4354 std::pair<std::vector<name_component>::const_iterator,
4355           std::vector<name_component>::const_iterator>
4356 mapped_index_base::find_name_components_bounds
4357   (const lookup_name_info &lookup_name_without_params) const
4358 {
4359   auto *name_cmp
4360     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4361
4362   const char *cplus
4363     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4364
4365   /* Comparison function object for lower_bound that matches against a
4366      given symbol name.  */
4367   auto lookup_compare_lower = [&] (const name_component &elem,
4368                                    const char *name)
4369     {
4370       const char *elem_qualified = this->symbol_name_at (elem.idx);
4371       const char *elem_name = elem_qualified + elem.name_offset;
4372       return name_cmp (elem_name, name) < 0;
4373     };
4374
4375   /* Comparison function object for upper_bound that matches against a
4376      given symbol name.  */
4377   auto lookup_compare_upper = [&] (const char *name,
4378                                    const name_component &elem)
4379     {
4380       const char *elem_qualified = this->symbol_name_at (elem.idx);
4381       const char *elem_name = elem_qualified + elem.name_offset;
4382       return name_cmp (name, elem_name) < 0;
4383     };
4384
4385   auto begin = this->name_components.begin ();
4386   auto end = this->name_components.end ();
4387
4388   /* Find the lower bound.  */
4389   auto lower = [&] ()
4390     {
4391       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4392         return begin;
4393       else
4394         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4395     } ();
4396
4397   /* Find the upper bound.  */
4398   auto upper = [&] ()
4399     {
4400       if (lookup_name_without_params.completion_mode ())
4401         {
4402           /* In completion mode, we want UPPER to point past all
4403              symbols names that have the same prefix.  I.e., with
4404              these symbols, and completing "func":
4405
4406               function        << lower bound
4407               function1
4408               other_function  << upper bound
4409
4410              We find the upper bound by looking for the insertion
4411              point of "func"-with-last-character-incremented,
4412              i.e. "fund".  */
4413           std::string after = make_sort_after_prefix_name (cplus);
4414           if (after.empty ())
4415             return end;
4416           return std::lower_bound (lower, end, after.c_str (),
4417                                    lookup_compare_lower);
4418         }
4419       else
4420         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4421     } ();
4422
4423   return {lower, upper};
4424 }
4425
4426 /* See declaration.  */
4427
4428 void
4429 mapped_index_base::build_name_components ()
4430 {
4431   if (!this->name_components.empty ())
4432     return;
4433
4434   this->name_components_casing = case_sensitivity;
4435   auto *name_cmp
4436     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4437
4438   /* The code below only knows how to break apart components of C++
4439      symbol names (and other languages that use '::' as
4440      namespace/module separator).  If we add support for wild matching
4441      to some language that uses some other operator (E.g., Ada, Go and
4442      D use '.'), then we'll need to try splitting the symbol name
4443      according to that language too.  Note that Ada does support wild
4444      matching, but doesn't currently support .gdb_index.  */
4445   auto count = this->symbol_name_count ();
4446   for (offset_type idx = 0; idx < count; idx++)
4447     {
4448       if (this->symbol_name_slot_invalid (idx))
4449         continue;
4450
4451       const char *name = this->symbol_name_at (idx);
4452
4453       /* Add each name component to the name component table.  */
4454       unsigned int previous_len = 0;
4455       for (unsigned int current_len = cp_find_first_component (name);
4456            name[current_len] != '\0';
4457            current_len += cp_find_first_component (name + current_len))
4458         {
4459           gdb_assert (name[current_len] == ':');
4460           this->name_components.push_back ({previous_len, idx});
4461           /* Skip the '::'.  */
4462           current_len += 2;
4463           previous_len = current_len;
4464         }
4465       this->name_components.push_back ({previous_len, idx});
4466     }
4467
4468   /* Sort name_components elements by name.  */
4469   auto name_comp_compare = [&] (const name_component &left,
4470                                 const name_component &right)
4471     {
4472       const char *left_qualified = this->symbol_name_at (left.idx);
4473       const char *right_qualified = this->symbol_name_at (right.idx);
4474
4475       const char *left_name = left_qualified + left.name_offset;
4476       const char *right_name = right_qualified + right.name_offset;
4477
4478       return name_cmp (left_name, right_name) < 0;
4479     };
4480
4481   std::sort (this->name_components.begin (),
4482              this->name_components.end (),
4483              name_comp_compare);
4484 }
4485
4486 /* Helper for dw2_expand_symtabs_matching that works with a
4487    mapped_index_base instead of the containing objfile.  This is split
4488    to a separate function in order to be able to unit test the
4489    name_components matching using a mock mapped_index_base.  For each
4490    symbol name that matches, calls MATCH_CALLBACK, passing it the
4491    symbol's index in the mapped_index_base symbol table.  */
4492
4493 static void
4494 dw2_expand_symtabs_matching_symbol
4495   (mapped_index_base &index,
4496    const lookup_name_info &lookup_name_in,
4497    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4498    enum search_domain kind,
4499    gdb::function_view<void (offset_type)> match_callback)
4500 {
4501   lookup_name_info lookup_name_without_params
4502     = lookup_name_in.make_ignore_params ();
4503   gdb_index_symbol_name_matcher lookup_name_matcher
4504     (lookup_name_without_params);
4505
4506   /* Build the symbol name component sorted vector, if we haven't
4507      yet.  */
4508   index.build_name_components ();
4509
4510   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4511
4512   /* Now for each symbol name in range, check to see if we have a name
4513      match, and if so, call the MATCH_CALLBACK callback.  */
4514
4515   /* The same symbol may appear more than once in the range though.
4516      E.g., if we're looking for symbols that complete "w", and we have
4517      a symbol named "w1::w2", we'll find the two name components for
4518      that same symbol in the range.  To be sure we only call the
4519      callback once per symbol, we first collect the symbol name
4520      indexes that matched in a temporary vector and ignore
4521      duplicates.  */
4522   std::vector<offset_type> matches;
4523   matches.reserve (std::distance (bounds.first, bounds.second));
4524
4525   for (; bounds.first != bounds.second; ++bounds.first)
4526     {
4527       const char *qualified = index.symbol_name_at (bounds.first->idx);
4528
4529       if (!lookup_name_matcher.matches (qualified)
4530           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4531         continue;
4532
4533       matches.push_back (bounds.first->idx);
4534     }
4535
4536   std::sort (matches.begin (), matches.end ());
4537
4538   /* Finally call the callback, once per match.  */
4539   ULONGEST prev = -1;
4540   for (offset_type idx : matches)
4541     {
4542       if (prev != idx)
4543         {
4544           match_callback (idx);
4545           prev = idx;
4546         }
4547     }
4548
4549   /* Above we use a type wider than idx's for 'prev', since 0 and
4550      (offset_type)-1 are both possible values.  */
4551   static_assert (sizeof (prev) > sizeof (offset_type), "");
4552 }
4553
4554 #if GDB_SELF_TEST
4555
4556 namespace selftests { namespace dw2_expand_symtabs_matching {
4557
4558 /* A mock .gdb_index/.debug_names-like name index table, enough to
4559    exercise dw2_expand_symtabs_matching_symbol, which works with the
4560    mapped_index_base interface.  Builds an index from the symbol list
4561    passed as parameter to the constructor.  */
4562 class mock_mapped_index : public mapped_index_base
4563 {
4564 public:
4565   mock_mapped_index (gdb::array_view<const char *> symbols)
4566     : m_symbol_table (symbols)
4567   {}
4568
4569   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4570
4571   /* Return the number of names in the symbol table.  */
4572   size_t symbol_name_count () const override
4573   {
4574     return m_symbol_table.size ();
4575   }
4576
4577   /* Get the name of the symbol at IDX in the symbol table.  */
4578   const char *symbol_name_at (offset_type idx) const override
4579   {
4580     return m_symbol_table[idx];
4581   }
4582
4583 private:
4584   gdb::array_view<const char *> m_symbol_table;
4585 };
4586
4587 /* Convenience function that converts a NULL pointer to a "<null>"
4588    string, to pass to print routines.  */
4589
4590 static const char *
4591 string_or_null (const char *str)
4592 {
4593   return str != NULL ? str : "<null>";
4594 }
4595
4596 /* Check if a lookup_name_info built from
4597    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4598    index.  EXPECTED_LIST is the list of expected matches, in expected
4599    matching order.  If no match expected, then an empty list is
4600    specified.  Returns true on success.  On failure prints a warning
4601    indicating the file:line that failed, and returns false.  */
4602
4603 static bool
4604 check_match (const char *file, int line,
4605              mock_mapped_index &mock_index,
4606              const char *name, symbol_name_match_type match_type,
4607              bool completion_mode,
4608              std::initializer_list<const char *> expected_list)
4609 {
4610   lookup_name_info lookup_name (name, match_type, completion_mode);
4611
4612   bool matched = true;
4613
4614   auto mismatch = [&] (const char *expected_str,
4615                        const char *got)
4616   {
4617     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4618                "expected=\"%s\", got=\"%s\"\n"),
4619              file, line,
4620              (match_type == symbol_name_match_type::FULL
4621               ? "FULL" : "WILD"),
4622              name, string_or_null (expected_str), string_or_null (got));
4623     matched = false;
4624   };
4625
4626   auto expected_it = expected_list.begin ();
4627   auto expected_end = expected_list.end ();
4628
4629   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4630                                       NULL, ALL_DOMAIN,
4631                                       [&] (offset_type idx)
4632   {
4633     const char *matched_name = mock_index.symbol_name_at (idx);
4634     const char *expected_str
4635       = expected_it == expected_end ? NULL : *expected_it++;
4636
4637     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4638       mismatch (expected_str, matched_name);
4639   });
4640
4641   const char *expected_str
4642   = expected_it == expected_end ? NULL : *expected_it++;
4643   if (expected_str != NULL)
4644     mismatch (expected_str, NULL);
4645
4646   return matched;
4647 }
4648
4649 /* The symbols added to the mock mapped_index for testing (in
4650    canonical form).  */
4651 static const char *test_symbols[] = {
4652   "function",
4653   "std::bar",
4654   "std::zfunction",
4655   "std::zfunction2",
4656   "w1::w2",
4657   "ns::foo<char*>",
4658   "ns::foo<int>",
4659   "ns::foo<long>",
4660   "ns2::tmpl<int>::foo2",
4661   "(anonymous namespace)::A::B::C",
4662
4663   /* These are used to check that the increment-last-char in the
4664      matching algorithm for completion doesn't match "t1_fund" when
4665      completing "t1_func".  */
4666   "t1_func",
4667   "t1_func1",
4668   "t1_fund",
4669   "t1_fund1",
4670
4671   /* A UTF-8 name with multi-byte sequences to make sure that
4672      cp-name-parser understands this as a single identifier ("função"
4673      is "function" in PT).  */
4674   u8"u8função",
4675
4676   /* \377 (0xff) is Latin1 'ÿ'.  */
4677   "yfunc\377",
4678
4679   /* \377 (0xff) is Latin1 'ÿ'.  */
4680   "\377",
4681   "\377\377123",
4682
4683   /* A name with all sorts of complications.  Starts with "z" to make
4684      it easier for the completion tests below.  */
4685 #define Z_SYM_NAME \
4686   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4687     "::tuple<(anonymous namespace)::ui*, " \
4688     "std::default_delete<(anonymous namespace)::ui>, void>"
4689
4690   Z_SYM_NAME
4691 };
4692
4693 /* Returns true if the mapped_index_base::find_name_component_bounds
4694    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4695    in completion mode.  */
4696
4697 static bool
4698 check_find_bounds_finds (mapped_index_base &index,
4699                          const char *search_name,
4700                          gdb::array_view<const char *> expected_syms)
4701 {
4702   lookup_name_info lookup_name (search_name,
4703                                 symbol_name_match_type::FULL, true);
4704
4705   auto bounds = index.find_name_components_bounds (lookup_name);
4706
4707   size_t distance = std::distance (bounds.first, bounds.second);
4708   if (distance != expected_syms.size ())
4709     return false;
4710
4711   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4712     {
4713       auto nc_elem = bounds.first + exp_elem;
4714       const char *qualified = index.symbol_name_at (nc_elem->idx);
4715       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4716         return false;
4717     }
4718
4719   return true;
4720 }
4721
4722 /* Test the lower-level mapped_index::find_name_component_bounds
4723    method.  */
4724
4725 static void
4726 test_mapped_index_find_name_component_bounds ()
4727 {
4728   mock_mapped_index mock_index (test_symbols);
4729
4730   mock_index.build_name_components ();
4731
4732   /* Test the lower-level mapped_index::find_name_component_bounds
4733      method in completion mode.  */
4734   {
4735     static const char *expected_syms[] = {
4736       "t1_func",
4737       "t1_func1",
4738     };
4739
4740     SELF_CHECK (check_find_bounds_finds (mock_index,
4741                                          "t1_func", expected_syms));
4742   }
4743
4744   /* Check that the increment-last-char in the name matching algorithm
4745      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4746   {
4747     static const char *expected_syms1[] = {
4748       "\377",
4749       "\377\377123",
4750     };
4751     SELF_CHECK (check_find_bounds_finds (mock_index,
4752                                          "\377", expected_syms1));
4753
4754     static const char *expected_syms2[] = {
4755       "\377\377123",
4756     };
4757     SELF_CHECK (check_find_bounds_finds (mock_index,
4758                                          "\377\377", expected_syms2));
4759   }
4760 }
4761
4762 /* Test dw2_expand_symtabs_matching_symbol.  */
4763
4764 static void
4765 test_dw2_expand_symtabs_matching_symbol ()
4766 {
4767   mock_mapped_index mock_index (test_symbols);
4768
4769   /* We let all tests run until the end even if some fails, for debug
4770      convenience.  */
4771   bool any_mismatch = false;
4772
4773   /* Create the expected symbols list (an initializer_list).  Needed
4774      because lists have commas, and we need to pass them to CHECK,
4775      which is a macro.  */
4776 #define EXPECT(...) { __VA_ARGS__ }
4777
4778   /* Wrapper for check_match that passes down the current
4779      __FILE__/__LINE__.  */
4780 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4781   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4782                                 mock_index,                             \
4783                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4784                                 EXPECTED_LIST)
4785
4786   /* Identity checks.  */
4787   for (const char *sym : test_symbols)
4788     {
4789       /* Should be able to match all existing symbols.  */
4790       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4791                    EXPECT (sym));
4792
4793       /* Should be able to match all existing symbols with
4794          parameters.  */
4795       std::string with_params = std::string (sym) + "(int)";
4796       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4797                    EXPECT (sym));
4798
4799       /* Should be able to match all existing symbols with
4800          parameters and qualifiers.  */
4801       with_params = std::string (sym) + " ( int ) const";
4802       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4803                    EXPECT (sym));
4804
4805       /* This should really find sym, but cp-name-parser.y doesn't
4806          know about lvalue/rvalue qualifiers yet.  */
4807       with_params = std::string (sym) + " ( int ) &&";
4808       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4809                    {});
4810     }
4811
4812   /* Check that the name matching algorithm for completion doesn't get
4813      confused with Latin1 'ÿ' / 0xff.  */
4814   {
4815     static const char str[] = "\377";
4816     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4817                  EXPECT ("\377", "\377\377123"));
4818   }
4819
4820   /* Check that the increment-last-char in the matching algorithm for
4821      completion doesn't match "t1_fund" when completing "t1_func".  */
4822   {
4823     static const char str[] = "t1_func";
4824     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4825                  EXPECT ("t1_func", "t1_func1"));
4826   }
4827
4828   /* Check that completion mode works at each prefix of the expected
4829      symbol name.  */
4830   {
4831     static const char str[] = "function(int)";
4832     size_t len = strlen (str);
4833     std::string lookup;
4834
4835     for (size_t i = 1; i < len; i++)
4836       {
4837         lookup.assign (str, i);
4838         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4839                      EXPECT ("function"));
4840       }
4841   }
4842
4843   /* While "w" is a prefix of both components, the match function
4844      should still only be called once.  */
4845   {
4846     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4847                  EXPECT ("w1::w2"));
4848     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4849                  EXPECT ("w1::w2"));
4850   }
4851
4852   /* Same, with a "complicated" symbol.  */
4853   {
4854     static const char str[] = Z_SYM_NAME;
4855     size_t len = strlen (str);
4856     std::string lookup;
4857
4858     for (size_t i = 1; i < len; i++)
4859       {
4860         lookup.assign (str, i);
4861         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4862                      EXPECT (Z_SYM_NAME));
4863       }
4864   }
4865
4866   /* In FULL mode, an incomplete symbol doesn't match.  */
4867   {
4868     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4869                  {});
4870   }
4871
4872   /* A complete symbol with parameters matches any overload, since the
4873      index has no overload info.  */
4874   {
4875     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4876                  EXPECT ("std::zfunction", "std::zfunction2"));
4877     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4878                  EXPECT ("std::zfunction", "std::zfunction2"));
4879     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4880                  EXPECT ("std::zfunction", "std::zfunction2"));
4881   }
4882
4883   /* Check that whitespace is ignored appropriately.  A symbol with a
4884      template argument list. */
4885   {
4886     static const char expected[] = "ns::foo<int>";
4887     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4888                  EXPECT (expected));
4889     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4890                  EXPECT (expected));
4891   }
4892
4893   /* Check that whitespace is ignored appropriately.  A symbol with a
4894      template argument list that includes a pointer.  */
4895   {
4896     static const char expected[] = "ns::foo<char*>";
4897     /* Try both completion and non-completion modes.  */
4898     static const bool completion_mode[2] = {false, true};
4899     for (size_t i = 0; i < 2; i++)
4900       {
4901         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4902                      completion_mode[i], EXPECT (expected));
4903         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4904                      completion_mode[i], EXPECT (expected));
4905
4906         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4907                      completion_mode[i], EXPECT (expected));
4908         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4909                      completion_mode[i], EXPECT (expected));
4910       }
4911   }
4912
4913   {
4914     /* Check method qualifiers are ignored.  */
4915     static const char expected[] = "ns::foo<char*>";
4916     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4917                  symbol_name_match_type::FULL, true, EXPECT (expected));
4918     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4919                  symbol_name_match_type::FULL, true, EXPECT (expected));
4920     CHECK_MATCH ("foo < char * >  ( int ) const",
4921                  symbol_name_match_type::WILD, true, EXPECT (expected));
4922     CHECK_MATCH ("foo < char * >  ( int ) &&",
4923                  symbol_name_match_type::WILD, true, EXPECT (expected));
4924   }
4925
4926   /* Test lookup names that don't match anything.  */
4927   {
4928     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4929                  {});
4930
4931     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4932                  {});
4933   }
4934
4935   /* Some wild matching tests, exercising "(anonymous namespace)",
4936      which should not be confused with a parameter list.  */
4937   {
4938     static const char *syms[] = {
4939       "A::B::C",
4940       "B::C",
4941       "C",
4942       "A :: B :: C ( int )",
4943       "B :: C ( int )",
4944       "C ( int )",
4945     };
4946
4947     for (const char *s : syms)
4948       {
4949         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4950                      EXPECT ("(anonymous namespace)::A::B::C"));
4951       }
4952   }
4953
4954   {
4955     static const char expected[] = "ns2::tmpl<int>::foo2";
4956     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4957                  EXPECT (expected));
4958     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4959                  EXPECT (expected));
4960   }
4961
4962   SELF_CHECK (!any_mismatch);
4963
4964 #undef EXPECT
4965 #undef CHECK_MATCH
4966 }
4967
4968 static void
4969 run_test ()
4970 {
4971   test_mapped_index_find_name_component_bounds ();
4972   test_dw2_expand_symtabs_matching_symbol ();
4973 }
4974
4975 }} // namespace selftests::dw2_expand_symtabs_matching
4976
4977 #endif /* GDB_SELF_TEST */
4978
4979 /* If FILE_MATCHER is NULL or if PER_CU has
4980    dwarf2_per_cu_quick_data::MARK set (see
4981    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4982    EXPANSION_NOTIFY on it.  */
4983
4984 static void
4985 dw2_expand_symtabs_matching_one
4986   (struct dwarf2_per_cu_data *per_cu,
4987    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4988    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4989 {
4990   if (file_matcher == NULL || per_cu->v.quick->mark)
4991     {
4992       bool symtab_was_null
4993         = (per_cu->v.quick->compunit_symtab == NULL);
4994
4995       dw2_instantiate_symtab (per_cu, false);
4996
4997       if (expansion_notify != NULL
4998           && symtab_was_null
4999           && per_cu->v.quick->compunit_symtab != NULL)
5000         expansion_notify (per_cu->v.quick->compunit_symtab);
5001     }
5002 }
5003
5004 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5005    matched, to expand corresponding CUs that were marked.  IDX is the
5006    index of the symbol name that matched.  */
5007
5008 static void
5009 dw2_expand_marked_cus
5010   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5011    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5012    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5013    search_domain kind)
5014 {
5015   offset_type *vec, vec_len, vec_idx;
5016   bool global_seen = false;
5017   mapped_index &index = *dwarf2_per_objfile->index_table;
5018
5019   vec = (offset_type *) (index.constant_pool
5020                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5021   vec_len = MAYBE_SWAP (vec[0]);
5022   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5023     {
5024       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5025       /* This value is only valid for index versions >= 7.  */
5026       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5027       gdb_index_symbol_kind symbol_kind =
5028         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5029       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5030       /* Only check the symbol attributes if they're present.
5031          Indices prior to version 7 don't record them,
5032          and indices >= 7 may elide them for certain symbols
5033          (gold does this).  */
5034       int attrs_valid =
5035         (index.version >= 7
5036          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5037
5038       /* Work around gold/15646.  */
5039       if (attrs_valid)
5040         {
5041           if (!is_static && global_seen)
5042             continue;
5043           if (!is_static)
5044             global_seen = true;
5045         }
5046
5047       /* Only check the symbol's kind if it has one.  */
5048       if (attrs_valid)
5049         {
5050           switch (kind)
5051             {
5052             case VARIABLES_DOMAIN:
5053               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5054                 continue;
5055               break;
5056             case FUNCTIONS_DOMAIN:
5057               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5058                 continue;
5059               break;
5060             case TYPES_DOMAIN:
5061               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5062                 continue;
5063               break;
5064             default:
5065               break;
5066             }
5067         }
5068
5069       /* Don't crash on bad data.  */
5070       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5071                        + dwarf2_per_objfile->all_type_units.size ()))
5072         {
5073           complaint (_(".gdb_index entry has bad CU index"
5074                        " [in module %s]"),
5075                        objfile_name (dwarf2_per_objfile->objfile));
5076           continue;
5077         }
5078
5079       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5080       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5081                                        expansion_notify);
5082     }
5083 }
5084
5085 /* If FILE_MATCHER is non-NULL, set all the
5086    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5087    that match FILE_MATCHER.  */
5088
5089 static void
5090 dw_expand_symtabs_matching_file_matcher
5091   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5092    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5093 {
5094   if (file_matcher == NULL)
5095     return;
5096
5097   objfile *const objfile = dwarf2_per_objfile->objfile;
5098
5099   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5100                                             htab_eq_pointer,
5101                                             NULL, xcalloc, xfree));
5102   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5103                                                 htab_eq_pointer,
5104                                                 NULL, xcalloc, xfree));
5105
5106   /* The rule is CUs specify all the files, including those used by
5107      any TU, so there's no need to scan TUs here.  */
5108
5109   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5110     {
5111       QUIT;
5112
5113       per_cu->v.quick->mark = 0;
5114
5115       /* We only need to look at symtabs not already expanded.  */
5116       if (per_cu->v.quick->compunit_symtab)
5117         continue;
5118
5119       quick_file_names *file_data = dw2_get_file_names (per_cu);
5120       if (file_data == NULL)
5121         continue;
5122
5123       if (htab_find (visited_not_found.get (), file_data) != NULL)
5124         continue;
5125       else if (htab_find (visited_found.get (), file_data) != NULL)
5126         {
5127           per_cu->v.quick->mark = 1;
5128           continue;
5129         }
5130
5131       for (int j = 0; j < file_data->num_file_names; ++j)
5132         {
5133           const char *this_real_name;
5134
5135           if (file_matcher (file_data->file_names[j], false))
5136             {
5137               per_cu->v.quick->mark = 1;
5138               break;
5139             }
5140
5141           /* Before we invoke realpath, which can get expensive when many
5142              files are involved, do a quick comparison of the basenames.  */
5143           if (!basenames_may_differ
5144               && !file_matcher (lbasename (file_data->file_names[j]),
5145                                 true))
5146             continue;
5147
5148           this_real_name = dw2_get_real_path (objfile, file_data, j);
5149           if (file_matcher (this_real_name, false))
5150             {
5151               per_cu->v.quick->mark = 1;
5152               break;
5153             }
5154         }
5155
5156       void **slot = htab_find_slot (per_cu->v.quick->mark
5157                                     ? visited_found.get ()
5158                                     : visited_not_found.get (),
5159                                     file_data, INSERT);
5160       *slot = file_data;
5161     }
5162 }
5163
5164 static void
5165 dw2_expand_symtabs_matching
5166   (struct objfile *objfile,
5167    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5168    const lookup_name_info &lookup_name,
5169    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5170    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5171    enum search_domain kind)
5172 {
5173   struct dwarf2_per_objfile *dwarf2_per_objfile
5174     = get_dwarf2_per_objfile (objfile);
5175
5176   /* index_table is NULL if OBJF_READNOW.  */
5177   if (!dwarf2_per_objfile->index_table)
5178     return;
5179
5180   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5181
5182   mapped_index &index = *dwarf2_per_objfile->index_table;
5183
5184   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5185                                       symbol_matcher,
5186                                       kind, [&] (offset_type idx)
5187     {
5188       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5189                              expansion_notify, kind);
5190     });
5191 }
5192
5193 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5194    symtab.  */
5195
5196 static struct compunit_symtab *
5197 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5198                                           CORE_ADDR pc)
5199 {
5200   int i;
5201
5202   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5203       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5204     return cust;
5205
5206   if (cust->includes == NULL)
5207     return NULL;
5208
5209   for (i = 0; cust->includes[i]; ++i)
5210     {
5211       struct compunit_symtab *s = cust->includes[i];
5212
5213       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5214       if (s != NULL)
5215         return s;
5216     }
5217
5218   return NULL;
5219 }
5220
5221 static struct compunit_symtab *
5222 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5223                                   struct bound_minimal_symbol msymbol,
5224                                   CORE_ADDR pc,
5225                                   struct obj_section *section,
5226                                   int warn_if_readin)
5227 {
5228   struct dwarf2_per_cu_data *data;
5229   struct compunit_symtab *result;
5230
5231   if (!objfile->psymtabs_addrmap)
5232     return NULL;
5233
5234   CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
5235                                  SECT_OFF_TEXT (objfile));
5236   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5237                                                      pc - baseaddr);
5238   if (!data)
5239     return NULL;
5240
5241   if (warn_if_readin && data->v.quick->compunit_symtab)
5242     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5243              paddress (get_objfile_arch (objfile), pc));
5244
5245   result
5246     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
5247                                                                         false),
5248                                                 pc);
5249   gdb_assert (result != NULL);
5250   return result;
5251 }
5252
5253 static void
5254 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5255                           void *data, int need_fullname)
5256 {
5257   struct dwarf2_per_objfile *dwarf2_per_objfile
5258     = get_dwarf2_per_objfile (objfile);
5259
5260   if (!dwarf2_per_objfile->filenames_cache)
5261     {
5262       dwarf2_per_objfile->filenames_cache.emplace ();
5263
5264       htab_up visited (htab_create_alloc (10,
5265                                           htab_hash_pointer, htab_eq_pointer,
5266                                           NULL, xcalloc, xfree));
5267
5268       /* The rule is CUs specify all the files, including those used
5269          by any TU, so there's no need to scan TUs here.  We can
5270          ignore file names coming from already-expanded CUs.  */
5271
5272       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5273         {
5274           if (per_cu->v.quick->compunit_symtab)
5275             {
5276               void **slot = htab_find_slot (visited.get (),
5277                                             per_cu->v.quick->file_names,
5278                                             INSERT);
5279
5280               *slot = per_cu->v.quick->file_names;
5281             }
5282         }
5283
5284       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5285         {
5286           /* We only need to look at symtabs not already expanded.  */
5287           if (per_cu->v.quick->compunit_symtab)
5288             continue;
5289
5290           quick_file_names *file_data = dw2_get_file_names (per_cu);
5291           if (file_data == NULL)
5292             continue;
5293
5294           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5295           if (*slot)
5296             {
5297               /* Already visited.  */
5298               continue;
5299             }
5300           *slot = file_data;
5301
5302           for (int j = 0; j < file_data->num_file_names; ++j)
5303             {
5304               const char *filename = file_data->file_names[j];
5305               dwarf2_per_objfile->filenames_cache->seen (filename);
5306             }
5307         }
5308     }
5309
5310   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5311     {
5312       gdb::unique_xmalloc_ptr<char> this_real_name;
5313
5314       if (need_fullname)
5315         this_real_name = gdb_realpath (filename);
5316       (*fun) (filename, this_real_name.get (), data);
5317     });
5318 }
5319
5320 static int
5321 dw2_has_symbols (struct objfile *objfile)
5322 {
5323   return 1;
5324 }
5325
5326 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5327 {
5328   dw2_has_symbols,
5329   dw2_find_last_source_symtab,
5330   dw2_forget_cached_source_info,
5331   dw2_map_symtabs_matching_filename,
5332   dw2_lookup_symbol,
5333   dw2_print_stats,
5334   dw2_dump,
5335   dw2_expand_symtabs_for_function,
5336   dw2_expand_all_symtabs,
5337   dw2_expand_symtabs_with_fullname,
5338   dw2_map_matching_symbols,
5339   dw2_expand_symtabs_matching,
5340   dw2_find_pc_sect_compunit_symtab,
5341   NULL,
5342   dw2_map_symbol_filenames
5343 };
5344
5345 /* DWARF-5 debug_names reader.  */
5346
5347 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5348 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5349
5350 /* A helper function that reads the .debug_names section in SECTION
5351    and fills in MAP.  FILENAME is the name of the file containing the
5352    section; it is used for error reporting.
5353
5354    Returns true if all went well, false otherwise.  */
5355
5356 static bool
5357 read_debug_names_from_section (struct objfile *objfile,
5358                                const char *filename,
5359                                struct dwarf2_section_info *section,
5360                                mapped_debug_names &map)
5361 {
5362   if (dwarf2_section_empty_p (section))
5363     return false;
5364
5365   /* Older elfutils strip versions could keep the section in the main
5366      executable while splitting it for the separate debug info file.  */
5367   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5368     return false;
5369
5370   dwarf2_read_section (objfile, section);
5371
5372   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5373
5374   const gdb_byte *addr = section->buffer;
5375
5376   bfd *const abfd = get_section_bfd_owner (section);
5377
5378   unsigned int bytes_read;
5379   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5380   addr += bytes_read;
5381
5382   map.dwarf5_is_dwarf64 = bytes_read != 4;
5383   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5384   if (bytes_read + length != section->size)
5385     {
5386       /* There may be multiple per-CU indices.  */
5387       warning (_("Section .debug_names in %s length %s does not match "
5388                  "section length %s, ignoring .debug_names."),
5389                filename, plongest (bytes_read + length),
5390                pulongest (section->size));
5391       return false;
5392     }
5393
5394   /* The version number.  */
5395   uint16_t version = read_2_bytes (abfd, addr);
5396   addr += 2;
5397   if (version != 5)
5398     {
5399       warning (_("Section .debug_names in %s has unsupported version %d, "
5400                  "ignoring .debug_names."),
5401                filename, version);
5402       return false;
5403     }
5404
5405   /* Padding.  */
5406   uint16_t padding = read_2_bytes (abfd, addr);
5407   addr += 2;
5408   if (padding != 0)
5409     {
5410       warning (_("Section .debug_names in %s has unsupported padding %d, "
5411                  "ignoring .debug_names."),
5412                filename, padding);
5413       return false;
5414     }
5415
5416   /* comp_unit_count - The number of CUs in the CU list.  */
5417   map.cu_count = read_4_bytes (abfd, addr);
5418   addr += 4;
5419
5420   /* local_type_unit_count - The number of TUs in the local TU
5421      list.  */
5422   map.tu_count = read_4_bytes (abfd, addr);
5423   addr += 4;
5424
5425   /* foreign_type_unit_count - The number of TUs in the foreign TU
5426      list.  */
5427   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5428   addr += 4;
5429   if (foreign_tu_count != 0)
5430     {
5431       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5432                  "ignoring .debug_names."),
5433                filename, static_cast<unsigned long> (foreign_tu_count));
5434       return false;
5435     }
5436
5437   /* bucket_count - The number of hash buckets in the hash lookup
5438      table.  */
5439   map.bucket_count = read_4_bytes (abfd, addr);
5440   addr += 4;
5441
5442   /* name_count - The number of unique names in the index.  */
5443   map.name_count = read_4_bytes (abfd, addr);
5444   addr += 4;
5445
5446   /* abbrev_table_size - The size in bytes of the abbreviations
5447      table.  */
5448   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5449   addr += 4;
5450
5451   /* augmentation_string_size - The size in bytes of the augmentation
5452      string.  This value is rounded up to a multiple of 4.  */
5453   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5454   addr += 4;
5455   map.augmentation_is_gdb = ((augmentation_string_size
5456                               == sizeof (dwarf5_augmentation))
5457                              && memcmp (addr, dwarf5_augmentation,
5458                                         sizeof (dwarf5_augmentation)) == 0);
5459   augmentation_string_size += (-augmentation_string_size) & 3;
5460   addr += augmentation_string_size;
5461
5462   /* List of CUs */
5463   map.cu_table_reordered = addr;
5464   addr += map.cu_count * map.offset_size;
5465
5466   /* List of Local TUs */
5467   map.tu_table_reordered = addr;
5468   addr += map.tu_count * map.offset_size;
5469
5470   /* Hash Lookup Table */
5471   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5472   addr += map.bucket_count * 4;
5473   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5474   addr += map.name_count * 4;
5475
5476   /* Name Table */
5477   map.name_table_string_offs_reordered = addr;
5478   addr += map.name_count * map.offset_size;
5479   map.name_table_entry_offs_reordered = addr;
5480   addr += map.name_count * map.offset_size;
5481
5482   const gdb_byte *abbrev_table_start = addr;
5483   for (;;)
5484     {
5485       unsigned int bytes_read;
5486       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5487       addr += bytes_read;
5488       if (index_num == 0)
5489         break;
5490
5491       const auto insertpair
5492         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5493       if (!insertpair.second)
5494         {
5495           warning (_("Section .debug_names in %s has duplicate index %s, "
5496                      "ignoring .debug_names."),
5497                    filename, pulongest (index_num));
5498           return false;
5499         }
5500       mapped_debug_names::index_val &indexval = insertpair.first->second;
5501       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5502       addr += bytes_read;
5503
5504       for (;;)
5505         {
5506           mapped_debug_names::index_val::attr attr;
5507           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5508           addr += bytes_read;
5509           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5510           addr += bytes_read;
5511           if (attr.form == DW_FORM_implicit_const)
5512             {
5513               attr.implicit_const = read_signed_leb128 (abfd, addr,
5514                                                         &bytes_read);
5515               addr += bytes_read;
5516             }
5517           if (attr.dw_idx == 0 && attr.form == 0)
5518             break;
5519           indexval.attr_vec.push_back (std::move (attr));
5520         }
5521     }
5522   if (addr != abbrev_table_start + abbrev_table_size)
5523     {
5524       warning (_("Section .debug_names in %s has abbreviation_table "
5525                  "of size %zu vs. written as %u, ignoring .debug_names."),
5526                filename, addr - abbrev_table_start, abbrev_table_size);
5527       return false;
5528     }
5529   map.entry_pool = addr;
5530
5531   return true;
5532 }
5533
5534 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5535    list.  */
5536
5537 static void
5538 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5539                                   const mapped_debug_names &map,
5540                                   dwarf2_section_info &section,
5541                                   bool is_dwz)
5542 {
5543   sect_offset sect_off_prev;
5544   for (uint32_t i = 0; i <= map.cu_count; ++i)
5545     {
5546       sect_offset sect_off_next;
5547       if (i < map.cu_count)
5548         {
5549           sect_off_next
5550             = (sect_offset) (extract_unsigned_integer
5551                              (map.cu_table_reordered + i * map.offset_size,
5552                               map.offset_size,
5553                               map.dwarf5_byte_order));
5554         }
5555       else
5556         sect_off_next = (sect_offset) section.size;
5557       if (i >= 1)
5558         {
5559           const ULONGEST length = sect_off_next - sect_off_prev;
5560           dwarf2_per_cu_data *per_cu
5561             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5562                                          sect_off_prev, length);
5563           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5564         }
5565       sect_off_prev = sect_off_next;
5566     }
5567 }
5568
5569 /* Read the CU list from the mapped index, and use it to create all
5570    the CU objects for this dwarf2_per_objfile.  */
5571
5572 static void
5573 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5574                              const mapped_debug_names &map,
5575                              const mapped_debug_names &dwz_map)
5576 {
5577   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5578   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5579
5580   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5581                                     dwarf2_per_objfile->info,
5582                                     false /* is_dwz */);
5583
5584   if (dwz_map.cu_count == 0)
5585     return;
5586
5587   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5588   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5589                                     true /* is_dwz */);
5590 }
5591
5592 /* Read .debug_names.  If everything went ok, initialize the "quick"
5593    elements of all the CUs and return true.  Otherwise, return false.  */
5594
5595 static bool
5596 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5597 {
5598   std::unique_ptr<mapped_debug_names> map
5599     (new mapped_debug_names (dwarf2_per_objfile));
5600   mapped_debug_names dwz_map (dwarf2_per_objfile);
5601   struct objfile *objfile = dwarf2_per_objfile->objfile;
5602
5603   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5604                                       &dwarf2_per_objfile->debug_names,
5605                                       *map))
5606     return false;
5607
5608   /* Don't use the index if it's empty.  */
5609   if (map->name_count == 0)
5610     return false;
5611
5612   /* If there is a .dwz file, read it so we can get its CU list as
5613      well.  */
5614   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5615   if (dwz != NULL)
5616     {
5617       if (!read_debug_names_from_section (objfile,
5618                                           bfd_get_filename (dwz->dwz_bfd),
5619                                           &dwz->debug_names, dwz_map))
5620         {
5621           warning (_("could not read '.debug_names' section from %s; skipping"),
5622                    bfd_get_filename (dwz->dwz_bfd));
5623           return false;
5624         }
5625     }
5626
5627   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5628
5629   if (map->tu_count != 0)
5630     {
5631       /* We can only handle a single .debug_types when we have an
5632          index.  */
5633       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5634         return false;
5635
5636       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5637                                                 dwarf2_per_objfile->types, 0);
5638
5639       create_signatured_type_table_from_debug_names
5640         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5641     }
5642
5643   create_addrmap_from_aranges (dwarf2_per_objfile,
5644                                &dwarf2_per_objfile->debug_aranges);
5645
5646   dwarf2_per_objfile->debug_names_table = std::move (map);
5647   dwarf2_per_objfile->using_index = 1;
5648   dwarf2_per_objfile->quick_file_names_table =
5649     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5650
5651   return true;
5652 }
5653
5654 /* Type used to manage iterating over all CUs looking for a symbol for
5655    .debug_names.  */
5656
5657 class dw2_debug_names_iterator
5658 {
5659 public:
5660   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5661      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5662   dw2_debug_names_iterator (const mapped_debug_names &map,
5663                             bool want_specific_block,
5664                             block_enum block_index, domain_enum domain,
5665                             const char *name)
5666     : m_map (map), m_want_specific_block (want_specific_block),
5667       m_block_index (block_index), m_domain (domain),
5668       m_addr (find_vec_in_debug_names (map, name))
5669   {}
5670
5671   dw2_debug_names_iterator (const mapped_debug_names &map,
5672                             search_domain search, uint32_t namei)
5673     : m_map (map),
5674       m_search (search),
5675       m_addr (find_vec_in_debug_names (map, namei))
5676   {}
5677
5678   /* Return the next matching CU or NULL if there are no more.  */
5679   dwarf2_per_cu_data *next ();
5680
5681 private:
5682   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5683                                                   const char *name);
5684   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5685                                                   uint32_t namei);
5686
5687   /* The internalized form of .debug_names.  */
5688   const mapped_debug_names &m_map;
5689
5690   /* If true, only look for symbols that match BLOCK_INDEX.  */
5691   const bool m_want_specific_block = false;
5692
5693   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5694      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5695      value.  */
5696   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5697
5698   /* The kind of symbol we're looking for.  */
5699   const domain_enum m_domain = UNDEF_DOMAIN;
5700   const search_domain m_search = ALL_DOMAIN;
5701
5702   /* The list of CUs from the index entry of the symbol, or NULL if
5703      not found.  */
5704   const gdb_byte *m_addr;
5705 };
5706
5707 const char *
5708 mapped_debug_names::namei_to_name (uint32_t namei) const
5709 {
5710   const ULONGEST namei_string_offs
5711     = extract_unsigned_integer ((name_table_string_offs_reordered
5712                                  + namei * offset_size),
5713                                 offset_size,
5714                                 dwarf5_byte_order);
5715   return read_indirect_string_at_offset
5716     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5717 }
5718
5719 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5720    found, return pointer to its pool data.  If NAME cannot be found,
5721    return NULL.  */
5722
5723 const gdb_byte *
5724 dw2_debug_names_iterator::find_vec_in_debug_names
5725   (const mapped_debug_names &map, const char *name)
5726 {
5727   int (*cmp) (const char *, const char *);
5728
5729   if (current_language->la_language == language_cplus
5730       || current_language->la_language == language_fortran
5731       || current_language->la_language == language_d)
5732     {
5733       /* NAME is already canonical.  Drop any qualifiers as
5734          .debug_names does not contain any.  */
5735
5736       if (strchr (name, '(') != NULL)
5737         {
5738           gdb::unique_xmalloc_ptr<char> without_params
5739             = cp_remove_params (name);
5740
5741           if (without_params != NULL)
5742             {
5743               name = without_params.get();
5744             }
5745         }
5746     }
5747
5748   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5749
5750   const uint32_t full_hash = dwarf5_djb_hash (name);
5751   uint32_t namei
5752     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5753                                 (map.bucket_table_reordered
5754                                  + (full_hash % map.bucket_count)), 4,
5755                                 map.dwarf5_byte_order);
5756   if (namei == 0)
5757     return NULL;
5758   --namei;
5759   if (namei >= map.name_count)
5760     {
5761       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5762                    "[in module %s]"),
5763                  namei, map.name_count,
5764                  objfile_name (map.dwarf2_per_objfile->objfile));
5765       return NULL;
5766     }
5767
5768   for (;;)
5769     {
5770       const uint32_t namei_full_hash
5771         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5772                                     (map.hash_table_reordered + namei), 4,
5773                                     map.dwarf5_byte_order);
5774       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5775         return NULL;
5776
5777       if (full_hash == namei_full_hash)
5778         {
5779           const char *const namei_string = map.namei_to_name (namei);
5780
5781 #if 0 /* An expensive sanity check.  */
5782           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5783             {
5784               complaint (_("Wrong .debug_names hash for string at index %u "
5785                            "[in module %s]"),
5786                          namei, objfile_name (dwarf2_per_objfile->objfile));
5787               return NULL;
5788             }
5789 #endif
5790
5791           if (cmp (namei_string, name) == 0)
5792             {
5793               const ULONGEST namei_entry_offs
5794                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5795                                              + namei * map.offset_size),
5796                                             map.offset_size, map.dwarf5_byte_order);
5797               return map.entry_pool + namei_entry_offs;
5798             }
5799         }
5800
5801       ++namei;
5802       if (namei >= map.name_count)
5803         return NULL;
5804     }
5805 }
5806
5807 const gdb_byte *
5808 dw2_debug_names_iterator::find_vec_in_debug_names
5809   (const mapped_debug_names &map, uint32_t namei)
5810 {
5811   if (namei >= map.name_count)
5812     {
5813       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5814                    "[in module %s]"),
5815                  namei, map.name_count,
5816                  objfile_name (map.dwarf2_per_objfile->objfile));
5817       return NULL;
5818     }
5819
5820   const ULONGEST namei_entry_offs
5821     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5822                                  + namei * map.offset_size),
5823                                 map.offset_size, map.dwarf5_byte_order);
5824   return map.entry_pool + namei_entry_offs;
5825 }
5826
5827 /* See dw2_debug_names_iterator.  */
5828
5829 dwarf2_per_cu_data *
5830 dw2_debug_names_iterator::next ()
5831 {
5832   if (m_addr == NULL)
5833     return NULL;
5834
5835   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5836   struct objfile *objfile = dwarf2_per_objfile->objfile;
5837   bfd *const abfd = objfile->obfd;
5838
5839  again:
5840
5841   unsigned int bytes_read;
5842   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5843   m_addr += bytes_read;
5844   if (abbrev == 0)
5845     return NULL;
5846
5847   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5848   if (indexval_it == m_map.abbrev_map.cend ())
5849     {
5850       complaint (_("Wrong .debug_names undefined abbrev code %s "
5851                    "[in module %s]"),
5852                  pulongest (abbrev), objfile_name (objfile));
5853       return NULL;
5854     }
5855   const mapped_debug_names::index_val &indexval = indexval_it->second;
5856   bool have_is_static = false;
5857   bool is_static;
5858   dwarf2_per_cu_data *per_cu = NULL;
5859   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5860     {
5861       ULONGEST ull;
5862       switch (attr.form)
5863         {
5864         case DW_FORM_implicit_const:
5865           ull = attr.implicit_const;
5866           break;
5867         case DW_FORM_flag_present:
5868           ull = 1;
5869           break;
5870         case DW_FORM_udata:
5871           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5872           m_addr += bytes_read;
5873           break;
5874         default:
5875           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5876                      dwarf_form_name (attr.form),
5877                      objfile_name (objfile));
5878           return NULL;
5879         }
5880       switch (attr.dw_idx)
5881         {
5882         case DW_IDX_compile_unit:
5883           /* Don't crash on bad data.  */
5884           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5885             {
5886               complaint (_(".debug_names entry has bad CU index %s"
5887                            " [in module %s]"),
5888                          pulongest (ull),
5889                          objfile_name (dwarf2_per_objfile->objfile));
5890               continue;
5891             }
5892           per_cu = dwarf2_per_objfile->get_cutu (ull);
5893           break;
5894         case DW_IDX_type_unit:
5895           /* Don't crash on bad data.  */
5896           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5897             {
5898               complaint (_(".debug_names entry has bad TU index %s"
5899                            " [in module %s]"),
5900                          pulongest (ull),
5901                          objfile_name (dwarf2_per_objfile->objfile));
5902               continue;
5903             }
5904           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5905           break;
5906         case DW_IDX_GNU_internal:
5907           if (!m_map.augmentation_is_gdb)
5908             break;
5909           have_is_static = true;
5910           is_static = true;
5911           break;
5912         case DW_IDX_GNU_external:
5913           if (!m_map.augmentation_is_gdb)
5914             break;
5915           have_is_static = true;
5916           is_static = false;
5917           break;
5918         }
5919     }
5920
5921   /* Skip if already read in.  */
5922   if (per_cu->v.quick->compunit_symtab)
5923     goto again;
5924
5925   /* Check static vs global.  */
5926   if (have_is_static)
5927     {
5928       const bool want_static = m_block_index != GLOBAL_BLOCK;
5929       if (m_want_specific_block && want_static != is_static)
5930         goto again;
5931     }
5932
5933   /* Match dw2_symtab_iter_next, symbol_kind
5934      and debug_names::psymbol_tag.  */
5935   switch (m_domain)
5936     {
5937     case VAR_DOMAIN:
5938       switch (indexval.dwarf_tag)
5939         {
5940         case DW_TAG_variable:
5941         case DW_TAG_subprogram:
5942         /* Some types are also in VAR_DOMAIN.  */
5943         case DW_TAG_typedef:
5944         case DW_TAG_structure_type:
5945           break;
5946         default:
5947           goto again;
5948         }
5949       break;
5950     case STRUCT_DOMAIN:
5951       switch (indexval.dwarf_tag)
5952         {
5953         case DW_TAG_typedef:
5954         case DW_TAG_structure_type:
5955           break;
5956         default:
5957           goto again;
5958         }
5959       break;
5960     case LABEL_DOMAIN:
5961       switch (indexval.dwarf_tag)
5962         {
5963         case 0:
5964         case DW_TAG_variable:
5965           break;
5966         default:
5967           goto again;
5968         }
5969       break;
5970     default:
5971       break;
5972     }
5973
5974   /* Match dw2_expand_symtabs_matching, symbol_kind and
5975      debug_names::psymbol_tag.  */
5976   switch (m_search)
5977     {
5978     case VARIABLES_DOMAIN:
5979       switch (indexval.dwarf_tag)
5980         {
5981         case DW_TAG_variable:
5982           break;
5983         default:
5984           goto again;
5985         }
5986       break;
5987     case FUNCTIONS_DOMAIN:
5988       switch (indexval.dwarf_tag)
5989         {
5990         case DW_TAG_subprogram:
5991           break;
5992         default:
5993           goto again;
5994         }
5995       break;
5996     case TYPES_DOMAIN:
5997       switch (indexval.dwarf_tag)
5998         {
5999         case DW_TAG_typedef:
6000         case DW_TAG_structure_type:
6001           break;
6002         default:
6003           goto again;
6004         }
6005       break;
6006     default:
6007       break;
6008     }
6009
6010   return per_cu;
6011 }
6012
6013 static struct compunit_symtab *
6014 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6015                                const char *name, domain_enum domain)
6016 {
6017   const block_enum block_index = static_cast<block_enum> (block_index_int);
6018   struct dwarf2_per_objfile *dwarf2_per_objfile
6019     = get_dwarf2_per_objfile (objfile);
6020
6021   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6022   if (!mapp)
6023     {
6024       /* index is NULL if OBJF_READNOW.  */
6025       return NULL;
6026     }
6027   const auto &map = *mapp;
6028
6029   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6030                                  block_index, domain, name);
6031
6032   struct compunit_symtab *stab_best = NULL;
6033   struct dwarf2_per_cu_data *per_cu;
6034   while ((per_cu = iter.next ()) != NULL)
6035     {
6036       struct symbol *sym, *with_opaque = NULL;
6037       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
6038       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6039       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6040
6041       sym = block_find_symbol (block, name, domain,
6042                                block_find_non_opaque_type_preferred,
6043                                &with_opaque);
6044
6045       /* Some caution must be observed with overloaded functions and
6046          methods, since the index will not contain any overload
6047          information (but NAME might contain it).  */
6048
6049       if (sym != NULL
6050           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6051         return stab;
6052       if (with_opaque != NULL
6053           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6054         stab_best = stab;
6055
6056       /* Keep looking through other CUs.  */
6057     }
6058
6059   return stab_best;
6060 }
6061
6062 /* This dumps minimal information about .debug_names.  It is called
6063    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6064    uses this to verify that .debug_names has been loaded.  */
6065
6066 static void
6067 dw2_debug_names_dump (struct objfile *objfile)
6068 {
6069   struct dwarf2_per_objfile *dwarf2_per_objfile
6070     = get_dwarf2_per_objfile (objfile);
6071
6072   gdb_assert (dwarf2_per_objfile->using_index);
6073   printf_filtered (".debug_names:");
6074   if (dwarf2_per_objfile->debug_names_table)
6075     printf_filtered (" exists\n");
6076   else
6077     printf_filtered (" faked for \"readnow\"\n");
6078   printf_filtered ("\n");
6079 }
6080
6081 static void
6082 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6083                                              const char *func_name)
6084 {
6085   struct dwarf2_per_objfile *dwarf2_per_objfile
6086     = get_dwarf2_per_objfile (objfile);
6087
6088   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6089   if (dwarf2_per_objfile->debug_names_table)
6090     {
6091       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6092
6093       /* Note: It doesn't matter what we pass for block_index here.  */
6094       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6095                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6096
6097       struct dwarf2_per_cu_data *per_cu;
6098       while ((per_cu = iter.next ()) != NULL)
6099         dw2_instantiate_symtab (per_cu, false);
6100     }
6101 }
6102
6103 static void
6104 dw2_debug_names_expand_symtabs_matching
6105   (struct objfile *objfile,
6106    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6107    const lookup_name_info &lookup_name,
6108    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6109    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6110    enum search_domain kind)
6111 {
6112   struct dwarf2_per_objfile *dwarf2_per_objfile
6113     = get_dwarf2_per_objfile (objfile);
6114
6115   /* debug_names_table is NULL if OBJF_READNOW.  */
6116   if (!dwarf2_per_objfile->debug_names_table)
6117     return;
6118
6119   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6120
6121   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6122
6123   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6124                                       symbol_matcher,
6125                                       kind, [&] (offset_type namei)
6126     {
6127       /* The name was matched, now expand corresponding CUs that were
6128          marked.  */
6129       dw2_debug_names_iterator iter (map, kind, namei);
6130
6131       struct dwarf2_per_cu_data *per_cu;
6132       while ((per_cu = iter.next ()) != NULL)
6133         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6134                                          expansion_notify);
6135     });
6136 }
6137
6138 const struct quick_symbol_functions dwarf2_debug_names_functions =
6139 {
6140   dw2_has_symbols,
6141   dw2_find_last_source_symtab,
6142   dw2_forget_cached_source_info,
6143   dw2_map_symtabs_matching_filename,
6144   dw2_debug_names_lookup_symbol,
6145   dw2_print_stats,
6146   dw2_debug_names_dump,
6147   dw2_debug_names_expand_symtabs_for_function,
6148   dw2_expand_all_symtabs,
6149   dw2_expand_symtabs_with_fullname,
6150   dw2_map_matching_symbols,
6151   dw2_debug_names_expand_symtabs_matching,
6152   dw2_find_pc_sect_compunit_symtab,
6153   NULL,
6154   dw2_map_symbol_filenames
6155 };
6156
6157 /* See symfile.h.  */
6158
6159 bool
6160 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6161 {
6162   struct dwarf2_per_objfile *dwarf2_per_objfile
6163     = get_dwarf2_per_objfile (objfile);
6164
6165   /* If we're about to read full symbols, don't bother with the
6166      indices.  In this case we also don't care if some other debug
6167      format is making psymtabs, because they are all about to be
6168      expanded anyway.  */
6169   if ((objfile->flags & OBJF_READNOW))
6170     {
6171       dwarf2_per_objfile->using_index = 1;
6172       create_all_comp_units (dwarf2_per_objfile);
6173       create_all_type_units (dwarf2_per_objfile);
6174       dwarf2_per_objfile->quick_file_names_table
6175         = create_quick_file_names_table
6176             (dwarf2_per_objfile->all_comp_units.size ());
6177
6178       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6179                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6180         {
6181           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6182
6183           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6184                                             struct dwarf2_per_cu_quick_data);
6185         }
6186
6187       /* Return 1 so that gdb sees the "quick" functions.  However,
6188          these functions will be no-ops because we will have expanded
6189          all symtabs.  */
6190       *index_kind = dw_index_kind::GDB_INDEX;
6191       return true;
6192     }
6193
6194   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6195     {
6196       *index_kind = dw_index_kind::DEBUG_NAMES;
6197       return true;
6198     }
6199
6200   if (dwarf2_read_gdb_index (dwarf2_per_objfile))
6201     {
6202       *index_kind = dw_index_kind::GDB_INDEX;
6203       return true;
6204     }
6205
6206   return false;
6207 }
6208
6209 \f
6210
6211 /* Build a partial symbol table.  */
6212
6213 void
6214 dwarf2_build_psymtabs (struct objfile *objfile)
6215 {
6216   struct dwarf2_per_objfile *dwarf2_per_objfile
6217     = get_dwarf2_per_objfile (objfile);
6218
6219   if (objfile->global_psymbols.capacity () == 0
6220       && objfile->static_psymbols.capacity () == 0)
6221     init_psymbol_list (objfile, 1024);
6222
6223   TRY
6224     {
6225       /* This isn't really ideal: all the data we allocate on the
6226          objfile's obstack is still uselessly kept around.  However,
6227          freeing it seems unsafe.  */
6228       psymtab_discarder psymtabs (objfile);
6229       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6230       psymtabs.keep ();
6231     }
6232   CATCH (except, RETURN_MASK_ERROR)
6233     {
6234       exception_print (gdb_stderr, except);
6235     }
6236   END_CATCH
6237 }
6238
6239 /* Return the total length of the CU described by HEADER.  */
6240
6241 static unsigned int
6242 get_cu_length (const struct comp_unit_head *header)
6243 {
6244   return header->initial_length_size + header->length;
6245 }
6246
6247 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6248
6249 static inline bool
6250 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6251 {
6252   sect_offset bottom = cu_header->sect_off;
6253   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6254
6255   return sect_off >= bottom && sect_off < top;
6256 }
6257
6258 /* Find the base address of the compilation unit for range lists and
6259    location lists.  It will normally be specified by DW_AT_low_pc.
6260    In DWARF-3 draft 4, the base address could be overridden by
6261    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6262    compilation units with discontinuous ranges.  */
6263
6264 static void
6265 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6266 {
6267   struct attribute *attr;
6268
6269   cu->base_known = 0;
6270   cu->base_address = 0;
6271
6272   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6273   if (attr)
6274     {
6275       cu->base_address = attr_value_as_address (attr);
6276       cu->base_known = 1;
6277     }
6278   else
6279     {
6280       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6281       if (attr)
6282         {
6283           cu->base_address = attr_value_as_address (attr);
6284           cu->base_known = 1;
6285         }
6286     }
6287 }
6288
6289 /* Read in the comp unit header information from the debug_info at info_ptr.
6290    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6291    NOTE: This leaves members offset, first_die_offset to be filled in
6292    by the caller.  */
6293
6294 static const gdb_byte *
6295 read_comp_unit_head (struct comp_unit_head *cu_header,
6296                      const gdb_byte *info_ptr,
6297                      struct dwarf2_section_info *section,
6298                      rcuh_kind section_kind)
6299 {
6300   int signed_addr;
6301   unsigned int bytes_read;
6302   const char *filename = get_section_file_name (section);
6303   bfd *abfd = get_section_bfd_owner (section);
6304
6305   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6306   cu_header->initial_length_size = bytes_read;
6307   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6308   info_ptr += bytes_read;
6309   cu_header->version = read_2_bytes (abfd, info_ptr);
6310   if (cu_header->version < 2 || cu_header->version > 5)
6311     error (_("Dwarf Error: wrong version in compilation unit header "
6312            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6313            cu_header->version, filename);
6314   info_ptr += 2;
6315   if (cu_header->version < 5)
6316     switch (section_kind)
6317       {
6318       case rcuh_kind::COMPILE:
6319         cu_header->unit_type = DW_UT_compile;
6320         break;
6321       case rcuh_kind::TYPE:
6322         cu_header->unit_type = DW_UT_type;
6323         break;
6324       default:
6325         internal_error (__FILE__, __LINE__,
6326                         _("read_comp_unit_head: invalid section_kind"));
6327       }
6328   else
6329     {
6330       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6331                                                  (read_1_byte (abfd, info_ptr));
6332       info_ptr += 1;
6333       switch (cu_header->unit_type)
6334         {
6335         case DW_UT_compile:
6336           if (section_kind != rcuh_kind::COMPILE)
6337             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6338                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6339                    filename);
6340           break;
6341         case DW_UT_type:
6342           section_kind = rcuh_kind::TYPE;
6343           break;
6344         default:
6345           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6346                  "(is %d, should be %d or %d) [in module %s]"),
6347                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6348         }
6349
6350       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6351       info_ptr += 1;
6352     }
6353   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6354                                                           cu_header,
6355                                                           &bytes_read);
6356   info_ptr += bytes_read;
6357   if (cu_header->version < 5)
6358     {
6359       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6360       info_ptr += 1;
6361     }
6362   signed_addr = bfd_get_sign_extend_vma (abfd);
6363   if (signed_addr < 0)
6364     internal_error (__FILE__, __LINE__,
6365                     _("read_comp_unit_head: dwarf from non elf file"));
6366   cu_header->signed_addr_p = signed_addr;
6367
6368   if (section_kind == rcuh_kind::TYPE)
6369     {
6370       LONGEST type_offset;
6371
6372       cu_header->signature = read_8_bytes (abfd, info_ptr);
6373       info_ptr += 8;
6374
6375       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6376       info_ptr += bytes_read;
6377       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6378       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6379         error (_("Dwarf Error: Too big type_offset in compilation unit "
6380                "header (is %s) [in module %s]"), plongest (type_offset),
6381                filename);
6382     }
6383
6384   return info_ptr;
6385 }
6386
6387 /* Helper function that returns the proper abbrev section for
6388    THIS_CU.  */
6389
6390 static struct dwarf2_section_info *
6391 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6392 {
6393   struct dwarf2_section_info *abbrev;
6394   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6395
6396   if (this_cu->is_dwz)
6397     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6398   else
6399     abbrev = &dwarf2_per_objfile->abbrev;
6400
6401   return abbrev;
6402 }
6403
6404 /* Subroutine of read_and_check_comp_unit_head and
6405    read_and_check_type_unit_head to simplify them.
6406    Perform various error checking on the header.  */
6407
6408 static void
6409 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6410                             struct comp_unit_head *header,
6411                             struct dwarf2_section_info *section,
6412                             struct dwarf2_section_info *abbrev_section)
6413 {
6414   const char *filename = get_section_file_name (section);
6415
6416   if (to_underlying (header->abbrev_sect_off)
6417       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6418     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6419            "(offset %s + 6) [in module %s]"),
6420            sect_offset_str (header->abbrev_sect_off),
6421            sect_offset_str (header->sect_off),
6422            filename);
6423
6424   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6425      avoid potential 32-bit overflow.  */
6426   if (((ULONGEST) header->sect_off + get_cu_length (header))
6427       > section->size)
6428     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6429            "(offset %s + 0) [in module %s]"),
6430            header->length, sect_offset_str (header->sect_off),
6431            filename);
6432 }
6433
6434 /* Read in a CU/TU header and perform some basic error checking.
6435    The contents of the header are stored in HEADER.
6436    The result is a pointer to the start of the first DIE.  */
6437
6438 static const gdb_byte *
6439 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6440                                struct comp_unit_head *header,
6441                                struct dwarf2_section_info *section,
6442                                struct dwarf2_section_info *abbrev_section,
6443                                const gdb_byte *info_ptr,
6444                                rcuh_kind section_kind)
6445 {
6446   const gdb_byte *beg_of_comp_unit = info_ptr;
6447
6448   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6449
6450   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6451
6452   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6453
6454   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6455                               abbrev_section);
6456
6457   return info_ptr;
6458 }
6459
6460 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6461
6462 static sect_offset
6463 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6464                     struct dwarf2_section_info *section,
6465                     sect_offset sect_off)
6466 {
6467   bfd *abfd = get_section_bfd_owner (section);
6468   const gdb_byte *info_ptr;
6469   unsigned int initial_length_size, offset_size;
6470   uint16_t version;
6471
6472   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6473   info_ptr = section->buffer + to_underlying (sect_off);
6474   read_initial_length (abfd, info_ptr, &initial_length_size);
6475   offset_size = initial_length_size == 4 ? 4 : 8;
6476   info_ptr += initial_length_size;
6477
6478   version = read_2_bytes (abfd, info_ptr);
6479   info_ptr += 2;
6480   if (version >= 5)
6481     {
6482       /* Skip unit type and address size.  */
6483       info_ptr += 2;
6484     }
6485
6486   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6487 }
6488
6489 /* Allocate a new partial symtab for file named NAME and mark this new
6490    partial symtab as being an include of PST.  */
6491
6492 static void
6493 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6494                                struct objfile *objfile)
6495 {
6496   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6497
6498   if (!IS_ABSOLUTE_PATH (subpst->filename))
6499     {
6500       /* It shares objfile->objfile_obstack.  */
6501       subpst->dirname = pst->dirname;
6502     }
6503
6504   subpst->dependencies
6505     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6506   subpst->dependencies[0] = pst;
6507   subpst->number_of_dependencies = 1;
6508
6509   subpst->globals_offset = 0;
6510   subpst->n_global_syms = 0;
6511   subpst->statics_offset = 0;
6512   subpst->n_static_syms = 0;
6513   subpst->compunit_symtab = NULL;
6514   subpst->read_symtab = pst->read_symtab;
6515   subpst->readin = 0;
6516
6517   /* No private part is necessary for include psymtabs.  This property
6518      can be used to differentiate between such include psymtabs and
6519      the regular ones.  */
6520   subpst->read_symtab_private = NULL;
6521 }
6522
6523 /* Read the Line Number Program data and extract the list of files
6524    included by the source file represented by PST.  Build an include
6525    partial symtab for each of these included files.  */
6526
6527 static void
6528 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6529                                struct die_info *die,
6530                                struct partial_symtab *pst)
6531 {
6532   line_header_up lh;
6533   struct attribute *attr;
6534
6535   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6536   if (attr)
6537     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6538   if (lh == NULL)
6539     return;  /* No linetable, so no includes.  */
6540
6541   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
6542      that we pass in the raw text_low here; that is ok because we're
6543      only decoding the line table to make include partial symtabs, and
6544      so the addresses aren't really used.  */
6545   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
6546                       pst->raw_text_low (), 1);
6547 }
6548
6549 static hashval_t
6550 hash_signatured_type (const void *item)
6551 {
6552   const struct signatured_type *sig_type
6553     = (const struct signatured_type *) item;
6554
6555   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6556   return sig_type->signature;
6557 }
6558
6559 static int
6560 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6561 {
6562   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6563   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6564
6565   return lhs->signature == rhs->signature;
6566 }
6567
6568 /* Allocate a hash table for signatured types.  */
6569
6570 static htab_t
6571 allocate_signatured_type_table (struct objfile *objfile)
6572 {
6573   return htab_create_alloc_ex (41,
6574                                hash_signatured_type,
6575                                eq_signatured_type,
6576                                NULL,
6577                                &objfile->objfile_obstack,
6578                                hashtab_obstack_allocate,
6579                                dummy_obstack_deallocate);
6580 }
6581
6582 /* A helper function to add a signatured type CU to a table.  */
6583
6584 static int
6585 add_signatured_type_cu_to_table (void **slot, void *datum)
6586 {
6587   struct signatured_type *sigt = (struct signatured_type *) *slot;
6588   std::vector<signatured_type *> *all_type_units
6589     = (std::vector<signatured_type *> *) datum;
6590
6591   all_type_units->push_back (sigt);
6592
6593   return 1;
6594 }
6595
6596 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6597    and fill them into TYPES_HTAB.  It will process only type units,
6598    therefore DW_UT_type.  */
6599
6600 static void
6601 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6602                               struct dwo_file *dwo_file,
6603                               dwarf2_section_info *section, htab_t &types_htab,
6604                               rcuh_kind section_kind)
6605 {
6606   struct objfile *objfile = dwarf2_per_objfile->objfile;
6607   struct dwarf2_section_info *abbrev_section;
6608   bfd *abfd;
6609   const gdb_byte *info_ptr, *end_ptr;
6610
6611   abbrev_section = (dwo_file != NULL
6612                     ? &dwo_file->sections.abbrev
6613                     : &dwarf2_per_objfile->abbrev);
6614
6615   if (dwarf_read_debug)
6616     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6617                         get_section_name (section),
6618                         get_section_file_name (abbrev_section));
6619
6620   dwarf2_read_section (objfile, section);
6621   info_ptr = section->buffer;
6622
6623   if (info_ptr == NULL)
6624     return;
6625
6626   /* We can't set abfd until now because the section may be empty or
6627      not present, in which case the bfd is unknown.  */
6628   abfd = get_section_bfd_owner (section);
6629
6630   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6631      because we don't need to read any dies: the signature is in the
6632      header.  */
6633
6634   end_ptr = info_ptr + section->size;
6635   while (info_ptr < end_ptr)
6636     {
6637       struct signatured_type *sig_type;
6638       struct dwo_unit *dwo_tu;
6639       void **slot;
6640       const gdb_byte *ptr = info_ptr;
6641       struct comp_unit_head header;
6642       unsigned int length;
6643
6644       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6645
6646       /* Initialize it due to a false compiler warning.  */
6647       header.signature = -1;
6648       header.type_cu_offset_in_tu = (cu_offset) -1;
6649
6650       /* We need to read the type's signature in order to build the hash
6651          table, but we don't need anything else just yet.  */
6652
6653       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6654                                            abbrev_section, ptr, section_kind);
6655
6656       length = get_cu_length (&header);
6657
6658       /* Skip dummy type units.  */
6659       if (ptr >= info_ptr + length
6660           || peek_abbrev_code (abfd, ptr) == 0
6661           || header.unit_type != DW_UT_type)
6662         {
6663           info_ptr += length;
6664           continue;
6665         }
6666
6667       if (types_htab == NULL)
6668         {
6669           if (dwo_file)
6670             types_htab = allocate_dwo_unit_table (objfile);
6671           else
6672             types_htab = allocate_signatured_type_table (objfile);
6673         }
6674
6675       if (dwo_file)
6676         {
6677           sig_type = NULL;
6678           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6679                                    struct dwo_unit);
6680           dwo_tu->dwo_file = dwo_file;
6681           dwo_tu->signature = header.signature;
6682           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6683           dwo_tu->section = section;
6684           dwo_tu->sect_off = sect_off;
6685           dwo_tu->length = length;
6686         }
6687       else
6688         {
6689           /* N.B.: type_offset is not usable if this type uses a DWO file.
6690              The real type_offset is in the DWO file.  */
6691           dwo_tu = NULL;
6692           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6693                                      struct signatured_type);
6694           sig_type->signature = header.signature;
6695           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6696           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6697           sig_type->per_cu.is_debug_types = 1;
6698           sig_type->per_cu.section = section;
6699           sig_type->per_cu.sect_off = sect_off;
6700           sig_type->per_cu.length = length;
6701         }
6702
6703       slot = htab_find_slot (types_htab,
6704                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6705                              INSERT);
6706       gdb_assert (slot != NULL);
6707       if (*slot != NULL)
6708         {
6709           sect_offset dup_sect_off;
6710
6711           if (dwo_file)
6712             {
6713               const struct dwo_unit *dup_tu
6714                 = (const struct dwo_unit *) *slot;
6715
6716               dup_sect_off = dup_tu->sect_off;
6717             }
6718           else
6719             {
6720               const struct signatured_type *dup_tu
6721                 = (const struct signatured_type *) *slot;
6722
6723               dup_sect_off = dup_tu->per_cu.sect_off;
6724             }
6725
6726           complaint (_("debug type entry at offset %s is duplicate to"
6727                        " the entry at offset %s, signature %s"),
6728                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6729                      hex_string (header.signature));
6730         }
6731       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6732
6733       if (dwarf_read_debug > 1)
6734         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6735                             sect_offset_str (sect_off),
6736                             hex_string (header.signature));
6737
6738       info_ptr += length;
6739     }
6740 }
6741
6742 /* Create the hash table of all entries in the .debug_types
6743    (or .debug_types.dwo) section(s).
6744    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6745    otherwise it is NULL.
6746
6747    The result is a pointer to the hash table or NULL if there are no types.
6748
6749    Note: This function processes DWO files only, not DWP files.  */
6750
6751 static void
6752 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6753                                struct dwo_file *dwo_file,
6754                                VEC (dwarf2_section_info_def) *types,
6755                                htab_t &types_htab)
6756 {
6757   int ix;
6758   struct dwarf2_section_info *section;
6759
6760   if (VEC_empty (dwarf2_section_info_def, types))
6761     return;
6762
6763   for (ix = 0;
6764        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6765        ++ix)
6766     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6767                                   types_htab, rcuh_kind::TYPE);
6768 }
6769
6770 /* Create the hash table of all entries in the .debug_types section,
6771    and initialize all_type_units.
6772    The result is zero if there is an error (e.g. missing .debug_types section),
6773    otherwise non-zero.  */
6774
6775 static int
6776 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6777 {
6778   htab_t types_htab = NULL;
6779
6780   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6781                                 &dwarf2_per_objfile->info, types_htab,
6782                                 rcuh_kind::COMPILE);
6783   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6784                                  dwarf2_per_objfile->types, types_htab);
6785   if (types_htab == NULL)
6786     {
6787       dwarf2_per_objfile->signatured_types = NULL;
6788       return 0;
6789     }
6790
6791   dwarf2_per_objfile->signatured_types = types_htab;
6792
6793   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6794   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6795
6796   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6797                           &dwarf2_per_objfile->all_type_units);
6798
6799   return 1;
6800 }
6801
6802 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6803    If SLOT is non-NULL, it is the entry to use in the hash table.
6804    Otherwise we find one.  */
6805
6806 static struct signatured_type *
6807 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6808                void **slot)
6809 {
6810   struct objfile *objfile = dwarf2_per_objfile->objfile;
6811
6812   if (dwarf2_per_objfile->all_type_units.size ()
6813       == dwarf2_per_objfile->all_type_units.capacity ())
6814     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6815
6816   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6817                                               struct signatured_type);
6818
6819   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6820   sig_type->signature = sig;
6821   sig_type->per_cu.is_debug_types = 1;
6822   if (dwarf2_per_objfile->using_index)
6823     {
6824       sig_type->per_cu.v.quick =
6825         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6826                         struct dwarf2_per_cu_quick_data);
6827     }
6828
6829   if (slot == NULL)
6830     {
6831       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6832                              sig_type, INSERT);
6833     }
6834   gdb_assert (*slot == NULL);
6835   *slot = sig_type;
6836   /* The rest of sig_type must be filled in by the caller.  */
6837   return sig_type;
6838 }
6839
6840 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6841    Fill in SIG_ENTRY with DWO_ENTRY.  */
6842
6843 static void
6844 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6845                                   struct signatured_type *sig_entry,
6846                                   struct dwo_unit *dwo_entry)
6847 {
6848   /* Make sure we're not clobbering something we don't expect to.  */
6849   gdb_assert (! sig_entry->per_cu.queued);
6850   gdb_assert (sig_entry->per_cu.cu == NULL);
6851   if (dwarf2_per_objfile->using_index)
6852     {
6853       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6854       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6855     }
6856   else
6857       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6858   gdb_assert (sig_entry->signature == dwo_entry->signature);
6859   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6860   gdb_assert (sig_entry->type_unit_group == NULL);
6861   gdb_assert (sig_entry->dwo_unit == NULL);
6862
6863   sig_entry->per_cu.section = dwo_entry->section;
6864   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6865   sig_entry->per_cu.length = dwo_entry->length;
6866   sig_entry->per_cu.reading_dwo_directly = 1;
6867   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6868   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6869   sig_entry->dwo_unit = dwo_entry;
6870 }
6871
6872 /* Subroutine of lookup_signatured_type.
6873    If we haven't read the TU yet, create the signatured_type data structure
6874    for a TU to be read in directly from a DWO file, bypassing the stub.
6875    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6876    using .gdb_index, then when reading a CU we want to stay in the DWO file
6877    containing that CU.  Otherwise we could end up reading several other DWO
6878    files (due to comdat folding) to process the transitive closure of all the
6879    mentioned TUs, and that can be slow.  The current DWO file will have every
6880    type signature that it needs.
6881    We only do this for .gdb_index because in the psymtab case we already have
6882    to read all the DWOs to build the type unit groups.  */
6883
6884 static struct signatured_type *
6885 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6886 {
6887   struct dwarf2_per_objfile *dwarf2_per_objfile
6888     = cu->per_cu->dwarf2_per_objfile;
6889   struct objfile *objfile = dwarf2_per_objfile->objfile;
6890   struct dwo_file *dwo_file;
6891   struct dwo_unit find_dwo_entry, *dwo_entry;
6892   struct signatured_type find_sig_entry, *sig_entry;
6893   void **slot;
6894
6895   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6896
6897   /* If TU skeletons have been removed then we may not have read in any
6898      TUs yet.  */
6899   if (dwarf2_per_objfile->signatured_types == NULL)
6900     {
6901       dwarf2_per_objfile->signatured_types
6902         = allocate_signatured_type_table (objfile);
6903     }
6904
6905   /* We only ever need to read in one copy of a signatured type.
6906      Use the global signatured_types array to do our own comdat-folding
6907      of types.  If this is the first time we're reading this TU, and
6908      the TU has an entry in .gdb_index, replace the recorded data from
6909      .gdb_index with this TU.  */
6910
6911   find_sig_entry.signature = sig;
6912   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6913                          &find_sig_entry, INSERT);
6914   sig_entry = (struct signatured_type *) *slot;
6915
6916   /* We can get here with the TU already read, *or* in the process of being
6917      read.  Don't reassign the global entry to point to this DWO if that's
6918      the case.  Also note that if the TU is already being read, it may not
6919      have come from a DWO, the program may be a mix of Fission-compiled
6920      code and non-Fission-compiled code.  */
6921
6922   /* Have we already tried to read this TU?
6923      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6924      needn't exist in the global table yet).  */
6925   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6926     return sig_entry;
6927
6928   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6929      dwo_unit of the TU itself.  */
6930   dwo_file = cu->dwo_unit->dwo_file;
6931
6932   /* Ok, this is the first time we're reading this TU.  */
6933   if (dwo_file->tus == NULL)
6934     return NULL;
6935   find_dwo_entry.signature = sig;
6936   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
6937   if (dwo_entry == NULL)
6938     return NULL;
6939
6940   /* If the global table doesn't have an entry for this TU, add one.  */
6941   if (sig_entry == NULL)
6942     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6943
6944   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6945   sig_entry->per_cu.tu_read = 1;
6946   return sig_entry;
6947 }
6948
6949 /* Subroutine of lookup_signatured_type.
6950    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6951    then try the DWP file.  If the TU stub (skeleton) has been removed then
6952    it won't be in .gdb_index.  */
6953
6954 static struct signatured_type *
6955 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6956 {
6957   struct dwarf2_per_objfile *dwarf2_per_objfile
6958     = cu->per_cu->dwarf2_per_objfile;
6959   struct objfile *objfile = dwarf2_per_objfile->objfile;
6960   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
6961   struct dwo_unit *dwo_entry;
6962   struct signatured_type find_sig_entry, *sig_entry;
6963   void **slot;
6964
6965   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6966   gdb_assert (dwp_file != NULL);
6967
6968   /* If TU skeletons have been removed then we may not have read in any
6969      TUs yet.  */
6970   if (dwarf2_per_objfile->signatured_types == NULL)
6971     {
6972       dwarf2_per_objfile->signatured_types
6973         = allocate_signatured_type_table (objfile);
6974     }
6975
6976   find_sig_entry.signature = sig;
6977   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6978                          &find_sig_entry, INSERT);
6979   sig_entry = (struct signatured_type *) *slot;
6980
6981   /* Have we already tried to read this TU?
6982      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6983      needn't exist in the global table yet).  */
6984   if (sig_entry != NULL)
6985     return sig_entry;
6986
6987   if (dwp_file->tus == NULL)
6988     return NULL;
6989   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
6990                                       sig, 1 /* is_debug_types */);
6991   if (dwo_entry == NULL)
6992     return NULL;
6993
6994   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6995   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6996
6997   return sig_entry;
6998 }
6999
7000 /* Lookup a signature based type for DW_FORM_ref_sig8.
7001    Returns NULL if signature SIG is not present in the table.
7002    It is up to the caller to complain about this.  */
7003
7004 static struct signatured_type *
7005 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7006 {
7007   struct dwarf2_per_objfile *dwarf2_per_objfile
7008     = cu->per_cu->dwarf2_per_objfile;
7009
7010   if (cu->dwo_unit
7011       && dwarf2_per_objfile->using_index)
7012     {
7013       /* We're in a DWO/DWP file, and we're using .gdb_index.
7014          These cases require special processing.  */
7015       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7016         return lookup_dwo_signatured_type (cu, sig);
7017       else
7018         return lookup_dwp_signatured_type (cu, sig);
7019     }
7020   else
7021     {
7022       struct signatured_type find_entry, *entry;
7023
7024       if (dwarf2_per_objfile->signatured_types == NULL)
7025         return NULL;
7026       find_entry.signature = sig;
7027       entry = ((struct signatured_type *)
7028                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7029       return entry;
7030     }
7031 }
7032 \f
7033 /* Low level DIE reading support.  */
7034
7035 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7036
7037 static void
7038 init_cu_die_reader (struct die_reader_specs *reader,
7039                     struct dwarf2_cu *cu,
7040                     struct dwarf2_section_info *section,
7041                     struct dwo_file *dwo_file,
7042                     struct abbrev_table *abbrev_table)
7043 {
7044   gdb_assert (section->readin && section->buffer != NULL);
7045   reader->abfd = get_section_bfd_owner (section);
7046   reader->cu = cu;
7047   reader->dwo_file = dwo_file;
7048   reader->die_section = section;
7049   reader->buffer = section->buffer;
7050   reader->buffer_end = section->buffer + section->size;
7051   reader->comp_dir = NULL;
7052   reader->abbrev_table = abbrev_table;
7053 }
7054
7055 /* Subroutine of init_cutu_and_read_dies to simplify it.
7056    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7057    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7058    already.
7059
7060    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7061    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7062    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7063    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7064    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7065    STUB_COMP_DIR may be non-NULL.
7066    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7067    are filled in with the info of the DIE from the DWO file.
7068    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7069    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7070    kept around for at least as long as *RESULT_READER.
7071
7072    The result is non-zero if a valid (non-dummy) DIE was found.  */
7073
7074 static int
7075 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7076                         struct dwo_unit *dwo_unit,
7077                         struct die_info *stub_comp_unit_die,
7078                         const char *stub_comp_dir,
7079                         struct die_reader_specs *result_reader,
7080                         const gdb_byte **result_info_ptr,
7081                         struct die_info **result_comp_unit_die,
7082                         int *result_has_children,
7083                         abbrev_table_up *result_dwo_abbrev_table)
7084 {
7085   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7086   struct objfile *objfile = dwarf2_per_objfile->objfile;
7087   struct dwarf2_cu *cu = this_cu->cu;
7088   bfd *abfd;
7089   const gdb_byte *begin_info_ptr, *info_ptr;
7090   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7091   int i,num_extra_attrs;
7092   struct dwarf2_section_info *dwo_abbrev_section;
7093   struct attribute *attr;
7094   struct die_info *comp_unit_die;
7095
7096   /* At most one of these may be provided.  */
7097   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7098
7099   /* These attributes aren't processed until later:
7100      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7101      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7102      referenced later.  However, these attributes are found in the stub
7103      which we won't have later.  In order to not impose this complication
7104      on the rest of the code, we read them here and copy them to the
7105      DWO CU/TU die.  */
7106
7107   stmt_list = NULL;
7108   low_pc = NULL;
7109   high_pc = NULL;
7110   ranges = NULL;
7111   comp_dir = NULL;
7112
7113   if (stub_comp_unit_die != NULL)
7114     {
7115       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7116          DWO file.  */
7117       if (! this_cu->is_debug_types)
7118         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7119       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7120       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7121       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7122       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7123
7124       /* There should be a DW_AT_addr_base attribute here (if needed).
7125          We need the value before we can process DW_FORM_GNU_addr_index.  */
7126       cu->addr_base = 0;
7127       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7128       if (attr)
7129         cu->addr_base = DW_UNSND (attr);
7130
7131       /* There should be a DW_AT_ranges_base attribute here (if needed).
7132          We need the value before we can process DW_AT_ranges.  */
7133       cu->ranges_base = 0;
7134       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7135       if (attr)
7136         cu->ranges_base = DW_UNSND (attr);
7137     }
7138   else if (stub_comp_dir != NULL)
7139     {
7140       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7141       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7142       comp_dir->name = DW_AT_comp_dir;
7143       comp_dir->form = DW_FORM_string;
7144       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7145       DW_STRING (comp_dir) = stub_comp_dir;
7146     }
7147
7148   /* Set up for reading the DWO CU/TU.  */
7149   cu->dwo_unit = dwo_unit;
7150   dwarf2_section_info *section = dwo_unit->section;
7151   dwarf2_read_section (objfile, section);
7152   abfd = get_section_bfd_owner (section);
7153   begin_info_ptr = info_ptr = (section->buffer
7154                                + to_underlying (dwo_unit->sect_off));
7155   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7156
7157   if (this_cu->is_debug_types)
7158     {
7159       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7160
7161       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7162                                                 &cu->header, section,
7163                                                 dwo_abbrev_section,
7164                                                 info_ptr, rcuh_kind::TYPE);
7165       /* This is not an assert because it can be caused by bad debug info.  */
7166       if (sig_type->signature != cu->header.signature)
7167         {
7168           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7169                    " TU at offset %s [in module %s]"),
7170                  hex_string (sig_type->signature),
7171                  hex_string (cu->header.signature),
7172                  sect_offset_str (dwo_unit->sect_off),
7173                  bfd_get_filename (abfd));
7174         }
7175       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7176       /* For DWOs coming from DWP files, we don't know the CU length
7177          nor the type's offset in the TU until now.  */
7178       dwo_unit->length = get_cu_length (&cu->header);
7179       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7180
7181       /* Establish the type offset that can be used to lookup the type.
7182          For DWO files, we don't know it until now.  */
7183       sig_type->type_offset_in_section
7184         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7185     }
7186   else
7187     {
7188       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7189                                                 &cu->header, section,
7190                                                 dwo_abbrev_section,
7191                                                 info_ptr, rcuh_kind::COMPILE);
7192       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7193       /* For DWOs coming from DWP files, we don't know the CU length
7194          until now.  */
7195       dwo_unit->length = get_cu_length (&cu->header);
7196     }
7197
7198   *result_dwo_abbrev_table
7199     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7200                                cu->header.abbrev_sect_off);
7201   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7202                       result_dwo_abbrev_table->get ());
7203
7204   /* Read in the die, but leave space to copy over the attributes
7205      from the stub.  This has the benefit of simplifying the rest of
7206      the code - all the work to maintain the illusion of a single
7207      DW_TAG_{compile,type}_unit DIE is done here.  */
7208   num_extra_attrs = ((stmt_list != NULL)
7209                      + (low_pc != NULL)
7210                      + (high_pc != NULL)
7211                      + (ranges != NULL)
7212                      + (comp_dir != NULL));
7213   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7214                               result_has_children, num_extra_attrs);
7215
7216   /* Copy over the attributes from the stub to the DIE we just read in.  */
7217   comp_unit_die = *result_comp_unit_die;
7218   i = comp_unit_die->num_attrs;
7219   if (stmt_list != NULL)
7220     comp_unit_die->attrs[i++] = *stmt_list;
7221   if (low_pc != NULL)
7222     comp_unit_die->attrs[i++] = *low_pc;
7223   if (high_pc != NULL)
7224     comp_unit_die->attrs[i++] = *high_pc;
7225   if (ranges != NULL)
7226     comp_unit_die->attrs[i++] = *ranges;
7227   if (comp_dir != NULL)
7228     comp_unit_die->attrs[i++] = *comp_dir;
7229   comp_unit_die->num_attrs += num_extra_attrs;
7230
7231   if (dwarf_die_debug)
7232     {
7233       fprintf_unfiltered (gdb_stdlog,
7234                           "Read die from %s@0x%x of %s:\n",
7235                           get_section_name (section),
7236                           (unsigned) (begin_info_ptr - section->buffer),
7237                           bfd_get_filename (abfd));
7238       dump_die (comp_unit_die, dwarf_die_debug);
7239     }
7240
7241   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7242      TUs by skipping the stub and going directly to the entry in the DWO file.
7243      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7244      to get it via circuitous means.  Blech.  */
7245   if (comp_dir != NULL)
7246     result_reader->comp_dir = DW_STRING (comp_dir);
7247
7248   /* Skip dummy compilation units.  */
7249   if (info_ptr >= begin_info_ptr + dwo_unit->length
7250       || peek_abbrev_code (abfd, info_ptr) == 0)
7251     return 0;
7252
7253   *result_info_ptr = info_ptr;
7254   return 1;
7255 }
7256
7257 /* Subroutine of init_cutu_and_read_dies to simplify it.
7258    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7259    Returns NULL if the specified DWO unit cannot be found.  */
7260
7261 static struct dwo_unit *
7262 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7263                  struct die_info *comp_unit_die)
7264 {
7265   struct dwarf2_cu *cu = this_cu->cu;
7266   ULONGEST signature;
7267   struct dwo_unit *dwo_unit;
7268   const char *comp_dir, *dwo_name;
7269
7270   gdb_assert (cu != NULL);
7271
7272   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7273   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7274   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7275
7276   if (this_cu->is_debug_types)
7277     {
7278       struct signatured_type *sig_type;
7279
7280       /* Since this_cu is the first member of struct signatured_type,
7281          we can go from a pointer to one to a pointer to the other.  */
7282       sig_type = (struct signatured_type *) this_cu;
7283       signature = sig_type->signature;
7284       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7285     }
7286   else
7287     {
7288       struct attribute *attr;
7289
7290       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7291       if (! attr)
7292         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7293                  " [in module %s]"),
7294                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7295       signature = DW_UNSND (attr);
7296       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7297                                        signature);
7298     }
7299
7300   return dwo_unit;
7301 }
7302
7303 /* Subroutine of init_cutu_and_read_dies to simplify it.
7304    See it for a description of the parameters.
7305    Read a TU directly from a DWO file, bypassing the stub.  */
7306
7307 static void
7308 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7309                            int use_existing_cu, int keep,
7310                            die_reader_func_ftype *die_reader_func,
7311                            void *data)
7312 {
7313   std::unique_ptr<dwarf2_cu> new_cu;
7314   struct signatured_type *sig_type;
7315   struct die_reader_specs reader;
7316   const gdb_byte *info_ptr;
7317   struct die_info *comp_unit_die;
7318   int has_children;
7319   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7320
7321   /* Verify we can do the following downcast, and that we have the
7322      data we need.  */
7323   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7324   sig_type = (struct signatured_type *) this_cu;
7325   gdb_assert (sig_type->dwo_unit != NULL);
7326
7327   if (use_existing_cu && this_cu->cu != NULL)
7328     {
7329       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7330       /* There's no need to do the rereading_dwo_cu handling that
7331          init_cutu_and_read_dies does since we don't read the stub.  */
7332     }
7333   else
7334     {
7335       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7336       gdb_assert (this_cu->cu == NULL);
7337       new_cu.reset (new dwarf2_cu (this_cu));
7338     }
7339
7340   /* A future optimization, if needed, would be to use an existing
7341      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7342      could share abbrev tables.  */
7343
7344   /* The abbreviation table used by READER, this must live at least as long as
7345      READER.  */
7346   abbrev_table_up dwo_abbrev_table;
7347
7348   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7349                               NULL /* stub_comp_unit_die */,
7350                               sig_type->dwo_unit->dwo_file->comp_dir,
7351                               &reader, &info_ptr,
7352                               &comp_unit_die, &has_children,
7353                               &dwo_abbrev_table) == 0)
7354     {
7355       /* Dummy die.  */
7356       return;
7357     }
7358
7359   /* All the "real" work is done here.  */
7360   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7361
7362   /* This duplicates the code in init_cutu_and_read_dies,
7363      but the alternative is making the latter more complex.
7364      This function is only for the special case of using DWO files directly:
7365      no point in overly complicating the general case just to handle this.  */
7366   if (new_cu != NULL && keep)
7367     {
7368       /* Link this CU into read_in_chain.  */
7369       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7370       dwarf2_per_objfile->read_in_chain = this_cu;
7371       /* The chain owns it now.  */
7372       new_cu.release ();
7373     }
7374 }
7375
7376 /* Initialize a CU (or TU) and read its DIEs.
7377    If the CU defers to a DWO file, read the DWO file as well.
7378
7379    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7380    Otherwise the table specified in the comp unit header is read in and used.
7381    This is an optimization for when we already have the abbrev table.
7382
7383    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7384    Otherwise, a new CU is allocated with xmalloc.
7385
7386    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7387    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7388
7389    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7390    linker) then DIE_READER_FUNC will not get called.  */
7391
7392 static void
7393 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7394                          struct abbrev_table *abbrev_table,
7395                          int use_existing_cu, int keep,
7396                          bool skip_partial,
7397                          die_reader_func_ftype *die_reader_func,
7398                          void *data)
7399 {
7400   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7401   struct objfile *objfile = dwarf2_per_objfile->objfile;
7402   struct dwarf2_section_info *section = this_cu->section;
7403   bfd *abfd = get_section_bfd_owner (section);
7404   struct dwarf2_cu *cu;
7405   const gdb_byte *begin_info_ptr, *info_ptr;
7406   struct die_reader_specs reader;
7407   struct die_info *comp_unit_die;
7408   int has_children;
7409   struct attribute *attr;
7410   struct signatured_type *sig_type = NULL;
7411   struct dwarf2_section_info *abbrev_section;
7412   /* Non-zero if CU currently points to a DWO file and we need to
7413      reread it.  When this happens we need to reread the skeleton die
7414      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7415   int rereading_dwo_cu = 0;
7416
7417   if (dwarf_die_debug)
7418     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7419                         this_cu->is_debug_types ? "type" : "comp",
7420                         sect_offset_str (this_cu->sect_off));
7421
7422   if (use_existing_cu)
7423     gdb_assert (keep);
7424
7425   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7426      file (instead of going through the stub), short-circuit all of this.  */
7427   if (this_cu->reading_dwo_directly)
7428     {
7429       /* Narrow down the scope of possibilities to have to understand.  */
7430       gdb_assert (this_cu->is_debug_types);
7431       gdb_assert (abbrev_table == NULL);
7432       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7433                                  die_reader_func, data);
7434       return;
7435     }
7436
7437   /* This is cheap if the section is already read in.  */
7438   dwarf2_read_section (objfile, section);
7439
7440   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7441
7442   abbrev_section = get_abbrev_section_for_cu (this_cu);
7443
7444   std::unique_ptr<dwarf2_cu> new_cu;
7445   if (use_existing_cu && this_cu->cu != NULL)
7446     {
7447       cu = this_cu->cu;
7448       /* If this CU is from a DWO file we need to start over, we need to
7449          refetch the attributes from the skeleton CU.
7450          This could be optimized by retrieving those attributes from when we
7451          were here the first time: the previous comp_unit_die was stored in
7452          comp_unit_obstack.  But there's no data yet that we need this
7453          optimization.  */
7454       if (cu->dwo_unit != NULL)
7455         rereading_dwo_cu = 1;
7456     }
7457   else
7458     {
7459       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7460       gdb_assert (this_cu->cu == NULL);
7461       new_cu.reset (new dwarf2_cu (this_cu));
7462       cu = new_cu.get ();
7463     }
7464
7465   /* Get the header.  */
7466   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7467     {
7468       /* We already have the header, there's no need to read it in again.  */
7469       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7470     }
7471   else
7472     {
7473       if (this_cu->is_debug_types)
7474         {
7475           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7476                                                     &cu->header, section,
7477                                                     abbrev_section, info_ptr,
7478                                                     rcuh_kind::TYPE);
7479
7480           /* Since per_cu is the first member of struct signatured_type,
7481              we can go from a pointer to one to a pointer to the other.  */
7482           sig_type = (struct signatured_type *) this_cu;
7483           gdb_assert (sig_type->signature == cu->header.signature);
7484           gdb_assert (sig_type->type_offset_in_tu
7485                       == cu->header.type_cu_offset_in_tu);
7486           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7487
7488           /* LENGTH has not been set yet for type units if we're
7489              using .gdb_index.  */
7490           this_cu->length = get_cu_length (&cu->header);
7491
7492           /* Establish the type offset that can be used to lookup the type.  */
7493           sig_type->type_offset_in_section =
7494             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7495
7496           this_cu->dwarf_version = cu->header.version;
7497         }
7498       else
7499         {
7500           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7501                                                     &cu->header, section,
7502                                                     abbrev_section,
7503                                                     info_ptr,
7504                                                     rcuh_kind::COMPILE);
7505
7506           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7507           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7508           this_cu->dwarf_version = cu->header.version;
7509         }
7510     }
7511
7512   /* Skip dummy compilation units.  */
7513   if (info_ptr >= begin_info_ptr + this_cu->length
7514       || peek_abbrev_code (abfd, info_ptr) == 0)
7515     return;
7516
7517   /* If we don't have them yet, read the abbrevs for this compilation unit.
7518      And if we need to read them now, make sure they're freed when we're
7519      done (own the table through ABBREV_TABLE_HOLDER).  */
7520   abbrev_table_up abbrev_table_holder;
7521   if (abbrev_table != NULL)
7522     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7523   else
7524     {
7525       abbrev_table_holder
7526         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7527                                    cu->header.abbrev_sect_off);
7528       abbrev_table = abbrev_table_holder.get ();
7529     }
7530
7531   /* Read the top level CU/TU die.  */
7532   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7533   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7534
7535   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7536     return;
7537
7538   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7539      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7540      table from the DWO file and pass the ownership over to us.  It will be
7541      referenced from READER, so we must make sure to free it after we're done
7542      with READER.
7543
7544      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7545      DWO CU, that this test will fail (the attribute will not be present).  */
7546   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7547   abbrev_table_up dwo_abbrev_table;
7548   if (attr)
7549     {
7550       struct dwo_unit *dwo_unit;
7551       struct die_info *dwo_comp_unit_die;
7552
7553       if (has_children)
7554         {
7555           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7556                        " has children (offset %s) [in module %s]"),
7557                      sect_offset_str (this_cu->sect_off),
7558                      bfd_get_filename (abfd));
7559         }
7560       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7561       if (dwo_unit != NULL)
7562         {
7563           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7564                                       comp_unit_die, NULL,
7565                                       &reader, &info_ptr,
7566                                       &dwo_comp_unit_die, &has_children,
7567                                       &dwo_abbrev_table) == 0)
7568             {
7569               /* Dummy die.  */
7570               return;
7571             }
7572           comp_unit_die = dwo_comp_unit_die;
7573         }
7574       else
7575         {
7576           /* Yikes, we couldn't find the rest of the DIE, we only have
7577              the stub.  A complaint has already been logged.  There's
7578              not much more we can do except pass on the stub DIE to
7579              die_reader_func.  We don't want to throw an error on bad
7580              debug info.  */
7581         }
7582     }
7583
7584   /* All of the above is setup for this call.  Yikes.  */
7585   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7586
7587   /* Done, clean up.  */
7588   if (new_cu != NULL && keep)
7589     {
7590       /* Link this CU into read_in_chain.  */
7591       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7592       dwarf2_per_objfile->read_in_chain = this_cu;
7593       /* The chain owns it now.  */
7594       new_cu.release ();
7595     }
7596 }
7597
7598 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7599    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7600    to have already done the lookup to find the DWO file).
7601
7602    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7603    THIS_CU->is_debug_types, but nothing else.
7604
7605    We fill in THIS_CU->length.
7606
7607    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7608    linker) then DIE_READER_FUNC will not get called.
7609
7610    THIS_CU->cu is always freed when done.
7611    This is done in order to not leave THIS_CU->cu in a state where we have
7612    to care whether it refers to the "main" CU or the DWO CU.  */
7613
7614 static void
7615 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7616                                    struct dwo_file *dwo_file,
7617                                    die_reader_func_ftype *die_reader_func,
7618                                    void *data)
7619 {
7620   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7621   struct objfile *objfile = dwarf2_per_objfile->objfile;
7622   struct dwarf2_section_info *section = this_cu->section;
7623   bfd *abfd = get_section_bfd_owner (section);
7624   struct dwarf2_section_info *abbrev_section;
7625   const gdb_byte *begin_info_ptr, *info_ptr;
7626   struct die_reader_specs reader;
7627   struct die_info *comp_unit_die;
7628   int has_children;
7629
7630   if (dwarf_die_debug)
7631     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7632                         this_cu->is_debug_types ? "type" : "comp",
7633                         sect_offset_str (this_cu->sect_off));
7634
7635   gdb_assert (this_cu->cu == NULL);
7636
7637   abbrev_section = (dwo_file != NULL
7638                     ? &dwo_file->sections.abbrev
7639                     : get_abbrev_section_for_cu (this_cu));
7640
7641   /* This is cheap if the section is already read in.  */
7642   dwarf2_read_section (objfile, section);
7643
7644   struct dwarf2_cu cu (this_cu);
7645
7646   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7647   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7648                                             &cu.header, section,
7649                                             abbrev_section, info_ptr,
7650                                             (this_cu->is_debug_types
7651                                              ? rcuh_kind::TYPE
7652                                              : rcuh_kind::COMPILE));
7653
7654   this_cu->length = get_cu_length (&cu.header);
7655
7656   /* Skip dummy compilation units.  */
7657   if (info_ptr >= begin_info_ptr + this_cu->length
7658       || peek_abbrev_code (abfd, info_ptr) == 0)
7659     return;
7660
7661   abbrev_table_up abbrev_table
7662     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7663                                cu.header.abbrev_sect_off);
7664
7665   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7666   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7667
7668   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7669 }
7670
7671 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7672    does not lookup the specified DWO file.
7673    This cannot be used to read DWO files.
7674
7675    THIS_CU->cu is always freed when done.
7676    This is done in order to not leave THIS_CU->cu in a state where we have
7677    to care whether it refers to the "main" CU or the DWO CU.
7678    We can revisit this if the data shows there's a performance issue.  */
7679
7680 static void
7681 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7682                                 die_reader_func_ftype *die_reader_func,
7683                                 void *data)
7684 {
7685   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7686 }
7687 \f
7688 /* Type Unit Groups.
7689
7690    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7691    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7692    so that all types coming from the same compilation (.o file) are grouped
7693    together.  A future step could be to put the types in the same symtab as
7694    the CU the types ultimately came from.  */
7695
7696 static hashval_t
7697 hash_type_unit_group (const void *item)
7698 {
7699   const struct type_unit_group *tu_group
7700     = (const struct type_unit_group *) item;
7701
7702   return hash_stmt_list_entry (&tu_group->hash);
7703 }
7704
7705 static int
7706 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7707 {
7708   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7709   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7710
7711   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7712 }
7713
7714 /* Allocate a hash table for type unit groups.  */
7715
7716 static htab_t
7717 allocate_type_unit_groups_table (struct objfile *objfile)
7718 {
7719   return htab_create_alloc_ex (3,
7720                                hash_type_unit_group,
7721                                eq_type_unit_group,
7722                                NULL,
7723                                &objfile->objfile_obstack,
7724                                hashtab_obstack_allocate,
7725                                dummy_obstack_deallocate);
7726 }
7727
7728 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7729    partial symtabs.  We combine several TUs per psymtab to not let the size
7730    of any one psymtab grow too big.  */
7731 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7732 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7733
7734 /* Helper routine for get_type_unit_group.
7735    Create the type_unit_group object used to hold one or more TUs.  */
7736
7737 static struct type_unit_group *
7738 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7739 {
7740   struct dwarf2_per_objfile *dwarf2_per_objfile
7741     = cu->per_cu->dwarf2_per_objfile;
7742   struct objfile *objfile = dwarf2_per_objfile->objfile;
7743   struct dwarf2_per_cu_data *per_cu;
7744   struct type_unit_group *tu_group;
7745
7746   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7747                              struct type_unit_group);
7748   per_cu = &tu_group->per_cu;
7749   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7750
7751   if (dwarf2_per_objfile->using_index)
7752     {
7753       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7754                                         struct dwarf2_per_cu_quick_data);
7755     }
7756   else
7757     {
7758       unsigned int line_offset = to_underlying (line_offset_struct);
7759       struct partial_symtab *pst;
7760       std::string name;
7761
7762       /* Give the symtab a useful name for debug purposes.  */
7763       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7764         name = string_printf ("<type_units_%d>",
7765                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7766       else
7767         name = string_printf ("<type_units_at_0x%x>", line_offset);
7768
7769       pst = create_partial_symtab (per_cu, name.c_str ());
7770       pst->anonymous = 1;
7771     }
7772
7773   tu_group->hash.dwo_unit = cu->dwo_unit;
7774   tu_group->hash.line_sect_off = line_offset_struct;
7775
7776   return tu_group;
7777 }
7778
7779 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7780    STMT_LIST is a DW_AT_stmt_list attribute.  */
7781
7782 static struct type_unit_group *
7783 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7784 {
7785   struct dwarf2_per_objfile *dwarf2_per_objfile
7786     = cu->per_cu->dwarf2_per_objfile;
7787   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7788   struct type_unit_group *tu_group;
7789   void **slot;
7790   unsigned int line_offset;
7791   struct type_unit_group type_unit_group_for_lookup;
7792
7793   if (dwarf2_per_objfile->type_unit_groups == NULL)
7794     {
7795       dwarf2_per_objfile->type_unit_groups =
7796         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7797     }
7798
7799   /* Do we need to create a new group, or can we use an existing one?  */
7800
7801   if (stmt_list)
7802     {
7803       line_offset = DW_UNSND (stmt_list);
7804       ++tu_stats->nr_symtab_sharers;
7805     }
7806   else
7807     {
7808       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7809          We can do various things here like create one group per TU or
7810          spread them over multiple groups to split up the expansion work.
7811          To avoid worst case scenarios (too many groups or too large groups)
7812          we, umm, group them in bunches.  */
7813       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7814                      | (tu_stats->nr_stmt_less_type_units
7815                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7816       ++tu_stats->nr_stmt_less_type_units;
7817     }
7818
7819   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7820   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7821   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7822                          &type_unit_group_for_lookup, INSERT);
7823   if (*slot != NULL)
7824     {
7825       tu_group = (struct type_unit_group *) *slot;
7826       gdb_assert (tu_group != NULL);
7827     }
7828   else
7829     {
7830       sect_offset line_offset_struct = (sect_offset) line_offset;
7831       tu_group = create_type_unit_group (cu, line_offset_struct);
7832       *slot = tu_group;
7833       ++tu_stats->nr_symtabs;
7834     }
7835
7836   return tu_group;
7837 }
7838 \f
7839 /* Partial symbol tables.  */
7840
7841 /* Create a psymtab named NAME and assign it to PER_CU.
7842
7843    The caller must fill in the following details:
7844    dirname, textlow, texthigh.  */
7845
7846 static struct partial_symtab *
7847 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7848 {
7849   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7850   struct partial_symtab *pst;
7851
7852   pst = start_psymtab_common (objfile, name, 0,
7853                               objfile->global_psymbols,
7854                               objfile->static_psymbols);
7855
7856   pst->psymtabs_addrmap_supported = 1;
7857
7858   /* This is the glue that links PST into GDB's symbol API.  */
7859   pst->read_symtab_private = per_cu;
7860   pst->read_symtab = dwarf2_read_symtab;
7861   per_cu->v.psymtab = pst;
7862
7863   return pst;
7864 }
7865
7866 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7867    type.  */
7868
7869 struct process_psymtab_comp_unit_data
7870 {
7871   /* True if we are reading a DW_TAG_partial_unit.  */
7872
7873   int want_partial_unit;
7874
7875   /* The "pretend" language that is used if the CU doesn't declare a
7876      language.  */
7877
7878   enum language pretend_language;
7879 };
7880
7881 /* die_reader_func for process_psymtab_comp_unit.  */
7882
7883 static void
7884 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7885                                   const gdb_byte *info_ptr,
7886                                   struct die_info *comp_unit_die,
7887                                   int has_children,
7888                                   void *data)
7889 {
7890   struct dwarf2_cu *cu = reader->cu;
7891   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7892   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7893   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7894   CORE_ADDR baseaddr;
7895   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7896   struct partial_symtab *pst;
7897   enum pc_bounds_kind cu_bounds_kind;
7898   const char *filename;
7899   struct process_psymtab_comp_unit_data *info
7900     = (struct process_psymtab_comp_unit_data *) data;
7901
7902   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7903     return;
7904
7905   gdb_assert (! per_cu->is_debug_types);
7906
7907   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7908
7909   /* Allocate a new partial symbol table structure.  */
7910   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7911   if (filename == NULL)
7912     filename = "";
7913
7914   pst = create_partial_symtab (per_cu, filename);
7915
7916   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7917   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7918
7919   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7920
7921   dwarf2_find_base_address (comp_unit_die, cu);
7922
7923   /* Possibly set the default values of LOWPC and HIGHPC from
7924      `DW_AT_ranges'.  */
7925   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7926                                          &best_highpc, cu, pst);
7927   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7928     {
7929       CORE_ADDR low
7930         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
7931            - baseaddr);
7932       CORE_ADDR high
7933         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
7934            - baseaddr - 1);
7935       /* Store the contiguous range if it is not empty; it can be
7936          empty for CUs with no code.  */
7937       addrmap_set_empty (objfile->psymtabs_addrmap, low, high, pst);
7938     }
7939
7940   /* Check if comp unit has_children.
7941      If so, read the rest of the partial symbols from this comp unit.
7942      If not, there's no more debug_info for this comp unit.  */
7943   if (has_children)
7944     {
7945       struct partial_die_info *first_die;
7946       CORE_ADDR lowpc, highpc;
7947
7948       lowpc = ((CORE_ADDR) -1);
7949       highpc = ((CORE_ADDR) 0);
7950
7951       first_die = load_partial_dies (reader, info_ptr, 1);
7952
7953       scan_partial_symbols (first_die, &lowpc, &highpc,
7954                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7955
7956       /* If we didn't find a lowpc, set it to highpc to avoid
7957          complaints from `maint check'.  */
7958       if (lowpc == ((CORE_ADDR) -1))
7959         lowpc = highpc;
7960
7961       /* If the compilation unit didn't have an explicit address range,
7962          then use the information extracted from its child dies.  */
7963       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7964         {
7965           best_lowpc = lowpc;
7966           best_highpc = highpc;
7967         }
7968     }
7969   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
7970                                                  best_lowpc + baseaddr)
7971                      - baseaddr);
7972   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
7973                                                   best_highpc + baseaddr)
7974                       - 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->text_low (objfile)),
8012                           paddress (gdbarch, pst->text_high (objfile)),
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               - baseaddr);
8807       if (pdi->is_external || cu->language == language_ada)
8808         {
8809           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8810              of the global scope.  But in Ada, we want to be able to access
8811              nested procedures globally.  So all Ada subprograms are stored
8812              in the global scope.  */
8813           add_psymbol_to_list (actual_name, strlen (actual_name),
8814                                built_actual_name != NULL,
8815                                VAR_DOMAIN, LOC_BLOCK,
8816                                SECT_OFF_TEXT (objfile),
8817                                &objfile->global_psymbols,
8818                                addr,
8819                                cu->language, objfile);
8820         }
8821       else
8822         {
8823           add_psymbol_to_list (actual_name, strlen (actual_name),
8824                                built_actual_name != NULL,
8825                                VAR_DOMAIN, LOC_BLOCK,
8826                                SECT_OFF_TEXT (objfile),
8827                                &objfile->static_psymbols,
8828                                addr, cu->language, objfile);
8829         }
8830
8831       if (pdi->main_subprogram && actual_name != NULL)
8832         set_objfile_main_name (objfile, actual_name, cu->language);
8833       break;
8834     case DW_TAG_constant:
8835       {
8836         std::vector<partial_symbol *> *list;
8837
8838         if (pdi->is_external)
8839           list = &objfile->global_psymbols;
8840         else
8841           list = &objfile->static_psymbols;
8842         add_psymbol_to_list (actual_name, strlen (actual_name),
8843                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8844                              -1, list, 0, cu->language, objfile);
8845       }
8846       break;
8847     case DW_TAG_variable:
8848       if (pdi->d.locdesc)
8849         addr = decode_locdesc (pdi->d.locdesc, cu);
8850
8851       if (pdi->d.locdesc
8852           && addr == 0
8853           && !dwarf2_per_objfile->has_section_at_zero)
8854         {
8855           /* A global or static variable may also have been stripped
8856              out by the linker if unused, in which case its address
8857              will be nullified; do not add such variables into partial
8858              symbol table then.  */
8859         }
8860       else if (pdi->is_external)
8861         {
8862           /* Global Variable.
8863              Don't enter into the minimal symbol tables as there is
8864              a minimal symbol table entry from the ELF symbols already.
8865              Enter into partial symbol table if it has a location
8866              descriptor or a type.
8867              If the location descriptor is missing, new_symbol will create
8868              a LOC_UNRESOLVED symbol, the address of the variable will then
8869              be determined from the minimal symbol table whenever the variable
8870              is referenced.
8871              The address for the partial symbol table entry is not
8872              used by GDB, but it comes in handy for debugging partial symbol
8873              table building.  */
8874
8875           if (pdi->d.locdesc || pdi->has_type)
8876             add_psymbol_to_list (actual_name, strlen (actual_name),
8877                                  built_actual_name != NULL,
8878                                  VAR_DOMAIN, LOC_STATIC,
8879                                  SECT_OFF_TEXT (objfile),
8880                                  &objfile->global_psymbols,
8881                                  addr, cu->language, objfile);
8882         }
8883       else
8884         {
8885           int has_loc = pdi->d.locdesc != NULL;
8886
8887           /* Static Variable.  Skip symbols whose value we cannot know (those
8888              without location descriptors or constant values).  */
8889           if (!has_loc && !pdi->has_const_value)
8890             {
8891               xfree (built_actual_name);
8892               return;
8893             }
8894
8895           add_psymbol_to_list (actual_name, strlen (actual_name),
8896                                built_actual_name != NULL,
8897                                VAR_DOMAIN, LOC_STATIC,
8898                                SECT_OFF_TEXT (objfile),
8899                                &objfile->static_psymbols,
8900                                has_loc ? addr : 0,
8901                                cu->language, objfile);
8902         }
8903       break;
8904     case DW_TAG_typedef:
8905     case DW_TAG_base_type:
8906     case DW_TAG_subrange_type:
8907       add_psymbol_to_list (actual_name, strlen (actual_name),
8908                            built_actual_name != NULL,
8909                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8910                            &objfile->static_psymbols,
8911                            0, cu->language, objfile);
8912       break;
8913     case DW_TAG_imported_declaration:
8914     case DW_TAG_namespace:
8915       add_psymbol_to_list (actual_name, strlen (actual_name),
8916                            built_actual_name != NULL,
8917                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8918                            &objfile->global_psymbols,
8919                            0, cu->language, objfile);
8920       break;
8921     case DW_TAG_module:
8922       add_psymbol_to_list (actual_name, strlen (actual_name),
8923                            built_actual_name != NULL,
8924                            MODULE_DOMAIN, LOC_TYPEDEF, -1,
8925                            &objfile->global_psymbols,
8926                            0, cu->language, objfile);
8927       break;
8928     case DW_TAG_class_type:
8929     case DW_TAG_interface_type:
8930     case DW_TAG_structure_type:
8931     case DW_TAG_union_type:
8932     case DW_TAG_enumeration_type:
8933       /* Skip external references.  The DWARF standard says in the section
8934          about "Structure, Union, and Class Type Entries": "An incomplete
8935          structure, union or class type is represented by a structure,
8936          union or class entry that does not have a byte size attribute
8937          and that has a DW_AT_declaration attribute."  */
8938       if (!pdi->has_byte_size && pdi->is_declaration)
8939         {
8940           xfree (built_actual_name);
8941           return;
8942         }
8943
8944       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8945          static vs. global.  */
8946       add_psymbol_to_list (actual_name, strlen (actual_name),
8947                            built_actual_name != NULL,
8948                            STRUCT_DOMAIN, LOC_TYPEDEF, -1,
8949                            cu->language == language_cplus
8950                            ? &objfile->global_psymbols
8951                            : &objfile->static_psymbols,
8952                            0, cu->language, objfile);
8953
8954       break;
8955     case DW_TAG_enumerator:
8956       add_psymbol_to_list (actual_name, strlen (actual_name),
8957                            built_actual_name != NULL,
8958                            VAR_DOMAIN, LOC_CONST, -1,
8959                            cu->language == language_cplus
8960                            ? &objfile->global_psymbols
8961                            : &objfile->static_psymbols,
8962                            0, cu->language, objfile);
8963       break;
8964     default:
8965       break;
8966     }
8967
8968   xfree (built_actual_name);
8969 }
8970
8971 /* Read a partial die corresponding to a namespace; also, add a symbol
8972    corresponding to that namespace to the symbol table.  NAMESPACE is
8973    the name of the enclosing namespace.  */
8974
8975 static void
8976 add_partial_namespace (struct partial_die_info *pdi,
8977                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8978                        int set_addrmap, struct dwarf2_cu *cu)
8979 {
8980   /* Add a symbol for the namespace.  */
8981
8982   add_partial_symbol (pdi, cu);
8983
8984   /* Now scan partial symbols in that namespace.  */
8985
8986   if (pdi->has_children)
8987     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8988 }
8989
8990 /* Read a partial die corresponding to a Fortran module.  */
8991
8992 static void
8993 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8994                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8995 {
8996   /* Add a symbol for the namespace.  */
8997
8998   add_partial_symbol (pdi, cu);
8999
9000   /* Now scan partial symbols in that module.  */
9001
9002   if (pdi->has_children)
9003     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9004 }
9005
9006 /* Read a partial die corresponding to a subprogram or an inlined
9007    subprogram and create a partial symbol for that subprogram.
9008    When the CU language allows it, this routine also defines a partial
9009    symbol for each nested subprogram that this subprogram contains.
9010    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9011    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9012
9013    PDI may also be a lexical block, in which case we simply search
9014    recursively for subprograms defined inside that lexical block.
9015    Again, this is only performed when the CU language allows this
9016    type of definitions.  */
9017
9018 static void
9019 add_partial_subprogram (struct partial_die_info *pdi,
9020                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9021                         int set_addrmap, struct dwarf2_cu *cu)
9022 {
9023   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9024     {
9025       if (pdi->has_pc_info)
9026         {
9027           if (pdi->lowpc < *lowpc)
9028             *lowpc = pdi->lowpc;
9029           if (pdi->highpc > *highpc)
9030             *highpc = pdi->highpc;
9031           if (set_addrmap)
9032             {
9033               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9034               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9035               CORE_ADDR baseaddr;
9036               CORE_ADDR highpc;
9037               CORE_ADDR lowpc;
9038
9039               baseaddr = ANOFFSET (objfile->section_offsets,
9040                                    SECT_OFF_TEXT (objfile));
9041               lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
9042                                                    pdi->lowpc + baseaddr)
9043                        - baseaddr);
9044               highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
9045                                                     pdi->highpc + baseaddr)
9046                         - baseaddr);
9047               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9048                                  cu->per_cu->v.psymtab);
9049             }
9050         }
9051
9052       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9053         {
9054           if (!pdi->is_declaration)
9055             /* Ignore subprogram DIEs that do not have a name, they are
9056                illegal.  Do not emit a complaint at this point, we will
9057                do so when we convert this psymtab into a symtab.  */
9058             if (pdi->name)
9059               add_partial_symbol (pdi, cu);
9060         }
9061     }
9062
9063   if (! pdi->has_children)
9064     return;
9065
9066   if (cu->language == language_ada)
9067     {
9068       pdi = pdi->die_child;
9069       while (pdi != NULL)
9070         {
9071           pdi->fixup (cu);
9072           if (pdi->tag == DW_TAG_subprogram
9073               || pdi->tag == DW_TAG_inlined_subroutine
9074               || pdi->tag == DW_TAG_lexical_block)
9075             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9076           pdi = pdi->die_sibling;
9077         }
9078     }
9079 }
9080
9081 /* Read a partial die corresponding to an enumeration type.  */
9082
9083 static void
9084 add_partial_enumeration (struct partial_die_info *enum_pdi,
9085                          struct dwarf2_cu *cu)
9086 {
9087   struct partial_die_info *pdi;
9088
9089   if (enum_pdi->name != NULL)
9090     add_partial_symbol (enum_pdi, cu);
9091
9092   pdi = enum_pdi->die_child;
9093   while (pdi)
9094     {
9095       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9096         complaint (_("malformed enumerator DIE ignored"));
9097       else
9098         add_partial_symbol (pdi, cu);
9099       pdi = pdi->die_sibling;
9100     }
9101 }
9102
9103 /* Return the initial uleb128 in the die at INFO_PTR.  */
9104
9105 static unsigned int
9106 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9107 {
9108   unsigned int bytes_read;
9109
9110   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9111 }
9112
9113 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9114    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9115
9116    Return the corresponding abbrev, or NULL if the number is zero (indicating
9117    an empty DIE).  In either case *BYTES_READ will be set to the length of
9118    the initial number.  */
9119
9120 static struct abbrev_info *
9121 peek_die_abbrev (const die_reader_specs &reader,
9122                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9123 {
9124   dwarf2_cu *cu = reader.cu;
9125   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9126   unsigned int abbrev_number
9127     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9128
9129   if (abbrev_number == 0)
9130     return NULL;
9131
9132   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9133   if (!abbrev)
9134     {
9135       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9136                " at offset %s [in module %s]"),
9137              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9138              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9139     }
9140
9141   return abbrev;
9142 }
9143
9144 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9145    Returns a pointer to the end of a series of DIEs, terminated by an empty
9146    DIE.  Any children of the skipped DIEs will also be skipped.  */
9147
9148 static const gdb_byte *
9149 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9150 {
9151   while (1)
9152     {
9153       unsigned int bytes_read;
9154       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9155
9156       if (abbrev == NULL)
9157         return info_ptr + bytes_read;
9158       else
9159         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9160     }
9161 }
9162
9163 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9164    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9165    abbrev corresponding to that skipped uleb128 should be passed in
9166    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9167    children.  */
9168
9169 static const gdb_byte *
9170 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9171               struct abbrev_info *abbrev)
9172 {
9173   unsigned int bytes_read;
9174   struct attribute attr;
9175   bfd *abfd = reader->abfd;
9176   struct dwarf2_cu *cu = reader->cu;
9177   const gdb_byte *buffer = reader->buffer;
9178   const gdb_byte *buffer_end = reader->buffer_end;
9179   unsigned int form, i;
9180
9181   for (i = 0; i < abbrev->num_attrs; i++)
9182     {
9183       /* The only abbrev we care about is DW_AT_sibling.  */
9184       if (abbrev->attrs[i].name == DW_AT_sibling)
9185         {
9186           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9187           if (attr.form == DW_FORM_ref_addr)
9188             complaint (_("ignoring absolute DW_AT_sibling"));
9189           else
9190             {
9191               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9192               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9193
9194               if (sibling_ptr < info_ptr)
9195                 complaint (_("DW_AT_sibling points backwards"));
9196               else if (sibling_ptr > reader->buffer_end)
9197                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9198               else
9199                 return sibling_ptr;
9200             }
9201         }
9202
9203       /* If it isn't DW_AT_sibling, skip this attribute.  */
9204       form = abbrev->attrs[i].form;
9205     skip_attribute:
9206       switch (form)
9207         {
9208         case DW_FORM_ref_addr:
9209           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9210              and later it is offset sized.  */
9211           if (cu->header.version == 2)
9212             info_ptr += cu->header.addr_size;
9213           else
9214             info_ptr += cu->header.offset_size;
9215           break;
9216         case DW_FORM_GNU_ref_alt:
9217           info_ptr += cu->header.offset_size;
9218           break;
9219         case DW_FORM_addr:
9220           info_ptr += cu->header.addr_size;
9221           break;
9222         case DW_FORM_data1:
9223         case DW_FORM_ref1:
9224         case DW_FORM_flag:
9225           info_ptr += 1;
9226           break;
9227         case DW_FORM_flag_present:
9228         case DW_FORM_implicit_const:
9229           break;
9230         case DW_FORM_data2:
9231         case DW_FORM_ref2:
9232           info_ptr += 2;
9233           break;
9234         case DW_FORM_data4:
9235         case DW_FORM_ref4:
9236           info_ptr += 4;
9237           break;
9238         case DW_FORM_data8:
9239         case DW_FORM_ref8:
9240         case DW_FORM_ref_sig8:
9241           info_ptr += 8;
9242           break;
9243         case DW_FORM_data16:
9244           info_ptr += 16;
9245           break;
9246         case DW_FORM_string:
9247           read_direct_string (abfd, info_ptr, &bytes_read);
9248           info_ptr += bytes_read;
9249           break;
9250         case DW_FORM_sec_offset:
9251         case DW_FORM_strp:
9252         case DW_FORM_GNU_strp_alt:
9253           info_ptr += cu->header.offset_size;
9254           break;
9255         case DW_FORM_exprloc:
9256         case DW_FORM_block:
9257           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9258           info_ptr += bytes_read;
9259           break;
9260         case DW_FORM_block1:
9261           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9262           break;
9263         case DW_FORM_block2:
9264           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9265           break;
9266         case DW_FORM_block4:
9267           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9268           break;
9269         case DW_FORM_sdata:
9270         case DW_FORM_udata:
9271         case DW_FORM_ref_udata:
9272         case DW_FORM_GNU_addr_index:
9273         case DW_FORM_GNU_str_index:
9274           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9275           break;
9276         case DW_FORM_indirect:
9277           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9278           info_ptr += bytes_read;
9279           /* We need to continue parsing from here, so just go back to
9280              the top.  */
9281           goto skip_attribute;
9282
9283         default:
9284           error (_("Dwarf Error: Cannot handle %s "
9285                    "in DWARF reader [in module %s]"),
9286                  dwarf_form_name (form),
9287                  bfd_get_filename (abfd));
9288         }
9289     }
9290
9291   if (abbrev->has_children)
9292     return skip_children (reader, info_ptr);
9293   else
9294     return info_ptr;
9295 }
9296
9297 /* Locate ORIG_PDI's sibling.
9298    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9299
9300 static const gdb_byte *
9301 locate_pdi_sibling (const struct die_reader_specs *reader,
9302                     struct partial_die_info *orig_pdi,
9303                     const gdb_byte *info_ptr)
9304 {
9305   /* Do we know the sibling already?  */
9306
9307   if (orig_pdi->sibling)
9308     return orig_pdi->sibling;
9309
9310   /* Are there any children to deal with?  */
9311
9312   if (!orig_pdi->has_children)
9313     return info_ptr;
9314
9315   /* Skip the children the long way.  */
9316
9317   return skip_children (reader, info_ptr);
9318 }
9319
9320 /* Expand this partial symbol table into a full symbol table.  SELF is
9321    not NULL.  */
9322
9323 static void
9324 dwarf2_read_symtab (struct partial_symtab *self,
9325                     struct objfile *objfile)
9326 {
9327   struct dwarf2_per_objfile *dwarf2_per_objfile
9328     = get_dwarf2_per_objfile (objfile);
9329
9330   if (self->readin)
9331     {
9332       warning (_("bug: psymtab for %s is already read in."),
9333                self->filename);
9334     }
9335   else
9336     {
9337       if (info_verbose)
9338         {
9339           printf_filtered (_("Reading in symbols for %s..."),
9340                            self->filename);
9341           gdb_flush (gdb_stdout);
9342         }
9343
9344       /* If this psymtab is constructed from a debug-only objfile, the
9345          has_section_at_zero flag will not necessarily be correct.  We
9346          can get the correct value for this flag by looking at the data
9347          associated with the (presumably stripped) associated objfile.  */
9348       if (objfile->separate_debug_objfile_backlink)
9349         {
9350           struct dwarf2_per_objfile *dpo_backlink
9351             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9352
9353           dwarf2_per_objfile->has_section_at_zero
9354             = dpo_backlink->has_section_at_zero;
9355         }
9356
9357       dwarf2_per_objfile->reading_partial_symbols = 0;
9358
9359       psymtab_to_symtab_1 (self);
9360
9361       /* Finish up the debug error message.  */
9362       if (info_verbose)
9363         printf_filtered (_("done.\n"));
9364     }
9365
9366   process_cu_includes (dwarf2_per_objfile);
9367 }
9368 \f
9369 /* Reading in full CUs.  */
9370
9371 /* Add PER_CU to the queue.  */
9372
9373 static void
9374 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9375                  enum language pretend_language)
9376 {
9377   struct dwarf2_queue_item *item;
9378
9379   per_cu->queued = 1;
9380   item = XNEW (struct dwarf2_queue_item);
9381   item->per_cu = per_cu;
9382   item->pretend_language = pretend_language;
9383   item->next = NULL;
9384
9385   if (dwarf2_queue == NULL)
9386     dwarf2_queue = item;
9387   else
9388     dwarf2_queue_tail->next = item;
9389
9390   dwarf2_queue_tail = item;
9391 }
9392
9393 /* If PER_CU is not yet queued, add it to the queue.
9394    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9395    dependency.
9396    The result is non-zero if PER_CU was queued, otherwise the result is zero
9397    meaning either PER_CU is already queued or it is already loaded.
9398
9399    N.B. There is an invariant here that if a CU is queued then it is loaded.
9400    The caller is required to load PER_CU if we return non-zero.  */
9401
9402 static int
9403 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9404                        struct dwarf2_per_cu_data *per_cu,
9405                        enum language pretend_language)
9406 {
9407   /* We may arrive here during partial symbol reading, if we need full
9408      DIEs to process an unusual case (e.g. template arguments).  Do
9409      not queue PER_CU, just tell our caller to load its DIEs.  */
9410   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9411     {
9412       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9413         return 1;
9414       return 0;
9415     }
9416
9417   /* Mark the dependence relation so that we don't flush PER_CU
9418      too early.  */
9419   if (dependent_cu != NULL)
9420     dwarf2_add_dependence (dependent_cu, per_cu);
9421
9422   /* If it's already on the queue, we have nothing to do.  */
9423   if (per_cu->queued)
9424     return 0;
9425
9426   /* If the compilation unit is already loaded, just mark it as
9427      used.  */
9428   if (per_cu->cu != NULL)
9429     {
9430       per_cu->cu->last_used = 0;
9431       return 0;
9432     }
9433
9434   /* Add it to the queue.  */
9435   queue_comp_unit (per_cu, pretend_language);
9436
9437   return 1;
9438 }
9439
9440 /* Process the queue.  */
9441
9442 static void
9443 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9444 {
9445   struct dwarf2_queue_item *item, *next_item;
9446
9447   if (dwarf_read_debug)
9448     {
9449       fprintf_unfiltered (gdb_stdlog,
9450                           "Expanding one or more symtabs of objfile %s ...\n",
9451                           objfile_name (dwarf2_per_objfile->objfile));
9452     }
9453
9454   /* The queue starts out with one item, but following a DIE reference
9455      may load a new CU, adding it to the end of the queue.  */
9456   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9457     {
9458       if ((dwarf2_per_objfile->using_index
9459            ? !item->per_cu->v.quick->compunit_symtab
9460            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9461           /* Skip dummy CUs.  */
9462           && item->per_cu->cu != NULL)
9463         {
9464           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9465           unsigned int debug_print_threshold;
9466           char buf[100];
9467
9468           if (per_cu->is_debug_types)
9469             {
9470               struct signatured_type *sig_type =
9471                 (struct signatured_type *) per_cu;
9472
9473               sprintf (buf, "TU %s at offset %s",
9474                        hex_string (sig_type->signature),
9475                        sect_offset_str (per_cu->sect_off));
9476               /* There can be 100s of TUs.
9477                  Only print them in verbose mode.  */
9478               debug_print_threshold = 2;
9479             }
9480           else
9481             {
9482               sprintf (buf, "CU at offset %s",
9483                        sect_offset_str (per_cu->sect_off));
9484               debug_print_threshold = 1;
9485             }
9486
9487           if (dwarf_read_debug >= debug_print_threshold)
9488             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9489
9490           if (per_cu->is_debug_types)
9491             process_full_type_unit (per_cu, item->pretend_language);
9492           else
9493             process_full_comp_unit (per_cu, item->pretend_language);
9494
9495           if (dwarf_read_debug >= debug_print_threshold)
9496             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9497         }
9498
9499       item->per_cu->queued = 0;
9500       next_item = item->next;
9501       xfree (item);
9502     }
9503
9504   dwarf2_queue_tail = NULL;
9505
9506   if (dwarf_read_debug)
9507     {
9508       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9509                           objfile_name (dwarf2_per_objfile->objfile));
9510     }
9511 }
9512
9513 /* Read in full symbols for PST, and anything it depends on.  */
9514
9515 static void
9516 psymtab_to_symtab_1 (struct partial_symtab *pst)
9517 {
9518   struct dwarf2_per_cu_data *per_cu;
9519   int i;
9520
9521   if (pst->readin)
9522     return;
9523
9524   for (i = 0; i < pst->number_of_dependencies; i++)
9525     if (!pst->dependencies[i]->readin
9526         && pst->dependencies[i]->user == NULL)
9527       {
9528         /* Inform about additional files that need to be read in.  */
9529         if (info_verbose)
9530           {
9531             /* FIXME: i18n: Need to make this a single string.  */
9532             fputs_filtered (" ", gdb_stdout);
9533             wrap_here ("");
9534             fputs_filtered ("and ", gdb_stdout);
9535             wrap_here ("");
9536             printf_filtered ("%s...", pst->dependencies[i]->filename);
9537             wrap_here ("");     /* Flush output.  */
9538             gdb_flush (gdb_stdout);
9539           }
9540         psymtab_to_symtab_1 (pst->dependencies[i]);
9541       }
9542
9543   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9544
9545   if (per_cu == NULL)
9546     {
9547       /* It's an include file, no symbols to read for it.
9548          Everything is in the parent symtab.  */
9549       pst->readin = 1;
9550       return;
9551     }
9552
9553   dw2_do_instantiate_symtab (per_cu, false);
9554 }
9555
9556 /* Trivial hash function for die_info: the hash value of a DIE
9557    is its offset in .debug_info for this objfile.  */
9558
9559 static hashval_t
9560 die_hash (const void *item)
9561 {
9562   const struct die_info *die = (const struct die_info *) item;
9563
9564   return to_underlying (die->sect_off);
9565 }
9566
9567 /* Trivial comparison function for die_info structures: two DIEs
9568    are equal if they have the same offset.  */
9569
9570 static int
9571 die_eq (const void *item_lhs, const void *item_rhs)
9572 {
9573   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9574   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9575
9576   return die_lhs->sect_off == die_rhs->sect_off;
9577 }
9578
9579 /* die_reader_func for load_full_comp_unit.
9580    This is identical to read_signatured_type_reader,
9581    but is kept separate for now.  */
9582
9583 static void
9584 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9585                             const gdb_byte *info_ptr,
9586                             struct die_info *comp_unit_die,
9587                             int has_children,
9588                             void *data)
9589 {
9590   struct dwarf2_cu *cu = reader->cu;
9591   enum language *language_ptr = (enum language *) data;
9592
9593   gdb_assert (cu->die_hash == NULL);
9594   cu->die_hash =
9595     htab_create_alloc_ex (cu->header.length / 12,
9596                           die_hash,
9597                           die_eq,
9598                           NULL,
9599                           &cu->comp_unit_obstack,
9600                           hashtab_obstack_allocate,
9601                           dummy_obstack_deallocate);
9602
9603   if (has_children)
9604     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9605                                                   &info_ptr, comp_unit_die);
9606   cu->dies = comp_unit_die;
9607   /* comp_unit_die is not stored in die_hash, no need.  */
9608
9609   /* We try not to read any attributes in this function, because not
9610      all CUs needed for references have been loaded yet, and symbol
9611      table processing isn't initialized.  But we have to set the CU language,
9612      or we won't be able to build types correctly.
9613      Similarly, if we do not read the producer, we can not apply
9614      producer-specific interpretation.  */
9615   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9616 }
9617
9618 /* Load the DIEs associated with PER_CU into memory.  */
9619
9620 static void
9621 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9622                      bool skip_partial,
9623                      enum language pretend_language)
9624 {
9625   gdb_assert (! this_cu->is_debug_types);
9626
9627   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9628                            load_full_comp_unit_reader, &pretend_language);
9629 }
9630
9631 /* Add a DIE to the delayed physname list.  */
9632
9633 static void
9634 add_to_method_list (struct type *type, int fnfield_index, int index,
9635                     const char *name, struct die_info *die,
9636                     struct dwarf2_cu *cu)
9637 {
9638   struct delayed_method_info mi;
9639   mi.type = type;
9640   mi.fnfield_index = fnfield_index;
9641   mi.index = index;
9642   mi.name = name;
9643   mi.die = die;
9644   cu->method_list.push_back (mi);
9645 }
9646
9647 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9648    "const" / "volatile".  If so, decrements LEN by the length of the
9649    modifier and return true.  Otherwise return false.  */
9650
9651 template<size_t N>
9652 static bool
9653 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9654 {
9655   size_t mod_len = sizeof (mod) - 1;
9656   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9657     {
9658       len -= mod_len;
9659       return true;
9660     }
9661   return false;
9662 }
9663
9664 /* Compute the physnames of any methods on the CU's method list.
9665
9666    The computation of method physnames is delayed in order to avoid the
9667    (bad) condition that one of the method's formal parameters is of an as yet
9668    incomplete type.  */
9669
9670 static void
9671 compute_delayed_physnames (struct dwarf2_cu *cu)
9672 {
9673   /* Only C++ delays computing physnames.  */
9674   if (cu->method_list.empty ())
9675     return;
9676   gdb_assert (cu->language == language_cplus);
9677
9678   for (const delayed_method_info &mi : cu->method_list)
9679     {
9680       const char *physname;
9681       struct fn_fieldlist *fn_flp
9682         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9683       physname = dwarf2_physname (mi.name, mi.die, cu);
9684       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9685         = physname ? physname : "";
9686
9687       /* Since there's no tag to indicate whether a method is a
9688          const/volatile overload, extract that information out of the
9689          demangled name.  */
9690       if (physname != NULL)
9691         {
9692           size_t len = strlen (physname);
9693
9694           while (1)
9695             {
9696               if (physname[len] == ')') /* shortcut */
9697                 break;
9698               else if (check_modifier (physname, len, " const"))
9699                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9700               else if (check_modifier (physname, len, " volatile"))
9701                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9702               else
9703                 break;
9704             }
9705         }
9706     }
9707
9708   /* The list is no longer needed.  */
9709   cu->method_list.clear ();
9710 }
9711
9712 /* A wrapper for add_symbol_to_list to ensure that SYMBOL's language is
9713    the same as all other symbols in LISTHEAD.  If a new symbol is added
9714    with a different language, this function asserts.  */
9715
9716 static inline void
9717 dw2_add_symbol_to_list (struct symbol *symbol, struct pending **listhead)
9718 {
9719   /* Only assert if LISTHEAD already contains symbols of a different
9720      language (dict_create_hashed/insert_symbol_hashed requires that all
9721      symbols in this list are of the same language).  */
9722   gdb_assert ((*listhead) == NULL
9723               || (SYMBOL_LANGUAGE ((*listhead)->symbol[0])
9724                   == SYMBOL_LANGUAGE (symbol)));
9725
9726   add_symbol_to_list (symbol, listhead);
9727 }
9728
9729 /* Go objects should be embedded in a DW_TAG_module DIE,
9730    and it's not clear if/how imported objects will appear.
9731    To keep Go support simple until that's worked out,
9732    go back through what we've read and create something usable.
9733    We could do this while processing each DIE, and feels kinda cleaner,
9734    but that way is more invasive.
9735    This is to, for example, allow the user to type "p var" or "b main"
9736    without having to specify the package name, and allow lookups
9737    of module.object to work in contexts that use the expression
9738    parser.  */
9739
9740 static void
9741 fixup_go_packaging (struct dwarf2_cu *cu)
9742 {
9743   char *package_name = NULL;
9744   struct pending *list;
9745   int i;
9746
9747   for (list = *cu->builder->get_global_symbols ();
9748        list != NULL;
9749        list = list->next)
9750     {
9751       for (i = 0; i < list->nsyms; ++i)
9752         {
9753           struct symbol *sym = list->symbol[i];
9754
9755           if (SYMBOL_LANGUAGE (sym) == language_go
9756               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9757             {
9758               char *this_package_name = go_symbol_package_name (sym);
9759
9760               if (this_package_name == NULL)
9761                 continue;
9762               if (package_name == NULL)
9763                 package_name = this_package_name;
9764               else
9765                 {
9766                   struct objfile *objfile
9767                     = cu->per_cu->dwarf2_per_objfile->objfile;
9768                   if (strcmp (package_name, this_package_name) != 0)
9769                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9770                                (symbol_symtab (sym) != NULL
9771                                 ? symtab_to_filename_for_display
9772                                     (symbol_symtab (sym))
9773                                 : objfile_name (objfile)),
9774                                this_package_name, package_name);
9775                   xfree (this_package_name);
9776                 }
9777             }
9778         }
9779     }
9780
9781   if (package_name != NULL)
9782     {
9783       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9784       const char *saved_package_name
9785         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9786                                         package_name,
9787                                         strlen (package_name));
9788       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9789                                      saved_package_name);
9790       struct symbol *sym;
9791
9792       sym = allocate_symbol (objfile);
9793       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9794       SYMBOL_SET_NAMES (sym, saved_package_name,
9795                         strlen (saved_package_name), 0, objfile);
9796       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9797          e.g., "main" finds the "main" module and not C's main().  */
9798       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9799       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9800       SYMBOL_TYPE (sym) = type;
9801
9802       dw2_add_symbol_to_list (sym, cu->builder->get_global_symbols ());
9803
9804       xfree (package_name);
9805     }
9806 }
9807
9808 /* Allocate a fully-qualified name consisting of the two parts on the
9809    obstack.  */
9810
9811 static const char *
9812 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9813 {
9814   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9815 }
9816
9817 /* A helper that allocates a struct discriminant_info to attach to a
9818    union type.  */
9819
9820 static struct discriminant_info *
9821 alloc_discriminant_info (struct type *type, int discriminant_index,
9822                          int default_index)
9823 {
9824   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9825   gdb_assert (discriminant_index == -1
9826               || (discriminant_index >= 0
9827                   && discriminant_index < TYPE_NFIELDS (type)));
9828   gdb_assert (default_index == -1
9829               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9830
9831   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9832
9833   struct discriminant_info *disc
9834     = ((struct discriminant_info *)
9835        TYPE_ZALLOC (type,
9836                     offsetof (struct discriminant_info, discriminants)
9837                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9838   disc->default_index = default_index;
9839   disc->discriminant_index = discriminant_index;
9840
9841   struct dynamic_prop prop;
9842   prop.kind = PROP_UNDEFINED;
9843   prop.data.baton = disc;
9844
9845   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9846
9847   return disc;
9848 }
9849
9850 /* Some versions of rustc emitted enums in an unusual way.
9851
9852    Ordinary enums were emitted as unions.  The first element of each
9853    structure in the union was named "RUST$ENUM$DISR".  This element
9854    held the discriminant.
9855
9856    These versions of Rust also implemented the "non-zero"
9857    optimization.  When the enum had two values, and one is empty and
9858    the other holds a pointer that cannot be zero, the pointer is used
9859    as the discriminant, with a zero value meaning the empty variant.
9860    Here, the union's first member is of the form
9861    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9862    where the fieldnos are the indices of the fields that should be
9863    traversed in order to find the field (which may be several fields deep)
9864    and the variantname is the name of the variant of the case when the
9865    field is zero.
9866
9867    This function recognizes whether TYPE is of one of these forms,
9868    and, if so, smashes it to be a variant type.  */
9869
9870 static void
9871 quirk_rust_enum (struct type *type, struct objfile *objfile)
9872 {
9873   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9874
9875   /* We don't need to deal with empty enums.  */
9876   if (TYPE_NFIELDS (type) == 0)
9877     return;
9878
9879 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9880   if (TYPE_NFIELDS (type) == 1
9881       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9882     {
9883       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9884
9885       /* Decode the field name to find the offset of the
9886          discriminant.  */
9887       ULONGEST bit_offset = 0;
9888       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9889       while (name[0] >= '0' && name[0] <= '9')
9890         {
9891           char *tail;
9892           unsigned long index = strtoul (name, &tail, 10);
9893           name = tail;
9894           if (*name != '$'
9895               || index >= TYPE_NFIELDS (field_type)
9896               || (TYPE_FIELD_LOC_KIND (field_type, index)
9897                   != FIELD_LOC_KIND_BITPOS))
9898             {
9899               complaint (_("Could not parse Rust enum encoding string \"%s\""
9900                            "[in module %s]"),
9901                          TYPE_FIELD_NAME (type, 0),
9902                          objfile_name (objfile));
9903               return;
9904             }
9905           ++name;
9906
9907           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9908           field_type = TYPE_FIELD_TYPE (field_type, index);
9909         }
9910
9911       /* Make a union to hold the variants.  */
9912       struct type *union_type = alloc_type (objfile);
9913       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9914       TYPE_NFIELDS (union_type) = 3;
9915       TYPE_FIELDS (union_type)
9916         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9917       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9918       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9919
9920       /* Put the discriminant must at index 0.  */
9921       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9922       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9923       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9924       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9925
9926       /* The order of fields doesn't really matter, so put the real
9927          field at index 1 and the data-less field at index 2.  */
9928       struct discriminant_info *disc
9929         = alloc_discriminant_info (union_type, 0, 1);
9930       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9931       TYPE_FIELD_NAME (union_type, 1)
9932         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9933       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9934         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9935                               TYPE_FIELD_NAME (union_type, 1));
9936
9937       const char *dataless_name
9938         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9939                               name);
9940       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9941                                               dataless_name);
9942       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9943       /* NAME points into the original discriminant name, which
9944          already has the correct lifetime.  */
9945       TYPE_FIELD_NAME (union_type, 2) = name;
9946       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9947       disc->discriminants[2] = 0;
9948
9949       /* Smash this type to be a structure type.  We have to do this
9950          because the type has already been recorded.  */
9951       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9952       TYPE_NFIELDS (type) = 1;
9953       TYPE_FIELDS (type)
9954         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9955
9956       /* Install the variant part.  */
9957       TYPE_FIELD_TYPE (type, 0) = union_type;
9958       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9959       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9960     }
9961   else if (TYPE_NFIELDS (type) == 1)
9962     {
9963       /* We assume that a union with a single field is a univariant
9964          enum.  */
9965       /* Smash this type to be a structure type.  We have to do this
9966          because the type has already been recorded.  */
9967       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9968
9969       /* Make a union to hold the variants.  */
9970       struct type *union_type = alloc_type (objfile);
9971       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9972       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
9973       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9974       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9975       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
9976
9977       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
9978       const char *variant_name
9979         = rust_last_path_segment (TYPE_NAME (field_type));
9980       TYPE_FIELD_NAME (union_type, 0) = variant_name;
9981       TYPE_NAME (field_type)
9982         = rust_fully_qualify (&objfile->objfile_obstack,
9983                               TYPE_NAME (type), variant_name);
9984
9985       /* Install the union in the outer struct type.  */
9986       TYPE_NFIELDS (type) = 1;
9987       TYPE_FIELDS (type)
9988         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
9989       TYPE_FIELD_TYPE (type, 0) = union_type;
9990       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9991       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9992
9993       alloc_discriminant_info (union_type, -1, 0);
9994     }
9995   else
9996     {
9997       struct type *disr_type = nullptr;
9998       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
9999         {
10000           disr_type = TYPE_FIELD_TYPE (type, i);
10001
10002           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
10003             {
10004               /* All fields of a true enum will be structs.  */
10005               return;
10006             }
10007           else if (TYPE_NFIELDS (disr_type) == 0)
10008             {
10009               /* Could be data-less variant, so keep going.  */
10010               disr_type = nullptr;
10011             }
10012           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10013                            "RUST$ENUM$DISR") != 0)
10014             {
10015               /* Not a Rust enum.  */
10016               return;
10017             }
10018           else
10019             {
10020               /* Found one.  */
10021               break;
10022             }
10023         }
10024
10025       /* If we got here without a discriminant, then it's probably
10026          just a union.  */
10027       if (disr_type == nullptr)
10028         return;
10029
10030       /* Smash this type to be a structure type.  We have to do this
10031          because the type has already been recorded.  */
10032       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10033
10034       /* Make a union to hold the variants.  */
10035       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10036       struct type *union_type = alloc_type (objfile);
10037       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10038       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10039       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10040       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10041       TYPE_FIELDS (union_type)
10042         = (struct field *) TYPE_ZALLOC (union_type,
10043                                         (TYPE_NFIELDS (union_type)
10044                                          * sizeof (struct field)));
10045
10046       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10047               TYPE_NFIELDS (type) * sizeof (struct field));
10048
10049       /* Install the discriminant at index 0 in the union.  */
10050       TYPE_FIELD (union_type, 0) = *disr_field;
10051       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10052       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10053
10054       /* Install the union in the outer struct type.  */
10055       TYPE_FIELD_TYPE (type, 0) = union_type;
10056       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10057       TYPE_NFIELDS (type) = 1;
10058
10059       /* Set the size and offset of the union type.  */
10060       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10061
10062       /* We need a way to find the correct discriminant given a
10063          variant name.  For convenience we build a map here.  */
10064       struct type *enum_type = FIELD_TYPE (*disr_field);
10065       std::unordered_map<std::string, ULONGEST> discriminant_map;
10066       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10067         {
10068           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10069             {
10070               const char *name
10071                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10072               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10073             }
10074         }
10075
10076       int n_fields = TYPE_NFIELDS (union_type);
10077       struct discriminant_info *disc
10078         = alloc_discriminant_info (union_type, 0, -1);
10079       /* Skip the discriminant here.  */
10080       for (int i = 1; i < n_fields; ++i)
10081         {
10082           /* Find the final word in the name of this variant's type.
10083              That name can be used to look up the correct
10084              discriminant.  */
10085           const char *variant_name
10086             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10087                                                                   i)));
10088
10089           auto iter = discriminant_map.find (variant_name);
10090           if (iter != discriminant_map.end ())
10091             disc->discriminants[i] = iter->second;
10092
10093           /* Remove the discriminant field, if it exists.  */
10094           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10095           if (TYPE_NFIELDS (sub_type) > 0)
10096             {
10097               --TYPE_NFIELDS (sub_type);
10098               ++TYPE_FIELDS (sub_type);
10099             }
10100           TYPE_FIELD_NAME (union_type, i) = variant_name;
10101           TYPE_NAME (sub_type)
10102             = rust_fully_qualify (&objfile->objfile_obstack,
10103                                   TYPE_NAME (type), variant_name);
10104         }
10105     }
10106 }
10107
10108 /* Rewrite some Rust unions to be structures with variants parts.  */
10109
10110 static void
10111 rust_union_quirks (struct dwarf2_cu *cu)
10112 {
10113   gdb_assert (cu->language == language_rust);
10114   for (type *type_ : cu->rust_unions)
10115     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10116   /* We don't need this any more.  */
10117   cu->rust_unions.clear ();
10118 }
10119
10120 /* Return the symtab for PER_CU.  This works properly regardless of
10121    whether we're using the index or psymtabs.  */
10122
10123 static struct compunit_symtab *
10124 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10125 {
10126   return (per_cu->dwarf2_per_objfile->using_index
10127           ? per_cu->v.quick->compunit_symtab
10128           : per_cu->v.psymtab->compunit_symtab);
10129 }
10130
10131 /* A helper function for computing the list of all symbol tables
10132    included by PER_CU.  */
10133
10134 static void
10135 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10136                                 htab_t all_children, htab_t all_type_symtabs,
10137                                 struct dwarf2_per_cu_data *per_cu,
10138                                 struct compunit_symtab *immediate_parent)
10139 {
10140   void **slot;
10141   int ix;
10142   struct compunit_symtab *cust;
10143   struct dwarf2_per_cu_data *iter;
10144
10145   slot = htab_find_slot (all_children, per_cu, INSERT);
10146   if (*slot != NULL)
10147     {
10148       /* This inclusion and its children have been processed.  */
10149       return;
10150     }
10151
10152   *slot = per_cu;
10153   /* Only add a CU if it has a symbol table.  */
10154   cust = get_compunit_symtab (per_cu);
10155   if (cust != NULL)
10156     {
10157       /* If this is a type unit only add its symbol table if we haven't
10158          seen it yet (type unit per_cu's can share symtabs).  */
10159       if (per_cu->is_debug_types)
10160         {
10161           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10162           if (*slot == NULL)
10163             {
10164               *slot = cust;
10165               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10166               if (cust->user == NULL)
10167                 cust->user = immediate_parent;
10168             }
10169         }
10170       else
10171         {
10172           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10173           if (cust->user == NULL)
10174             cust->user = immediate_parent;
10175         }
10176     }
10177
10178   for (ix = 0;
10179        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10180        ++ix)
10181     {
10182       recursively_compute_inclusions (result, all_children,
10183                                       all_type_symtabs, iter, cust);
10184     }
10185 }
10186
10187 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10188    PER_CU.  */
10189
10190 static void
10191 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10192 {
10193   gdb_assert (! per_cu->is_debug_types);
10194
10195   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10196     {
10197       int ix, len;
10198       struct dwarf2_per_cu_data *per_cu_iter;
10199       struct compunit_symtab *compunit_symtab_iter;
10200       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10201       htab_t all_children, all_type_symtabs;
10202       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10203
10204       /* If we don't have a symtab, we can just skip this case.  */
10205       if (cust == NULL)
10206         return;
10207
10208       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10209                                         NULL, xcalloc, xfree);
10210       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10211                                             NULL, xcalloc, xfree);
10212
10213       for (ix = 0;
10214            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10215                         ix, per_cu_iter);
10216            ++ix)
10217         {
10218           recursively_compute_inclusions (&result_symtabs, all_children,
10219                                           all_type_symtabs, per_cu_iter,
10220                                           cust);
10221         }
10222
10223       /* Now we have a transitive closure of all the included symtabs.  */
10224       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10225       cust->includes
10226         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10227                      struct compunit_symtab *, len + 1);
10228       for (ix = 0;
10229            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10230                         compunit_symtab_iter);
10231            ++ix)
10232         cust->includes[ix] = compunit_symtab_iter;
10233       cust->includes[len] = NULL;
10234
10235       VEC_free (compunit_symtab_ptr, result_symtabs);
10236       htab_delete (all_children);
10237       htab_delete (all_type_symtabs);
10238     }
10239 }
10240
10241 /* Compute the 'includes' field for the symtabs of all the CUs we just
10242    read.  */
10243
10244 static void
10245 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10246 {
10247   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10248     {
10249       if (! iter->is_debug_types)
10250         compute_compunit_symtab_includes (iter);
10251     }
10252
10253   dwarf2_per_objfile->just_read_cus.clear ();
10254 }
10255
10256 /* Generate full symbol information for PER_CU, whose DIEs have
10257    already been loaded into memory.  */
10258
10259 static void
10260 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10261                         enum language pretend_language)
10262 {
10263   struct dwarf2_cu *cu = per_cu->cu;
10264   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10265   struct objfile *objfile = dwarf2_per_objfile->objfile;
10266   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10267   CORE_ADDR lowpc, highpc;
10268   struct compunit_symtab *cust;
10269   CORE_ADDR baseaddr;
10270   struct block *static_block;
10271   CORE_ADDR addr;
10272
10273   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10274
10275   /* Clear the list here in case something was left over.  */
10276   cu->method_list.clear ();
10277
10278   cu->language = pretend_language;
10279   cu->language_defn = language_def (cu->language);
10280
10281   /* Do line number decoding in read_file_scope () */
10282   process_die (cu->dies, cu);
10283
10284   /* For now fudge the Go package.  */
10285   if (cu->language == language_go)
10286     fixup_go_packaging (cu);
10287
10288   /* Now that we have processed all the DIEs in the CU, all the types 
10289      should be complete, and it should now be safe to compute all of the
10290      physnames.  */
10291   compute_delayed_physnames (cu);
10292
10293   if (cu->language == language_rust)
10294     rust_union_quirks (cu);
10295
10296   /* Some compilers don't define a DW_AT_high_pc attribute for the
10297      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10298      it, by scanning the DIE's below the compilation unit.  */
10299   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10300
10301   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10302   static_block = cu->builder->end_symtab_get_static_block (addr, 0, 1);
10303
10304   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10305      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10306      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10307      addrmap to help ensure it has an accurate map of pc values belonging to
10308      this comp unit.  */
10309   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10310
10311   cust = cu->builder->end_symtab_from_static_block (static_block,
10312                                                     SECT_OFF_TEXT (objfile),
10313                                                     0);
10314
10315   if (cust != NULL)
10316     {
10317       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10318
10319       /* Set symtab language to language from DW_AT_language.  If the
10320          compilation is from a C file generated by language preprocessors, do
10321          not set the language if it was already deduced by start_subfile.  */
10322       if (!(cu->language == language_c
10323             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10324         COMPUNIT_FILETABS (cust)->language = cu->language;
10325
10326       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10327          produce DW_AT_location with location lists but it can be possibly
10328          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10329          there were bugs in prologue debug info, fixed later in GCC-4.5
10330          by "unwind info for epilogues" patch (which is not directly related).
10331
10332          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10333          needed, it would be wrong due to missing DW_AT_producer there.
10334
10335          Still one can confuse GDB by using non-standard GCC compilation
10336          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10337          */ 
10338       if (cu->has_loclist && gcc_4_minor >= 5)
10339         cust->locations_valid = 1;
10340
10341       if (gcc_4_minor >= 5)
10342         cust->epilogue_unwind_valid = 1;
10343
10344       cust->call_site_htab = cu->call_site_htab;
10345     }
10346
10347   if (dwarf2_per_objfile->using_index)
10348     per_cu->v.quick->compunit_symtab = cust;
10349   else
10350     {
10351       struct partial_symtab *pst = per_cu->v.psymtab;
10352       pst->compunit_symtab = cust;
10353       pst->readin = 1;
10354     }
10355
10356   /* Push it for inclusion processing later.  */
10357   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10358
10359   /* Not needed any more.  */
10360   cu->builder.reset ();
10361 }
10362
10363 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10364    already been loaded into memory.  */
10365
10366 static void
10367 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10368                         enum language pretend_language)
10369 {
10370   struct dwarf2_cu *cu = per_cu->cu;
10371   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10372   struct objfile *objfile = dwarf2_per_objfile->objfile;
10373   struct compunit_symtab *cust;
10374   struct signatured_type *sig_type;
10375
10376   gdb_assert (per_cu->is_debug_types);
10377   sig_type = (struct signatured_type *) per_cu;
10378
10379   /* Clear the list here in case something was left over.  */
10380   cu->method_list.clear ();
10381
10382   cu->language = pretend_language;
10383   cu->language_defn = language_def (cu->language);
10384
10385   /* The symbol tables are set up in read_type_unit_scope.  */
10386   process_die (cu->dies, cu);
10387
10388   /* For now fudge the Go package.  */
10389   if (cu->language == language_go)
10390     fixup_go_packaging (cu);
10391
10392   /* Now that we have processed all the DIEs in the CU, all the types 
10393      should be complete, and it should now be safe to compute all of the
10394      physnames.  */
10395   compute_delayed_physnames (cu);
10396
10397   if (cu->language == language_rust)
10398     rust_union_quirks (cu);
10399
10400   /* TUs share symbol tables.
10401      If this is the first TU to use this symtab, complete the construction
10402      of it with end_expandable_symtab.  Otherwise, complete the addition of
10403      this TU's symbols to the existing symtab.  */
10404   if (sig_type->type_unit_group->compunit_symtab == NULL)
10405     {
10406       cust = cu->builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10407       sig_type->type_unit_group->compunit_symtab = cust;
10408
10409       if (cust != NULL)
10410         {
10411           /* Set symtab language to language from DW_AT_language.  If the
10412              compilation is from a C file generated by language preprocessors,
10413              do not set the language if it was already deduced by
10414              start_subfile.  */
10415           if (!(cu->language == language_c
10416                 && COMPUNIT_FILETABS (cust)->language != language_c))
10417             COMPUNIT_FILETABS (cust)->language = cu->language;
10418         }
10419     }
10420   else
10421     {
10422       cu->builder->augment_type_symtab ();
10423       cust = sig_type->type_unit_group->compunit_symtab;
10424     }
10425
10426   if (dwarf2_per_objfile->using_index)
10427     per_cu->v.quick->compunit_symtab = cust;
10428   else
10429     {
10430       struct partial_symtab *pst = per_cu->v.psymtab;
10431       pst->compunit_symtab = cust;
10432       pst->readin = 1;
10433     }
10434
10435   /* Not needed any more.  */
10436   cu->builder.reset ();
10437 }
10438
10439 /* Process an imported unit DIE.  */
10440
10441 static void
10442 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10443 {
10444   struct attribute *attr;
10445
10446   /* For now we don't handle imported units in type units.  */
10447   if (cu->per_cu->is_debug_types)
10448     {
10449       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10450                " supported in type units [in module %s]"),
10451              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10452     }
10453
10454   attr = dwarf2_attr (die, DW_AT_import, cu);
10455   if (attr != NULL)
10456     {
10457       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10458       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10459       dwarf2_per_cu_data *per_cu
10460         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10461                                             cu->per_cu->dwarf2_per_objfile);
10462
10463       /* If necessary, add it to the queue and load its DIEs.  */
10464       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10465         load_full_comp_unit (per_cu, false, cu->language);
10466
10467       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10468                      per_cu);
10469     }
10470 }
10471
10472 /* RAII object that represents a process_die scope: i.e.,
10473    starts/finishes processing a DIE.  */
10474 class process_die_scope
10475 {
10476 public:
10477   process_die_scope (die_info *die, dwarf2_cu *cu)
10478     : m_die (die), m_cu (cu)
10479   {
10480     /* We should only be processing DIEs not already in process.  */
10481     gdb_assert (!m_die->in_process);
10482     m_die->in_process = true;
10483   }
10484
10485   ~process_die_scope ()
10486   {
10487     m_die->in_process = false;
10488
10489     /* If we're done processing the DIE for the CU that owns the line
10490        header, we don't need the line header anymore.  */
10491     if (m_cu->line_header_die_owner == m_die)
10492       {
10493         delete m_cu->line_header;
10494         m_cu->line_header = NULL;
10495         m_cu->line_header_die_owner = NULL;
10496       }
10497   }
10498
10499 private:
10500   die_info *m_die;
10501   dwarf2_cu *m_cu;
10502 };
10503
10504 /* Process a die and its children.  */
10505
10506 static void
10507 process_die (struct die_info *die, struct dwarf2_cu *cu)
10508 {
10509   process_die_scope scope (die, cu);
10510
10511   switch (die->tag)
10512     {
10513     case DW_TAG_padding:
10514       break;
10515     case DW_TAG_compile_unit:
10516     case DW_TAG_partial_unit:
10517       read_file_scope (die, cu);
10518       break;
10519     case DW_TAG_type_unit:
10520       read_type_unit_scope (die, cu);
10521       break;
10522     case DW_TAG_subprogram:
10523     case DW_TAG_inlined_subroutine:
10524       read_func_scope (die, cu);
10525       break;
10526     case DW_TAG_lexical_block:
10527     case DW_TAG_try_block:
10528     case DW_TAG_catch_block:
10529       read_lexical_block_scope (die, cu);
10530       break;
10531     case DW_TAG_call_site:
10532     case DW_TAG_GNU_call_site:
10533       read_call_site_scope (die, cu);
10534       break;
10535     case DW_TAG_class_type:
10536     case DW_TAG_interface_type:
10537     case DW_TAG_structure_type:
10538     case DW_TAG_union_type:
10539       process_structure_scope (die, cu);
10540       break;
10541     case DW_TAG_enumeration_type:
10542       process_enumeration_scope (die, cu);
10543       break;
10544
10545     /* These dies have a type, but processing them does not create
10546        a symbol or recurse to process the children.  Therefore we can
10547        read them on-demand through read_type_die.  */
10548     case DW_TAG_subroutine_type:
10549     case DW_TAG_set_type:
10550     case DW_TAG_array_type:
10551     case DW_TAG_pointer_type:
10552     case DW_TAG_ptr_to_member_type:
10553     case DW_TAG_reference_type:
10554     case DW_TAG_rvalue_reference_type:
10555     case DW_TAG_string_type:
10556       break;
10557
10558     case DW_TAG_base_type:
10559     case DW_TAG_subrange_type:
10560     case DW_TAG_typedef:
10561       /* Add a typedef symbol for the type definition, if it has a
10562          DW_AT_name.  */
10563       new_symbol (die, read_type_die (die, cu), cu);
10564       break;
10565     case DW_TAG_common_block:
10566       read_common_block (die, cu);
10567       break;
10568     case DW_TAG_common_inclusion:
10569       break;
10570     case DW_TAG_namespace:
10571       cu->processing_has_namespace_info = 1;
10572       read_namespace (die, cu);
10573       break;
10574     case DW_TAG_module:
10575       cu->processing_has_namespace_info = 1;
10576       read_module (die, cu);
10577       break;
10578     case DW_TAG_imported_declaration:
10579       cu->processing_has_namespace_info = 1;
10580       if (read_namespace_alias (die, cu))
10581         break;
10582       /* The declaration is not a global namespace alias.  */
10583       /* Fall through.  */
10584     case DW_TAG_imported_module:
10585       cu->processing_has_namespace_info = 1;
10586       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10587                                  || cu->language != language_fortran))
10588         complaint (_("Tag '%s' has unexpected children"),
10589                    dwarf_tag_name (die->tag));
10590       read_import_statement (die, cu);
10591       break;
10592
10593     case DW_TAG_imported_unit:
10594       process_imported_unit_die (die, cu);
10595       break;
10596
10597     case DW_TAG_variable:
10598       read_variable (die, cu);
10599       break;
10600
10601     default:
10602       new_symbol (die, NULL, cu);
10603       break;
10604     }
10605 }
10606 \f
10607 /* DWARF name computation.  */
10608
10609 /* A helper function for dwarf2_compute_name which determines whether DIE
10610    needs to have the name of the scope prepended to the name listed in the
10611    die.  */
10612
10613 static int
10614 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10615 {
10616   struct attribute *attr;
10617
10618   switch (die->tag)
10619     {
10620     case DW_TAG_namespace:
10621     case DW_TAG_typedef:
10622     case DW_TAG_class_type:
10623     case DW_TAG_interface_type:
10624     case DW_TAG_structure_type:
10625     case DW_TAG_union_type:
10626     case DW_TAG_enumeration_type:
10627     case DW_TAG_enumerator:
10628     case DW_TAG_subprogram:
10629     case DW_TAG_inlined_subroutine:
10630     case DW_TAG_member:
10631     case DW_TAG_imported_declaration:
10632       return 1;
10633
10634     case DW_TAG_variable:
10635     case DW_TAG_constant:
10636       /* We only need to prefix "globally" visible variables.  These include
10637          any variable marked with DW_AT_external or any variable that
10638          lives in a namespace.  [Variables in anonymous namespaces
10639          require prefixing, but they are not DW_AT_external.]  */
10640
10641       if (dwarf2_attr (die, DW_AT_specification, cu))
10642         {
10643           struct dwarf2_cu *spec_cu = cu;
10644
10645           return die_needs_namespace (die_specification (die, &spec_cu),
10646                                       spec_cu);
10647         }
10648
10649       attr = dwarf2_attr (die, DW_AT_external, cu);
10650       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10651           && die->parent->tag != DW_TAG_module)
10652         return 0;
10653       /* A variable in a lexical block of some kind does not need a
10654          namespace, even though in C++ such variables may be external
10655          and have a mangled name.  */
10656       if (die->parent->tag ==  DW_TAG_lexical_block
10657           || die->parent->tag ==  DW_TAG_try_block
10658           || die->parent->tag ==  DW_TAG_catch_block
10659           || die->parent->tag == DW_TAG_subprogram)
10660         return 0;
10661       return 1;
10662
10663     default:
10664       return 0;
10665     }
10666 }
10667
10668 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10669    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10670    defined for the given DIE.  */
10671
10672 static struct attribute *
10673 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10674 {
10675   struct attribute *attr;
10676
10677   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10678   if (attr == NULL)
10679     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10680
10681   return attr;
10682 }
10683
10684 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10685    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10686    defined for the given DIE.  */
10687
10688 static const char *
10689 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10690 {
10691   const char *linkage_name;
10692
10693   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10694   if (linkage_name == NULL)
10695     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10696
10697   return linkage_name;
10698 }
10699
10700 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10701    compute the physname for the object, which include a method's:
10702    - formal parameters (C++),
10703    - receiver type (Go),
10704
10705    The term "physname" is a bit confusing.
10706    For C++, for example, it is the demangled name.
10707    For Go, for example, it's the mangled name.
10708
10709    For Ada, return the DIE's linkage name rather than the fully qualified
10710    name.  PHYSNAME is ignored..
10711
10712    The result is allocated on the objfile_obstack and canonicalized.  */
10713
10714 static const char *
10715 dwarf2_compute_name (const char *name,
10716                      struct die_info *die, struct dwarf2_cu *cu,
10717                      int physname)
10718 {
10719   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10720
10721   if (name == NULL)
10722     name = dwarf2_name (die, cu);
10723
10724   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10725      but otherwise compute it by typename_concat inside GDB.
10726      FIXME: Actually this is not really true, or at least not always true.
10727      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10728      Fortran names because there is no mangling standard.  So new_symbol
10729      will set the demangled name to the result of dwarf2_full_name, and it is
10730      the demangled name that GDB uses if it exists.  */
10731   if (cu->language == language_ada
10732       || (cu->language == language_fortran && physname))
10733     {
10734       /* For Ada unit, we prefer the linkage name over the name, as
10735          the former contains the exported name, which the user expects
10736          to be able to reference.  Ideally, we want the user to be able
10737          to reference this entity using either natural or linkage name,
10738          but we haven't started looking at this enhancement yet.  */
10739       const char *linkage_name = dw2_linkage_name (die, cu);
10740
10741       if (linkage_name != NULL)
10742         return linkage_name;
10743     }
10744
10745   /* These are the only languages we know how to qualify names in.  */
10746   if (name != NULL
10747       && (cu->language == language_cplus
10748           || cu->language == language_fortran || cu->language == language_d
10749           || cu->language == language_rust))
10750     {
10751       if (die_needs_namespace (die, cu))
10752         {
10753           const char *prefix;
10754           const char *canonical_name = NULL;
10755
10756           string_file buf;
10757
10758           prefix = determine_prefix (die, cu);
10759           if (*prefix != '\0')
10760             {
10761               char *prefixed_name = typename_concat (NULL, prefix, name,
10762                                                      physname, cu);
10763
10764               buf.puts (prefixed_name);
10765               xfree (prefixed_name);
10766             }
10767           else
10768             buf.puts (name);
10769
10770           /* Template parameters may be specified in the DIE's DW_AT_name, or
10771              as children with DW_TAG_template_type_param or
10772              DW_TAG_value_type_param.  If the latter, add them to the name
10773              here.  If the name already has template parameters, then
10774              skip this step; some versions of GCC emit both, and
10775              it is more efficient to use the pre-computed name.
10776
10777              Something to keep in mind about this process: it is very
10778              unlikely, or in some cases downright impossible, to produce
10779              something that will match the mangled name of a function.
10780              If the definition of the function has the same debug info,
10781              we should be able to match up with it anyway.  But fallbacks
10782              using the minimal symbol, for instance to find a method
10783              implemented in a stripped copy of libstdc++, will not work.
10784              If we do not have debug info for the definition, we will have to
10785              match them up some other way.
10786
10787              When we do name matching there is a related problem with function
10788              templates; two instantiated function templates are allowed to
10789              differ only by their return types, which we do not add here.  */
10790
10791           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10792             {
10793               struct attribute *attr;
10794               struct die_info *child;
10795               int first = 1;
10796
10797               die->building_fullname = 1;
10798
10799               for (child = die->child; child != NULL; child = child->sibling)
10800                 {
10801                   struct type *type;
10802                   LONGEST value;
10803                   const gdb_byte *bytes;
10804                   struct dwarf2_locexpr_baton *baton;
10805                   struct value *v;
10806
10807                   if (child->tag != DW_TAG_template_type_param
10808                       && child->tag != DW_TAG_template_value_param)
10809                     continue;
10810
10811                   if (first)
10812                     {
10813                       buf.puts ("<");
10814                       first = 0;
10815                     }
10816                   else
10817                     buf.puts (", ");
10818
10819                   attr = dwarf2_attr (child, DW_AT_type, cu);
10820                   if (attr == NULL)
10821                     {
10822                       complaint (_("template parameter missing DW_AT_type"));
10823                       buf.puts ("UNKNOWN_TYPE");
10824                       continue;
10825                     }
10826                   type = die_type (child, cu);
10827
10828                   if (child->tag == DW_TAG_template_type_param)
10829                     {
10830                       c_print_type (type, "", &buf, -1, 0, cu->language,
10831                                     &type_print_raw_options);
10832                       continue;
10833                     }
10834
10835                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10836                   if (attr == NULL)
10837                     {
10838                       complaint (_("template parameter missing "
10839                                    "DW_AT_const_value"));
10840                       buf.puts ("UNKNOWN_VALUE");
10841                       continue;
10842                     }
10843
10844                   dwarf2_const_value_attr (attr, type, name,
10845                                            &cu->comp_unit_obstack, cu,
10846                                            &value, &bytes, &baton);
10847
10848                   if (TYPE_NOSIGN (type))
10849                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10850                        changed, this can use value_print instead.  */
10851                     c_printchar (value, type, &buf);
10852                   else
10853                     {
10854                       struct value_print_options opts;
10855
10856                       if (baton != NULL)
10857                         v = dwarf2_evaluate_loc_desc (type, NULL,
10858                                                       baton->data,
10859                                                       baton->size,
10860                                                       baton->per_cu);
10861                       else if (bytes != NULL)
10862                         {
10863                           v = allocate_value (type);
10864                           memcpy (value_contents_writeable (v), bytes,
10865                                   TYPE_LENGTH (type));
10866                         }
10867                       else
10868                         v = value_from_longest (type, value);
10869
10870                       /* Specify decimal so that we do not depend on
10871                          the radix.  */
10872                       get_formatted_print_options (&opts, 'd');
10873                       opts.raw = 1;
10874                       value_print (v, &buf, &opts);
10875                       release_value (v);
10876                     }
10877                 }
10878
10879               die->building_fullname = 0;
10880
10881               if (!first)
10882                 {
10883                   /* Close the argument list, with a space if necessary
10884                      (nested templates).  */
10885                   if (!buf.empty () && buf.string ().back () == '>')
10886                     buf.puts (" >");
10887                   else
10888                     buf.puts (">");
10889                 }
10890             }
10891
10892           /* For C++ methods, append formal parameter type
10893              information, if PHYSNAME.  */
10894
10895           if (physname && die->tag == DW_TAG_subprogram
10896               && cu->language == language_cplus)
10897             {
10898               struct type *type = read_type_die (die, cu);
10899
10900               c_type_print_args (type, &buf, 1, cu->language,
10901                                  &type_print_raw_options);
10902
10903               if (cu->language == language_cplus)
10904                 {
10905                   /* Assume that an artificial first parameter is
10906                      "this", but do not crash if it is not.  RealView
10907                      marks unnamed (and thus unused) parameters as
10908                      artificial; there is no way to differentiate
10909                      the two cases.  */
10910                   if (TYPE_NFIELDS (type) > 0
10911                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10912                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10913                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10914                                                                         0))))
10915                     buf.puts (" const");
10916                 }
10917             }
10918
10919           const std::string &intermediate_name = buf.string ();
10920
10921           if (cu->language == language_cplus)
10922             canonical_name
10923               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10924                                           &objfile->per_bfd->storage_obstack);
10925
10926           /* If we only computed INTERMEDIATE_NAME, or if
10927              INTERMEDIATE_NAME is already canonical, then we need to
10928              copy it to the appropriate obstack.  */
10929           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10930             name = ((const char *)
10931                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10932                                    intermediate_name.c_str (),
10933                                    intermediate_name.length ()));
10934           else
10935             name = canonical_name;
10936         }
10937     }
10938
10939   return name;
10940 }
10941
10942 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10943    If scope qualifiers are appropriate they will be added.  The result
10944    will be allocated on the storage_obstack, or NULL if the DIE does
10945    not have a name.  NAME may either be from a previous call to
10946    dwarf2_name or NULL.
10947
10948    The output string will be canonicalized (if C++).  */
10949
10950 static const char *
10951 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10952 {
10953   return dwarf2_compute_name (name, die, cu, 0);
10954 }
10955
10956 /* Construct a physname for the given DIE in CU.  NAME may either be
10957    from a previous call to dwarf2_name or NULL.  The result will be
10958    allocated on the objfile_objstack or NULL if the DIE does not have a
10959    name.
10960
10961    The output string will be canonicalized (if C++).  */
10962
10963 static const char *
10964 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10965 {
10966   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10967   const char *retval, *mangled = NULL, *canon = NULL;
10968   int need_copy = 1;
10969
10970   /* In this case dwarf2_compute_name is just a shortcut not building anything
10971      on its own.  */
10972   if (!die_needs_namespace (die, cu))
10973     return dwarf2_compute_name (name, die, cu, 1);
10974
10975   mangled = dw2_linkage_name (die, cu);
10976
10977   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10978      See https://github.com/rust-lang/rust/issues/32925.  */
10979   if (cu->language == language_rust && mangled != NULL
10980       && strchr (mangled, '{') != NULL)
10981     mangled = NULL;
10982
10983   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10984      has computed.  */
10985   gdb::unique_xmalloc_ptr<char> demangled;
10986   if (mangled != NULL)
10987     {
10988
10989       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
10990         {
10991           /* Do nothing (do not demangle the symbol name).  */
10992         }
10993       else if (cu->language == language_go)
10994         {
10995           /* This is a lie, but we already lie to the caller new_symbol.
10996              new_symbol assumes we return the mangled name.
10997              This just undoes that lie until things are cleaned up.  */
10998         }
10999       else
11000         {
11001           /* Use DMGL_RET_DROP for C++ template functions to suppress
11002              their return type.  It is easier for GDB users to search
11003              for such functions as `name(params)' than `long name(params)'.
11004              In such case the minimal symbol names do not match the full
11005              symbol names but for template functions there is never a need
11006              to look up their definition from their declaration so
11007              the only disadvantage remains the minimal symbol variant
11008              `long name(params)' does not have the proper inferior type.  */
11009           demangled.reset (gdb_demangle (mangled,
11010                                          (DMGL_PARAMS | DMGL_ANSI
11011                                           | DMGL_RET_DROP)));
11012         }
11013       if (demangled)
11014         canon = demangled.get ();
11015       else
11016         {
11017           canon = mangled;
11018           need_copy = 0;
11019         }
11020     }
11021
11022   if (canon == NULL || check_physname)
11023     {
11024       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11025
11026       if (canon != NULL && strcmp (physname, canon) != 0)
11027         {
11028           /* It may not mean a bug in GDB.  The compiler could also
11029              compute DW_AT_linkage_name incorrectly.  But in such case
11030              GDB would need to be bug-to-bug compatible.  */
11031
11032           complaint (_("Computed physname <%s> does not match demangled <%s> "
11033                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11034                      physname, canon, mangled, sect_offset_str (die->sect_off),
11035                      objfile_name (objfile));
11036
11037           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11038              is available here - over computed PHYSNAME.  It is safer
11039              against both buggy GDB and buggy compilers.  */
11040
11041           retval = canon;
11042         }
11043       else
11044         {
11045           retval = physname;
11046           need_copy = 0;
11047         }
11048     }
11049   else
11050     retval = canon;
11051
11052   if (need_copy)
11053     retval = ((const char *)
11054               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11055                              retval, strlen (retval)));
11056
11057   return retval;
11058 }
11059
11060 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11061    a new symbol for it.
11062
11063    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11064
11065 static int
11066 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11067 {
11068   struct attribute *attr;
11069
11070   /* If the die does not have a name, this is not a namespace
11071      alias.  */
11072   attr = dwarf2_attr (die, DW_AT_name, cu);
11073   if (attr != NULL)
11074     {
11075       int num;
11076       struct die_info *d = die;
11077       struct dwarf2_cu *imported_cu = cu;
11078
11079       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11080          keep inspecting DIEs until we hit the underlying import.  */
11081 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11082       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11083         {
11084           attr = dwarf2_attr (d, DW_AT_import, cu);
11085           if (attr == NULL)
11086             break;
11087
11088           d = follow_die_ref (d, attr, &imported_cu);
11089           if (d->tag != DW_TAG_imported_declaration)
11090             break;
11091         }
11092
11093       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11094         {
11095           complaint (_("DIE at %s has too many recursively imported "
11096                        "declarations"), sect_offset_str (d->sect_off));
11097           return 0;
11098         }
11099
11100       if (attr != NULL)
11101         {
11102           struct type *type;
11103           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11104
11105           type = get_die_type_at_offset (sect_off, cu->per_cu);
11106           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11107             {
11108               /* This declaration is a global namespace alias.  Add
11109                  a symbol for it whose type is the aliased namespace.  */
11110               new_symbol (die, type, cu);
11111               return 1;
11112             }
11113         }
11114     }
11115
11116   return 0;
11117 }
11118
11119 /* Return the using directives repository (global or local?) to use in the
11120    current context for CU.
11121
11122    For Ada, imported declarations can materialize renamings, which *may* be
11123    global.  However it is impossible (for now?) in DWARF to distinguish
11124    "external" imported declarations and "static" ones.  As all imported
11125    declarations seem to be static in all other languages, make them all CU-wide
11126    global only in Ada.  */
11127
11128 static struct using_direct **
11129 using_directives (struct dwarf2_cu *cu)
11130 {
11131   if (cu->language == language_ada && cu->builder->outermost_context_p ())
11132     return cu->builder->get_global_using_directives ();
11133   else
11134     return cu->builder->get_local_using_directives ();
11135 }
11136
11137 /* Read the import statement specified by the given die and record it.  */
11138
11139 static void
11140 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11141 {
11142   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11143   struct attribute *import_attr;
11144   struct die_info *imported_die, *child_die;
11145   struct dwarf2_cu *imported_cu;
11146   const char *imported_name;
11147   const char *imported_name_prefix;
11148   const char *canonical_name;
11149   const char *import_alias;
11150   const char *imported_declaration = NULL;
11151   const char *import_prefix;
11152   std::vector<const char *> excludes;
11153
11154   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11155   if (import_attr == NULL)
11156     {
11157       complaint (_("Tag '%s' has no DW_AT_import"),
11158                  dwarf_tag_name (die->tag));
11159       return;
11160     }
11161
11162   imported_cu = cu;
11163   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11164   imported_name = dwarf2_name (imported_die, imported_cu);
11165   if (imported_name == NULL)
11166     {
11167       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11168
11169         The import in the following code:
11170         namespace A
11171           {
11172             typedef int B;
11173           }
11174
11175         int main ()
11176           {
11177             using A::B;
11178             B b;
11179             return b;
11180           }
11181
11182         ...
11183          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11184             <52>   DW_AT_decl_file   : 1
11185             <53>   DW_AT_decl_line   : 6
11186             <54>   DW_AT_import      : <0x75>
11187          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11188             <59>   DW_AT_name        : B
11189             <5b>   DW_AT_decl_file   : 1
11190             <5c>   DW_AT_decl_line   : 2
11191             <5d>   DW_AT_type        : <0x6e>
11192         ...
11193          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11194             <76>   DW_AT_byte_size   : 4
11195             <77>   DW_AT_encoding    : 5        (signed)
11196
11197         imports the wrong die ( 0x75 instead of 0x58 ).
11198         This case will be ignored until the gcc bug is fixed.  */
11199       return;
11200     }
11201
11202   /* Figure out the local name after import.  */
11203   import_alias = dwarf2_name (die, cu);
11204
11205   /* Figure out where the statement is being imported to.  */
11206   import_prefix = determine_prefix (die, cu);
11207
11208   /* Figure out what the scope of the imported die is and prepend it
11209      to the name of the imported die.  */
11210   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11211
11212   if (imported_die->tag != DW_TAG_namespace
11213       && imported_die->tag != DW_TAG_module)
11214     {
11215       imported_declaration = imported_name;
11216       canonical_name = imported_name_prefix;
11217     }
11218   else if (strlen (imported_name_prefix) > 0)
11219     canonical_name = obconcat (&objfile->objfile_obstack,
11220                                imported_name_prefix,
11221                                (cu->language == language_d ? "." : "::"),
11222                                imported_name, (char *) NULL);
11223   else
11224     canonical_name = imported_name;
11225
11226   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11227     for (child_die = die->child; child_die && child_die->tag;
11228          child_die = sibling_die (child_die))
11229       {
11230         /* DWARF-4: A Fortran use statement with a “rename list” may be
11231            represented by an imported module entry with an import attribute
11232            referring to the module and owned entries corresponding to those
11233            entities that are renamed as part of being imported.  */
11234
11235         if (child_die->tag != DW_TAG_imported_declaration)
11236           {
11237             complaint (_("child DW_TAG_imported_declaration expected "
11238                          "- DIE at %s [in module %s]"),
11239                        sect_offset_str (child_die->sect_off),
11240                        objfile_name (objfile));
11241             continue;
11242           }
11243
11244         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11245         if (import_attr == NULL)
11246           {
11247             complaint (_("Tag '%s' has no DW_AT_import"),
11248                        dwarf_tag_name (child_die->tag));
11249             continue;
11250           }
11251
11252         imported_cu = cu;
11253         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11254                                               &imported_cu);
11255         imported_name = dwarf2_name (imported_die, imported_cu);
11256         if (imported_name == NULL)
11257           {
11258             complaint (_("child DW_TAG_imported_declaration has unknown "
11259                          "imported name - DIE at %s [in module %s]"),
11260                        sect_offset_str (child_die->sect_off),
11261                        objfile_name (objfile));
11262             continue;
11263           }
11264
11265         excludes.push_back (imported_name);
11266
11267         process_die (child_die, cu);
11268       }
11269
11270   add_using_directive (using_directives (cu),
11271                        import_prefix,
11272                        canonical_name,
11273                        import_alias,
11274                        imported_declaration,
11275                        excludes,
11276                        0,
11277                        &objfile->objfile_obstack);
11278 }
11279
11280 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11281    types, but gives them a size of zero.  Starting with version 14,
11282    ICC is compatible with GCC.  */
11283
11284 static int
11285 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11286 {
11287   if (!cu->checked_producer)
11288     check_producer (cu);
11289
11290   return cu->producer_is_icc_lt_14;
11291 }
11292
11293 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11294    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11295    this, it was first present in GCC release 4.3.0.  */
11296
11297 static int
11298 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11299 {
11300   if (!cu->checked_producer)
11301     check_producer (cu);
11302
11303   return cu->producer_is_gcc_lt_4_3;
11304 }
11305
11306 static file_and_directory
11307 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11308 {
11309   file_and_directory res;
11310
11311   /* Find the filename.  Do not use dwarf2_name here, since the filename
11312      is not a source language identifier.  */
11313   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11314   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11315
11316   if (res.comp_dir == NULL
11317       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11318       && IS_ABSOLUTE_PATH (res.name))
11319     {
11320       res.comp_dir_storage = ldirname (res.name);
11321       if (!res.comp_dir_storage.empty ())
11322         res.comp_dir = res.comp_dir_storage.c_str ();
11323     }
11324   if (res.comp_dir != NULL)
11325     {
11326       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11327          directory, get rid of it.  */
11328       const char *cp = strchr (res.comp_dir, ':');
11329
11330       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11331         res.comp_dir = cp + 1;
11332     }
11333
11334   if (res.name == NULL)
11335     res.name = "<unknown>";
11336
11337   return res;
11338 }
11339
11340 /* Handle DW_AT_stmt_list for a compilation unit.
11341    DIE is the DW_TAG_compile_unit die for CU.
11342    COMP_DIR is the compilation directory.  LOWPC is passed to
11343    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11344
11345 static void
11346 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11347                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11348 {
11349   struct dwarf2_per_objfile *dwarf2_per_objfile
11350     = cu->per_cu->dwarf2_per_objfile;
11351   struct objfile *objfile = dwarf2_per_objfile->objfile;
11352   struct attribute *attr;
11353   struct line_header line_header_local;
11354   hashval_t line_header_local_hash;
11355   void **slot;
11356   int decode_mapping;
11357
11358   gdb_assert (! cu->per_cu->is_debug_types);
11359
11360   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11361   if (attr == NULL)
11362     return;
11363
11364   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11365
11366   /* The line header hash table is only created if needed (it exists to
11367      prevent redundant reading of the line table for partial_units).
11368      If we're given a partial_unit, we'll need it.  If we're given a
11369      compile_unit, then use the line header hash table if it's already
11370      created, but don't create one just yet.  */
11371
11372   if (dwarf2_per_objfile->line_header_hash == NULL
11373       && die->tag == DW_TAG_partial_unit)
11374     {
11375       dwarf2_per_objfile->line_header_hash
11376         = htab_create_alloc_ex (127, line_header_hash_voidp,
11377                                 line_header_eq_voidp,
11378                                 free_line_header_voidp,
11379                                 &objfile->objfile_obstack,
11380                                 hashtab_obstack_allocate,
11381                                 dummy_obstack_deallocate);
11382     }
11383
11384   line_header_local.sect_off = line_offset;
11385   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11386   line_header_local_hash = line_header_hash (&line_header_local);
11387   if (dwarf2_per_objfile->line_header_hash != NULL)
11388     {
11389       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11390                                        &line_header_local,
11391                                        line_header_local_hash, NO_INSERT);
11392
11393       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11394          is not present in *SLOT (since if there is something in *SLOT then
11395          it will be for a partial_unit).  */
11396       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11397         {
11398           gdb_assert (*slot != NULL);
11399           cu->line_header = (struct line_header *) *slot;
11400           return;
11401         }
11402     }
11403
11404   /* dwarf_decode_line_header does not yet provide sufficient information.
11405      We always have to call also dwarf_decode_lines for it.  */
11406   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11407   if (lh == NULL)
11408     return;
11409
11410   cu->line_header = lh.release ();
11411   cu->line_header_die_owner = die;
11412
11413   if (dwarf2_per_objfile->line_header_hash == NULL)
11414     slot = NULL;
11415   else
11416     {
11417       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11418                                        &line_header_local,
11419                                        line_header_local_hash, INSERT);
11420       gdb_assert (slot != NULL);
11421     }
11422   if (slot != NULL && *slot == NULL)
11423     {
11424       /* This newly decoded line number information unit will be owned
11425          by line_header_hash hash table.  */
11426       *slot = cu->line_header;
11427       cu->line_header_die_owner = NULL;
11428     }
11429   else
11430     {
11431       /* We cannot free any current entry in (*slot) as that struct line_header
11432          may be already used by multiple CUs.  Create only temporary decoded
11433          line_header for this CU - it may happen at most once for each line
11434          number information unit.  And if we're not using line_header_hash
11435          then this is what we want as well.  */
11436       gdb_assert (die->tag != DW_TAG_partial_unit);
11437     }
11438   decode_mapping = (die->tag != DW_TAG_partial_unit);
11439   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11440                       decode_mapping);
11441
11442 }
11443
11444 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11445
11446 static void
11447 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11448 {
11449   struct dwarf2_per_objfile *dwarf2_per_objfile
11450     = cu->per_cu->dwarf2_per_objfile;
11451   struct objfile *objfile = dwarf2_per_objfile->objfile;
11452   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11453   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11454   CORE_ADDR highpc = ((CORE_ADDR) 0);
11455   struct attribute *attr;
11456   struct die_info *child_die;
11457   CORE_ADDR baseaddr;
11458
11459   prepare_one_comp_unit (cu, die, cu->language);
11460   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11461
11462   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11463
11464   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11465      from finish_block.  */
11466   if (lowpc == ((CORE_ADDR) -1))
11467     lowpc = highpc;
11468   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11469
11470   file_and_directory fnd = find_file_and_directory (die, cu);
11471
11472   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11473      standardised yet.  As a workaround for the language detection we fall
11474      back to the DW_AT_producer string.  */
11475   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11476     cu->language = language_opencl;
11477
11478   /* Similar hack for Go.  */
11479   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11480     set_cu_language (DW_LANG_Go, cu);
11481
11482   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11483
11484   /* Decode line number information if present.  We do this before
11485      processing child DIEs, so that the line header table is available
11486      for DW_AT_decl_file.  */
11487   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11488
11489   /* Process all dies in compilation unit.  */
11490   if (die->child != NULL)
11491     {
11492       child_die = die->child;
11493       while (child_die && child_die->tag)
11494         {
11495           process_die (child_die, cu);
11496           child_die = sibling_die (child_die);
11497         }
11498     }
11499
11500   /* Decode macro information, if present.  Dwarf 2 macro information
11501      refers to information in the line number info statement program
11502      header, so we can only read it if we've read the header
11503      successfully.  */
11504   attr = dwarf2_attr (die, DW_AT_macros, cu);
11505   if (attr == NULL)
11506     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11507   if (attr && cu->line_header)
11508     {
11509       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11510         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11511
11512       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11513     }
11514   else
11515     {
11516       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11517       if (attr && cu->line_header)
11518         {
11519           unsigned int macro_offset = DW_UNSND (attr);
11520
11521           dwarf_decode_macros (cu, macro_offset, 0);
11522         }
11523     }
11524 }
11525
11526 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11527    Create the set of symtabs used by this TU, or if this TU is sharing
11528    symtabs with another TU and the symtabs have already been created
11529    then restore those symtabs in the line header.
11530    We don't need the pc/line-number mapping for type units.  */
11531
11532 static void
11533 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11534 {
11535   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11536   struct type_unit_group *tu_group;
11537   int first_time;
11538   struct attribute *attr;
11539   unsigned int i;
11540   struct signatured_type *sig_type;
11541
11542   gdb_assert (per_cu->is_debug_types);
11543   sig_type = (struct signatured_type *) per_cu;
11544
11545   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11546
11547   /* If we're using .gdb_index (includes -readnow) then
11548      per_cu->type_unit_group may not have been set up yet.  */
11549   if (sig_type->type_unit_group == NULL)
11550     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11551   tu_group = sig_type->type_unit_group;
11552
11553   /* If we've already processed this stmt_list there's no real need to
11554      do it again, we could fake it and just recreate the part we need
11555      (file name,index -> symtab mapping).  If data shows this optimization
11556      is useful we can do it then.  */
11557   first_time = tu_group->compunit_symtab == NULL;
11558
11559   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11560      debug info.  */
11561   line_header_up lh;
11562   if (attr != NULL)
11563     {
11564       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11565       lh = dwarf_decode_line_header (line_offset, cu);
11566     }
11567   if (lh == NULL)
11568     {
11569       if (first_time)
11570         dwarf2_start_symtab (cu, "", NULL, 0);
11571       else
11572         {
11573           gdb_assert (tu_group->symtabs == NULL);
11574           gdb_assert (cu->builder == nullptr);
11575           struct compunit_symtab *cust = tu_group->compunit_symtab;
11576           cu->builder.reset (new struct buildsym_compunit
11577                              (COMPUNIT_OBJFILE (cust), "",
11578                               COMPUNIT_DIRNAME (cust),
11579                               compunit_language (cust),
11580                               0, cust));
11581         }
11582       return;
11583     }
11584
11585   cu->line_header = lh.release ();
11586   cu->line_header_die_owner = die;
11587
11588   if (first_time)
11589     {
11590       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11591
11592       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11593          still initializing it, and our caller (a few levels up)
11594          process_full_type_unit still needs to know if this is the first
11595          time.  */
11596
11597       tu_group->num_symtabs = cu->line_header->file_names.size ();
11598       tu_group->symtabs = XNEWVEC (struct symtab *,
11599                                    cu->line_header->file_names.size ());
11600
11601       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11602         {
11603           file_entry &fe = cu->line_header->file_names[i];
11604
11605           dwarf2_start_subfile (cu, fe.name, fe.include_dir (cu->line_header));
11606
11607           if (cu->builder->get_current_subfile ()->symtab == NULL)
11608             {
11609               /* NOTE: start_subfile will recognize when it's been
11610                  passed a file it has already seen.  So we can't
11611                  assume there's a simple mapping from
11612                  cu->line_header->file_names to subfiles, plus
11613                  cu->line_header->file_names may contain dups.  */
11614               cu->builder->get_current_subfile ()->symtab
11615                 = allocate_symtab (cust,
11616                                    cu->builder->get_current_subfile ()->name);
11617             }
11618
11619           fe.symtab = cu->builder->get_current_subfile ()->symtab;
11620           tu_group->symtabs[i] = fe.symtab;
11621         }
11622     }
11623   else
11624     {
11625       gdb_assert (cu->builder == nullptr);
11626       struct compunit_symtab *cust = tu_group->compunit_symtab;
11627       cu->builder.reset (new struct buildsym_compunit
11628                          (COMPUNIT_OBJFILE (cust), "",
11629                           COMPUNIT_DIRNAME (cust),
11630                           compunit_language (cust),
11631                           0, cust));
11632
11633       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11634         {
11635           file_entry &fe = cu->line_header->file_names[i];
11636
11637           fe.symtab = tu_group->symtabs[i];
11638         }
11639     }
11640
11641   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11642      so they don't have a "real" (so to speak) symtab anyway.
11643      There is later code that will assign the main symtab to all symbols
11644      that don't have one.  We need to handle the case of a symbol with a
11645      missing symtab (DW_AT_decl_file) anyway.  */
11646 }
11647
11648 /* Process DW_TAG_type_unit.
11649    For TUs we want to skip the first top level sibling if it's not the
11650    actual type being defined by this TU.  In this case the first top
11651    level sibling is there to provide context only.  */
11652
11653 static void
11654 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11655 {
11656   struct die_info *child_die;
11657
11658   prepare_one_comp_unit (cu, die, language_minimal);
11659
11660   /* Initialize (or reinitialize) the machinery for building symtabs.
11661      We do this before processing child DIEs, so that the line header table
11662      is available for DW_AT_decl_file.  */
11663   setup_type_unit_groups (die, cu);
11664
11665   if (die->child != NULL)
11666     {
11667       child_die = die->child;
11668       while (child_die && child_die->tag)
11669         {
11670           process_die (child_die, cu);
11671           child_die = sibling_die (child_die);
11672         }
11673     }
11674 }
11675 \f
11676 /* DWO/DWP files.
11677
11678    http://gcc.gnu.org/wiki/DebugFission
11679    http://gcc.gnu.org/wiki/DebugFissionDWP
11680
11681    To simplify handling of both DWO files ("object" files with the DWARF info)
11682    and DWP files (a file with the DWOs packaged up into one file), we treat
11683    DWP files as having a collection of virtual DWO files.  */
11684
11685 static hashval_t
11686 hash_dwo_file (const void *item)
11687 {
11688   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11689   hashval_t hash;
11690
11691   hash = htab_hash_string (dwo_file->dwo_name);
11692   if (dwo_file->comp_dir != NULL)
11693     hash += htab_hash_string (dwo_file->comp_dir);
11694   return hash;
11695 }
11696
11697 static int
11698 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11699 {
11700   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11701   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11702
11703   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11704     return 0;
11705   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11706     return lhs->comp_dir == rhs->comp_dir;
11707   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11708 }
11709
11710 /* Allocate a hash table for DWO files.  */
11711
11712 static htab_t
11713 allocate_dwo_file_hash_table (struct objfile *objfile)
11714 {
11715   return htab_create_alloc_ex (41,
11716                                hash_dwo_file,
11717                                eq_dwo_file,
11718                                NULL,
11719                                &objfile->objfile_obstack,
11720                                hashtab_obstack_allocate,
11721                                dummy_obstack_deallocate);
11722 }
11723
11724 /* Lookup DWO file DWO_NAME.  */
11725
11726 static void **
11727 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11728                       const char *dwo_name,
11729                       const char *comp_dir)
11730 {
11731   struct dwo_file find_entry;
11732   void **slot;
11733
11734   if (dwarf2_per_objfile->dwo_files == NULL)
11735     dwarf2_per_objfile->dwo_files
11736       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11737
11738   memset (&find_entry, 0, sizeof (find_entry));
11739   find_entry.dwo_name = dwo_name;
11740   find_entry.comp_dir = comp_dir;
11741   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11742
11743   return slot;
11744 }
11745
11746 static hashval_t
11747 hash_dwo_unit (const void *item)
11748 {
11749   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11750
11751   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11752   return dwo_unit->signature;
11753 }
11754
11755 static int
11756 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11757 {
11758   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11759   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11760
11761   /* The signature is assumed to be unique within the DWO file.
11762      So while object file CU dwo_id's always have the value zero,
11763      that's OK, assuming each object file DWO file has only one CU,
11764      and that's the rule for now.  */
11765   return lhs->signature == rhs->signature;
11766 }
11767
11768 /* Allocate a hash table for DWO CUs,TUs.
11769    There is one of these tables for each of CUs,TUs for each DWO file.  */
11770
11771 static htab_t
11772 allocate_dwo_unit_table (struct objfile *objfile)
11773 {
11774   /* Start out with a pretty small number.
11775      Generally DWO files contain only one CU and maybe some TUs.  */
11776   return htab_create_alloc_ex (3,
11777                                hash_dwo_unit,
11778                                eq_dwo_unit,
11779                                NULL,
11780                                &objfile->objfile_obstack,
11781                                hashtab_obstack_allocate,
11782                                dummy_obstack_deallocate);
11783 }
11784
11785 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11786
11787 struct create_dwo_cu_data
11788 {
11789   struct dwo_file *dwo_file;
11790   struct dwo_unit dwo_unit;
11791 };
11792
11793 /* die_reader_func for create_dwo_cu.  */
11794
11795 static void
11796 create_dwo_cu_reader (const struct die_reader_specs *reader,
11797                       const gdb_byte *info_ptr,
11798                       struct die_info *comp_unit_die,
11799                       int has_children,
11800                       void *datap)
11801 {
11802   struct dwarf2_cu *cu = reader->cu;
11803   sect_offset sect_off = cu->per_cu->sect_off;
11804   struct dwarf2_section_info *section = cu->per_cu->section;
11805   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11806   struct dwo_file *dwo_file = data->dwo_file;
11807   struct dwo_unit *dwo_unit = &data->dwo_unit;
11808   struct attribute *attr;
11809
11810   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11811   if (attr == NULL)
11812     {
11813       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11814                    " its dwo_id [in module %s]"),
11815                  sect_offset_str (sect_off), dwo_file->dwo_name);
11816       return;
11817     }
11818
11819   dwo_unit->dwo_file = dwo_file;
11820   dwo_unit->signature = DW_UNSND (attr);
11821   dwo_unit->section = section;
11822   dwo_unit->sect_off = sect_off;
11823   dwo_unit->length = cu->per_cu->length;
11824
11825   if (dwarf_read_debug)
11826     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11827                         sect_offset_str (sect_off),
11828                         hex_string (dwo_unit->signature));
11829 }
11830
11831 /* Create the dwo_units for the CUs in a DWO_FILE.
11832    Note: This function processes DWO files only, not DWP files.  */
11833
11834 static void
11835 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11836                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11837                        htab_t &cus_htab)
11838 {
11839   struct objfile *objfile = dwarf2_per_objfile->objfile;
11840   const gdb_byte *info_ptr, *end_ptr;
11841
11842   dwarf2_read_section (objfile, &section);
11843   info_ptr = section.buffer;
11844
11845   if (info_ptr == NULL)
11846     return;
11847
11848   if (dwarf_read_debug)
11849     {
11850       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11851                           get_section_name (&section),
11852                           get_section_file_name (&section));
11853     }
11854
11855   end_ptr = info_ptr + section.size;
11856   while (info_ptr < end_ptr)
11857     {
11858       struct dwarf2_per_cu_data per_cu;
11859       struct create_dwo_cu_data create_dwo_cu_data;
11860       struct dwo_unit *dwo_unit;
11861       void **slot;
11862       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11863
11864       memset (&create_dwo_cu_data.dwo_unit, 0,
11865               sizeof (create_dwo_cu_data.dwo_unit));
11866       memset (&per_cu, 0, sizeof (per_cu));
11867       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11868       per_cu.is_debug_types = 0;
11869       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11870       per_cu.section = &section;
11871       create_dwo_cu_data.dwo_file = &dwo_file;
11872
11873       init_cutu_and_read_dies_no_follow (
11874           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11875       info_ptr += per_cu.length;
11876
11877       // If the unit could not be parsed, skip it.
11878       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11879         continue;
11880
11881       if (cus_htab == NULL)
11882         cus_htab = allocate_dwo_unit_table (objfile);
11883
11884       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11885       *dwo_unit = create_dwo_cu_data.dwo_unit;
11886       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11887       gdb_assert (slot != NULL);
11888       if (*slot != NULL)
11889         {
11890           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11891           sect_offset dup_sect_off = dup_cu->sect_off;
11892
11893           complaint (_("debug cu entry at offset %s is duplicate to"
11894                        " the entry at offset %s, signature %s"),
11895                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11896                      hex_string (dwo_unit->signature));
11897         }
11898       *slot = (void *)dwo_unit;
11899     }
11900 }
11901
11902 /* DWP file .debug_{cu,tu}_index section format:
11903    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11904
11905    DWP Version 1:
11906
11907    Both index sections have the same format, and serve to map a 64-bit
11908    signature to a set of section numbers.  Each section begins with a header,
11909    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11910    indexes, and a pool of 32-bit section numbers.  The index sections will be
11911    aligned at 8-byte boundaries in the file.
11912
11913    The index section header consists of:
11914
11915     V, 32 bit version number
11916     -, 32 bits unused
11917     N, 32 bit number of compilation units or type units in the index
11918     M, 32 bit number of slots in the hash table
11919
11920    Numbers are recorded using the byte order of the application binary.
11921
11922    The hash table begins at offset 16 in the section, and consists of an array
11923    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11924    order of the application binary).  Unused slots in the hash table are 0.
11925    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11926
11927    The parallel table begins immediately after the hash table
11928    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11929    array of 32-bit indexes (using the byte order of the application binary),
11930    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11931    table contains a 32-bit index into the pool of section numbers.  For unused
11932    hash table slots, the corresponding entry in the parallel table will be 0.
11933
11934    The pool of section numbers begins immediately following the hash table
11935    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11936    section numbers consists of an array of 32-bit words (using the byte order
11937    of the application binary).  Each item in the array is indexed starting
11938    from 0.  The hash table entry provides the index of the first section
11939    number in the set.  Additional section numbers in the set follow, and the
11940    set is terminated by a 0 entry (section number 0 is not used in ELF).
11941
11942    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11943    section must be the first entry in the set, and the .debug_abbrev.dwo must
11944    be the second entry. Other members of the set may follow in any order.
11945
11946    ---
11947
11948    DWP Version 2:
11949
11950    DWP Version 2 combines all the .debug_info, etc. sections into one,
11951    and the entries in the index tables are now offsets into these sections.
11952    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11953    section.
11954
11955    Index Section Contents:
11956     Header
11957     Hash Table of Signatures   dwp_hash_table.hash_table
11958     Parallel Table of Indices  dwp_hash_table.unit_table
11959     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11960     Table of Section Sizes     dwp_hash_table.v2.sizes
11961
11962    The index section header consists of:
11963
11964     V, 32 bit version number
11965     L, 32 bit number of columns in the table of section offsets
11966     N, 32 bit number of compilation units or type units in the index
11967     M, 32 bit number of slots in the hash table
11968
11969    Numbers are recorded using the byte order of the application binary.
11970
11971    The hash table has the same format as version 1.
11972    The parallel table of indices has the same format as version 1,
11973    except that the entries are origin-1 indices into the table of sections
11974    offsets and the table of section sizes.
11975
11976    The table of offsets begins immediately following the parallel table
11977    (at offset 16 + 12 * M from the beginning of the section).  The table is
11978    a two-dimensional array of 32-bit words (using the byte order of the
11979    application binary), with L columns and N+1 rows, in row-major order.
11980    Each row in the array is indexed starting from 0.  The first row provides
11981    a key to the remaining rows: each column in this row provides an identifier
11982    for a debug section, and the offsets in the same column of subsequent rows
11983    refer to that section.  The section identifiers are:
11984
11985     DW_SECT_INFO         1  .debug_info.dwo
11986     DW_SECT_TYPES        2  .debug_types.dwo
11987     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11988     DW_SECT_LINE         4  .debug_line.dwo
11989     DW_SECT_LOC          5  .debug_loc.dwo
11990     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11991     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11992     DW_SECT_MACRO        8  .debug_macro.dwo
11993
11994    The offsets provided by the CU and TU index sections are the base offsets
11995    for the contributions made by each CU or TU to the corresponding section
11996    in the package file.  Each CU and TU header contains an abbrev_offset
11997    field, used to find the abbreviations table for that CU or TU within the
11998    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11999    be interpreted as relative to the base offset given in the index section.
12000    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12001    should be interpreted as relative to the base offset for .debug_line.dwo,
12002    and offsets into other debug sections obtained from DWARF attributes should
12003    also be interpreted as relative to the corresponding base offset.
12004
12005    The table of sizes begins immediately following the table of offsets.
12006    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12007    with L columns and N rows, in row-major order.  Each row in the array is
12008    indexed starting from 1 (row 0 is shared by the two tables).
12009
12010    ---
12011
12012    Hash table lookup is handled the same in version 1 and 2:
12013
12014    We assume that N and M will not exceed 2^32 - 1.
12015    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12016
12017    Given a 64-bit compilation unit signature or a type signature S, an entry
12018    in the hash table is located as follows:
12019
12020    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12021       the low-order k bits all set to 1.
12022
12023    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12024
12025    3) If the hash table entry at index H matches the signature, use that
12026       entry.  If the hash table entry at index H is unused (all zeroes),
12027       terminate the search: the signature is not present in the table.
12028
12029    4) Let H = (H + H') modulo M. Repeat at Step 3.
12030
12031    Because M > N and H' and M are relatively prime, the search is guaranteed
12032    to stop at an unused slot or find the match.  */
12033
12034 /* Create a hash table to map DWO IDs to their CU/TU entry in
12035    .debug_{info,types}.dwo in DWP_FILE.
12036    Returns NULL if there isn't one.
12037    Note: This function processes DWP files only, not DWO files.  */
12038
12039 static struct dwp_hash_table *
12040 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12041                        struct dwp_file *dwp_file, int is_debug_types)
12042 {
12043   struct objfile *objfile = dwarf2_per_objfile->objfile;
12044   bfd *dbfd = dwp_file->dbfd.get ();
12045   const gdb_byte *index_ptr, *index_end;
12046   struct dwarf2_section_info *index;
12047   uint32_t version, nr_columns, nr_units, nr_slots;
12048   struct dwp_hash_table *htab;
12049
12050   if (is_debug_types)
12051     index = &dwp_file->sections.tu_index;
12052   else
12053     index = &dwp_file->sections.cu_index;
12054
12055   if (dwarf2_section_empty_p (index))
12056     return NULL;
12057   dwarf2_read_section (objfile, index);
12058
12059   index_ptr = index->buffer;
12060   index_end = index_ptr + index->size;
12061
12062   version = read_4_bytes (dbfd, index_ptr);
12063   index_ptr += 4;
12064   if (version == 2)
12065     nr_columns = read_4_bytes (dbfd, index_ptr);
12066   else
12067     nr_columns = 0;
12068   index_ptr += 4;
12069   nr_units = read_4_bytes (dbfd, index_ptr);
12070   index_ptr += 4;
12071   nr_slots = read_4_bytes (dbfd, index_ptr);
12072   index_ptr += 4;
12073
12074   if (version != 1 && version != 2)
12075     {
12076       error (_("Dwarf Error: unsupported DWP file version (%s)"
12077                " [in module %s]"),
12078              pulongest (version), dwp_file->name);
12079     }
12080   if (nr_slots != (nr_slots & -nr_slots))
12081     {
12082       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12083                " is not power of 2 [in module %s]"),
12084              pulongest (nr_slots), dwp_file->name);
12085     }
12086
12087   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12088   htab->version = version;
12089   htab->nr_columns = nr_columns;
12090   htab->nr_units = nr_units;
12091   htab->nr_slots = nr_slots;
12092   htab->hash_table = index_ptr;
12093   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12094
12095   /* Exit early if the table is empty.  */
12096   if (nr_slots == 0 || nr_units == 0
12097       || (version == 2 && nr_columns == 0))
12098     {
12099       /* All must be zero.  */
12100       if (nr_slots != 0 || nr_units != 0
12101           || (version == 2 && nr_columns != 0))
12102         {
12103           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12104                        " all zero [in modules %s]"),
12105                      dwp_file->name);
12106         }
12107       return htab;
12108     }
12109
12110   if (version == 1)
12111     {
12112       htab->section_pool.v1.indices =
12113         htab->unit_table + sizeof (uint32_t) * nr_slots;
12114       /* It's harder to decide whether the section is too small in v1.
12115          V1 is deprecated anyway so we punt.  */
12116     }
12117   else
12118     {
12119       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12120       int *ids = htab->section_pool.v2.section_ids;
12121       /* Reverse map for error checking.  */
12122       int ids_seen[DW_SECT_MAX + 1];
12123       int i;
12124
12125       if (nr_columns < 2)
12126         {
12127           error (_("Dwarf Error: bad DWP hash table, too few columns"
12128                    " in section table [in module %s]"),
12129                  dwp_file->name);
12130         }
12131       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12132         {
12133           error (_("Dwarf Error: bad DWP hash table, too many columns"
12134                    " in section table [in module %s]"),
12135                  dwp_file->name);
12136         }
12137       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12138       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12139       for (i = 0; i < nr_columns; ++i)
12140         {
12141           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12142
12143           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12144             {
12145               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12146                        " in section table [in module %s]"),
12147                      id, dwp_file->name);
12148             }
12149           if (ids_seen[id] != -1)
12150             {
12151               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12152                        " id %d in section table [in module %s]"),
12153                      id, dwp_file->name);
12154             }
12155           ids_seen[id] = i;
12156           ids[i] = id;
12157         }
12158       /* Must have exactly one info or types section.  */
12159       if (((ids_seen[DW_SECT_INFO] != -1)
12160            + (ids_seen[DW_SECT_TYPES] != -1))
12161           != 1)
12162         {
12163           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12164                    " DWO info/types section [in module %s]"),
12165                  dwp_file->name);
12166         }
12167       /* Must have an abbrev section.  */
12168       if (ids_seen[DW_SECT_ABBREV] == -1)
12169         {
12170           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12171                    " section [in module %s]"),
12172                  dwp_file->name);
12173         }
12174       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12175       htab->section_pool.v2.sizes =
12176         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12177                                          * nr_units * nr_columns);
12178       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12179                                           * nr_units * nr_columns))
12180           > index_end)
12181         {
12182           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12183                    " [in module %s]"),
12184                  dwp_file->name);
12185         }
12186     }
12187
12188   return htab;
12189 }
12190
12191 /* Update SECTIONS with the data from SECTP.
12192
12193    This function is like the other "locate" section routines that are
12194    passed to bfd_map_over_sections, but in this context the sections to
12195    read comes from the DWP V1 hash table, not the full ELF section table.
12196
12197    The result is non-zero for success, or zero if an error was found.  */
12198
12199 static int
12200 locate_v1_virtual_dwo_sections (asection *sectp,
12201                                 struct virtual_v1_dwo_sections *sections)
12202 {
12203   const struct dwop_section_names *names = &dwop_section_names;
12204
12205   if (section_is_p (sectp->name, &names->abbrev_dwo))
12206     {
12207       /* There can be only one.  */
12208       if (sections->abbrev.s.section != NULL)
12209         return 0;
12210       sections->abbrev.s.section = sectp;
12211       sections->abbrev.size = bfd_get_section_size (sectp);
12212     }
12213   else if (section_is_p (sectp->name, &names->info_dwo)
12214            || section_is_p (sectp->name, &names->types_dwo))
12215     {
12216       /* There can be only one.  */
12217       if (sections->info_or_types.s.section != NULL)
12218         return 0;
12219       sections->info_or_types.s.section = sectp;
12220       sections->info_or_types.size = bfd_get_section_size (sectp);
12221     }
12222   else if (section_is_p (sectp->name, &names->line_dwo))
12223     {
12224       /* There can be only one.  */
12225       if (sections->line.s.section != NULL)
12226         return 0;
12227       sections->line.s.section = sectp;
12228       sections->line.size = bfd_get_section_size (sectp);
12229     }
12230   else if (section_is_p (sectp->name, &names->loc_dwo))
12231     {
12232       /* There can be only one.  */
12233       if (sections->loc.s.section != NULL)
12234         return 0;
12235       sections->loc.s.section = sectp;
12236       sections->loc.size = bfd_get_section_size (sectp);
12237     }
12238   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12239     {
12240       /* There can be only one.  */
12241       if (sections->macinfo.s.section != NULL)
12242         return 0;
12243       sections->macinfo.s.section = sectp;
12244       sections->macinfo.size = bfd_get_section_size (sectp);
12245     }
12246   else if (section_is_p (sectp->name, &names->macro_dwo))
12247     {
12248       /* There can be only one.  */
12249       if (sections->macro.s.section != NULL)
12250         return 0;
12251       sections->macro.s.section = sectp;
12252       sections->macro.size = bfd_get_section_size (sectp);
12253     }
12254   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12255     {
12256       /* There can be only one.  */
12257       if (sections->str_offsets.s.section != NULL)
12258         return 0;
12259       sections->str_offsets.s.section = sectp;
12260       sections->str_offsets.size = bfd_get_section_size (sectp);
12261     }
12262   else
12263     {
12264       /* No other kind of section is valid.  */
12265       return 0;
12266     }
12267
12268   return 1;
12269 }
12270
12271 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12272    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12273    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12274    This is for DWP version 1 files.  */
12275
12276 static struct dwo_unit *
12277 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12278                            struct dwp_file *dwp_file,
12279                            uint32_t unit_index,
12280                            const char *comp_dir,
12281                            ULONGEST signature, int is_debug_types)
12282 {
12283   struct objfile *objfile = dwarf2_per_objfile->objfile;
12284   const struct dwp_hash_table *dwp_htab =
12285     is_debug_types ? dwp_file->tus : dwp_file->cus;
12286   bfd *dbfd = dwp_file->dbfd.get ();
12287   const char *kind = is_debug_types ? "TU" : "CU";
12288   struct dwo_file *dwo_file;
12289   struct dwo_unit *dwo_unit;
12290   struct virtual_v1_dwo_sections sections;
12291   void **dwo_file_slot;
12292   int i;
12293
12294   gdb_assert (dwp_file->version == 1);
12295
12296   if (dwarf_read_debug)
12297     {
12298       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12299                           kind,
12300                           pulongest (unit_index), hex_string (signature),
12301                           dwp_file->name);
12302     }
12303
12304   /* Fetch the sections of this DWO unit.
12305      Put a limit on the number of sections we look for so that bad data
12306      doesn't cause us to loop forever.  */
12307
12308 #define MAX_NR_V1_DWO_SECTIONS \
12309   (1 /* .debug_info or .debug_types */ \
12310    + 1 /* .debug_abbrev */ \
12311    + 1 /* .debug_line */ \
12312    + 1 /* .debug_loc */ \
12313    + 1 /* .debug_str_offsets */ \
12314    + 1 /* .debug_macro or .debug_macinfo */ \
12315    + 1 /* trailing zero */)
12316
12317   memset (&sections, 0, sizeof (sections));
12318
12319   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12320     {
12321       asection *sectp;
12322       uint32_t section_nr =
12323         read_4_bytes (dbfd,
12324                       dwp_htab->section_pool.v1.indices
12325                       + (unit_index + i) * sizeof (uint32_t));
12326
12327       if (section_nr == 0)
12328         break;
12329       if (section_nr >= dwp_file->num_sections)
12330         {
12331           error (_("Dwarf Error: bad DWP hash table, section number too large"
12332                    " [in module %s]"),
12333                  dwp_file->name);
12334         }
12335
12336       sectp = dwp_file->elf_sections[section_nr];
12337       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12338         {
12339           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12340                    " [in module %s]"),
12341                  dwp_file->name);
12342         }
12343     }
12344
12345   if (i < 2
12346       || dwarf2_section_empty_p (&sections.info_or_types)
12347       || dwarf2_section_empty_p (&sections.abbrev))
12348     {
12349       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12350                " [in module %s]"),
12351              dwp_file->name);
12352     }
12353   if (i == MAX_NR_V1_DWO_SECTIONS)
12354     {
12355       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12356                " [in module %s]"),
12357              dwp_file->name);
12358     }
12359
12360   /* It's easier for the rest of the code if we fake a struct dwo_file and
12361      have dwo_unit "live" in that.  At least for now.
12362
12363      The DWP file can be made up of a random collection of CUs and TUs.
12364      However, for each CU + set of TUs that came from the same original DWO
12365      file, we can combine them back into a virtual DWO file to save space
12366      (fewer struct dwo_file objects to allocate).  Remember that for really
12367      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12368
12369   std::string virtual_dwo_name =
12370     string_printf ("virtual-dwo/%d-%d-%d-%d",
12371                    get_section_id (&sections.abbrev),
12372                    get_section_id (&sections.line),
12373                    get_section_id (&sections.loc),
12374                    get_section_id (&sections.str_offsets));
12375   /* Can we use an existing virtual DWO file?  */
12376   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12377                                         virtual_dwo_name.c_str (),
12378                                         comp_dir);
12379   /* Create one if necessary.  */
12380   if (*dwo_file_slot == NULL)
12381     {
12382       if (dwarf_read_debug)
12383         {
12384           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12385                               virtual_dwo_name.c_str ());
12386         }
12387       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12388       dwo_file->dwo_name
12389         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12390                                         virtual_dwo_name.c_str (),
12391                                         virtual_dwo_name.size ());
12392       dwo_file->comp_dir = comp_dir;
12393       dwo_file->sections.abbrev = sections.abbrev;
12394       dwo_file->sections.line = sections.line;
12395       dwo_file->sections.loc = sections.loc;
12396       dwo_file->sections.macinfo = sections.macinfo;
12397       dwo_file->sections.macro = sections.macro;
12398       dwo_file->sections.str_offsets = sections.str_offsets;
12399       /* The "str" section is global to the entire DWP file.  */
12400       dwo_file->sections.str = dwp_file->sections.str;
12401       /* The info or types section is assigned below to dwo_unit,
12402          there's no need to record it in dwo_file.
12403          Also, we can't simply record type sections in dwo_file because
12404          we record a pointer into the vector in dwo_unit.  As we collect more
12405          types we'll grow the vector and eventually have to reallocate space
12406          for it, invalidating all copies of pointers into the previous
12407          contents.  */
12408       *dwo_file_slot = dwo_file;
12409     }
12410   else
12411     {
12412       if (dwarf_read_debug)
12413         {
12414           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12415                               virtual_dwo_name.c_str ());
12416         }
12417       dwo_file = (struct dwo_file *) *dwo_file_slot;
12418     }
12419
12420   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12421   dwo_unit->dwo_file = dwo_file;
12422   dwo_unit->signature = signature;
12423   dwo_unit->section =
12424     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12425   *dwo_unit->section = sections.info_or_types;
12426   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12427
12428   return dwo_unit;
12429 }
12430
12431 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12432    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12433    piece within that section used by a TU/CU, return a virtual section
12434    of just that piece.  */
12435
12436 static struct dwarf2_section_info
12437 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12438                        struct dwarf2_section_info *section,
12439                        bfd_size_type offset, bfd_size_type size)
12440 {
12441   struct dwarf2_section_info result;
12442   asection *sectp;
12443
12444   gdb_assert (section != NULL);
12445   gdb_assert (!section->is_virtual);
12446
12447   memset (&result, 0, sizeof (result));
12448   result.s.containing_section = section;
12449   result.is_virtual = 1;
12450
12451   if (size == 0)
12452     return result;
12453
12454   sectp = get_section_bfd_section (section);
12455
12456   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12457      bounds of the real section.  This is a pretty-rare event, so just
12458      flag an error (easier) instead of a warning and trying to cope.  */
12459   if (sectp == NULL
12460       || offset + size > bfd_get_section_size (sectp))
12461     {
12462       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12463                " in section %s [in module %s]"),
12464              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12465              objfile_name (dwarf2_per_objfile->objfile));
12466     }
12467
12468   result.virtual_offset = offset;
12469   result.size = size;
12470   return result;
12471 }
12472
12473 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12474    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12475    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12476    This is for DWP version 2 files.  */
12477
12478 static struct dwo_unit *
12479 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12480                            struct dwp_file *dwp_file,
12481                            uint32_t unit_index,
12482                            const char *comp_dir,
12483                            ULONGEST signature, int is_debug_types)
12484 {
12485   struct objfile *objfile = dwarf2_per_objfile->objfile;
12486   const struct dwp_hash_table *dwp_htab =
12487     is_debug_types ? dwp_file->tus : dwp_file->cus;
12488   bfd *dbfd = dwp_file->dbfd.get ();
12489   const char *kind = is_debug_types ? "TU" : "CU";
12490   struct dwo_file *dwo_file;
12491   struct dwo_unit *dwo_unit;
12492   struct virtual_v2_dwo_sections sections;
12493   void **dwo_file_slot;
12494   int i;
12495
12496   gdb_assert (dwp_file->version == 2);
12497
12498   if (dwarf_read_debug)
12499     {
12500       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12501                           kind,
12502                           pulongest (unit_index), hex_string (signature),
12503                           dwp_file->name);
12504     }
12505
12506   /* Fetch the section offsets of this DWO unit.  */
12507
12508   memset (&sections, 0, sizeof (sections));
12509
12510   for (i = 0; i < dwp_htab->nr_columns; ++i)
12511     {
12512       uint32_t offset = read_4_bytes (dbfd,
12513                                       dwp_htab->section_pool.v2.offsets
12514                                       + (((unit_index - 1) * dwp_htab->nr_columns
12515                                           + i)
12516                                          * sizeof (uint32_t)));
12517       uint32_t size = read_4_bytes (dbfd,
12518                                     dwp_htab->section_pool.v2.sizes
12519                                     + (((unit_index - 1) * dwp_htab->nr_columns
12520                                         + i)
12521                                        * sizeof (uint32_t)));
12522
12523       switch (dwp_htab->section_pool.v2.section_ids[i])
12524         {
12525         case DW_SECT_INFO:
12526         case DW_SECT_TYPES:
12527           sections.info_or_types_offset = offset;
12528           sections.info_or_types_size = size;
12529           break;
12530         case DW_SECT_ABBREV:
12531           sections.abbrev_offset = offset;
12532           sections.abbrev_size = size;
12533           break;
12534         case DW_SECT_LINE:
12535           sections.line_offset = offset;
12536           sections.line_size = size;
12537           break;
12538         case DW_SECT_LOC:
12539           sections.loc_offset = offset;
12540           sections.loc_size = size;
12541           break;
12542         case DW_SECT_STR_OFFSETS:
12543           sections.str_offsets_offset = offset;
12544           sections.str_offsets_size = size;
12545           break;
12546         case DW_SECT_MACINFO:
12547           sections.macinfo_offset = offset;
12548           sections.macinfo_size = size;
12549           break;
12550         case DW_SECT_MACRO:
12551           sections.macro_offset = offset;
12552           sections.macro_size = size;
12553           break;
12554         }
12555     }
12556
12557   /* It's easier for the rest of the code if we fake a struct dwo_file and
12558      have dwo_unit "live" in that.  At least for now.
12559
12560      The DWP file can be made up of a random collection of CUs and TUs.
12561      However, for each CU + set of TUs that came from the same original DWO
12562      file, we can combine them back into a virtual DWO file to save space
12563      (fewer struct dwo_file objects to allocate).  Remember that for really
12564      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12565
12566   std::string virtual_dwo_name =
12567     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12568                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12569                    (long) (sections.line_size ? sections.line_offset : 0),
12570                    (long) (sections.loc_size ? sections.loc_offset : 0),
12571                    (long) (sections.str_offsets_size
12572                            ? sections.str_offsets_offset : 0));
12573   /* Can we use an existing virtual DWO file?  */
12574   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12575                                         virtual_dwo_name.c_str (),
12576                                         comp_dir);
12577   /* Create one if necessary.  */
12578   if (*dwo_file_slot == NULL)
12579     {
12580       if (dwarf_read_debug)
12581         {
12582           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12583                               virtual_dwo_name.c_str ());
12584         }
12585       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12586       dwo_file->dwo_name
12587         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12588                                         virtual_dwo_name.c_str (),
12589                                         virtual_dwo_name.size ());
12590       dwo_file->comp_dir = comp_dir;
12591       dwo_file->sections.abbrev =
12592         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12593                                sections.abbrev_offset, sections.abbrev_size);
12594       dwo_file->sections.line =
12595         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12596                                sections.line_offset, sections.line_size);
12597       dwo_file->sections.loc =
12598         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12599                                sections.loc_offset, sections.loc_size);
12600       dwo_file->sections.macinfo =
12601         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12602                                sections.macinfo_offset, sections.macinfo_size);
12603       dwo_file->sections.macro =
12604         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12605                                sections.macro_offset, sections.macro_size);
12606       dwo_file->sections.str_offsets =
12607         create_dwp_v2_section (dwarf2_per_objfile,
12608                                &dwp_file->sections.str_offsets,
12609                                sections.str_offsets_offset,
12610                                sections.str_offsets_size);
12611       /* The "str" section is global to the entire DWP file.  */
12612       dwo_file->sections.str = dwp_file->sections.str;
12613       /* The info or types section is assigned below to dwo_unit,
12614          there's no need to record it in dwo_file.
12615          Also, we can't simply record type sections in dwo_file because
12616          we record a pointer into the vector in dwo_unit.  As we collect more
12617          types we'll grow the vector and eventually have to reallocate space
12618          for it, invalidating all copies of pointers into the previous
12619          contents.  */
12620       *dwo_file_slot = dwo_file;
12621     }
12622   else
12623     {
12624       if (dwarf_read_debug)
12625         {
12626           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12627                               virtual_dwo_name.c_str ());
12628         }
12629       dwo_file = (struct dwo_file *) *dwo_file_slot;
12630     }
12631
12632   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12633   dwo_unit->dwo_file = dwo_file;
12634   dwo_unit->signature = signature;
12635   dwo_unit->section =
12636     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12637   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12638                                               is_debug_types
12639                                               ? &dwp_file->sections.types
12640                                               : &dwp_file->sections.info,
12641                                               sections.info_or_types_offset,
12642                                               sections.info_or_types_size);
12643   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12644
12645   return dwo_unit;
12646 }
12647
12648 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12649    Returns NULL if the signature isn't found.  */
12650
12651 static struct dwo_unit *
12652 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12653                         struct dwp_file *dwp_file, const char *comp_dir,
12654                         ULONGEST signature, int is_debug_types)
12655 {
12656   const struct dwp_hash_table *dwp_htab =
12657     is_debug_types ? dwp_file->tus : dwp_file->cus;
12658   bfd *dbfd = dwp_file->dbfd.get ();
12659   uint32_t mask = dwp_htab->nr_slots - 1;
12660   uint32_t hash = signature & mask;
12661   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12662   unsigned int i;
12663   void **slot;
12664   struct dwo_unit find_dwo_cu;
12665
12666   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12667   find_dwo_cu.signature = signature;
12668   slot = htab_find_slot (is_debug_types
12669                          ? dwp_file->loaded_tus
12670                          : dwp_file->loaded_cus,
12671                          &find_dwo_cu, INSERT);
12672
12673   if (*slot != NULL)
12674     return (struct dwo_unit *) *slot;
12675
12676   /* Use a for loop so that we don't loop forever on bad debug info.  */
12677   for (i = 0; i < dwp_htab->nr_slots; ++i)
12678     {
12679       ULONGEST signature_in_table;
12680
12681       signature_in_table =
12682         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12683       if (signature_in_table == signature)
12684         {
12685           uint32_t unit_index =
12686             read_4_bytes (dbfd,
12687                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12688
12689           if (dwp_file->version == 1)
12690             {
12691               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12692                                                  dwp_file, unit_index,
12693                                                  comp_dir, signature,
12694                                                  is_debug_types);
12695             }
12696           else
12697             {
12698               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12699                                                  dwp_file, unit_index,
12700                                                  comp_dir, signature,
12701                                                  is_debug_types);
12702             }
12703           return (struct dwo_unit *) *slot;
12704         }
12705       if (signature_in_table == 0)
12706         return NULL;
12707       hash = (hash + hash2) & mask;
12708     }
12709
12710   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12711            " [in module %s]"),
12712          dwp_file->name);
12713 }
12714
12715 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12716    Open the file specified by FILE_NAME and hand it off to BFD for
12717    preliminary analysis.  Return a newly initialized bfd *, which
12718    includes a canonicalized copy of FILE_NAME.
12719    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12720    SEARCH_CWD is true if the current directory is to be searched.
12721    It will be searched before debug-file-directory.
12722    If successful, the file is added to the bfd include table of the
12723    objfile's bfd (see gdb_bfd_record_inclusion).
12724    If unable to find/open the file, return NULL.
12725    NOTE: This function is derived from symfile_bfd_open.  */
12726
12727 static gdb_bfd_ref_ptr
12728 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12729                     const char *file_name, int is_dwp, int search_cwd)
12730 {
12731   int desc;
12732   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12733      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12734      to debug_file_directory.  */
12735   const char *search_path;
12736   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12737
12738   gdb::unique_xmalloc_ptr<char> search_path_holder;
12739   if (search_cwd)
12740     {
12741       if (*debug_file_directory != '\0')
12742         {
12743           search_path_holder.reset (concat (".", dirname_separator_string,
12744                                             debug_file_directory,
12745                                             (char *) NULL));
12746           search_path = search_path_holder.get ();
12747         }
12748       else
12749         search_path = ".";
12750     }
12751   else
12752     search_path = debug_file_directory;
12753
12754   openp_flags flags = OPF_RETURN_REALPATH;
12755   if (is_dwp)
12756     flags |= OPF_SEARCH_IN_PATH;
12757
12758   gdb::unique_xmalloc_ptr<char> absolute_name;
12759   desc = openp (search_path, flags, file_name,
12760                 O_RDONLY | O_BINARY, &absolute_name);
12761   if (desc < 0)
12762     return NULL;
12763
12764   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12765                                          gnutarget, desc));
12766   if (sym_bfd == NULL)
12767     return NULL;
12768   bfd_set_cacheable (sym_bfd.get (), 1);
12769
12770   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12771     return NULL;
12772
12773   /* Success.  Record the bfd as having been included by the objfile's bfd.
12774      This is important because things like demangled_names_hash lives in the
12775      objfile's per_bfd space and may have references to things like symbol
12776      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12777   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12778
12779   return sym_bfd;
12780 }
12781
12782 /* Try to open DWO file FILE_NAME.
12783    COMP_DIR is the DW_AT_comp_dir attribute.
12784    The result is the bfd handle of the file.
12785    If there is a problem finding or opening the file, return NULL.
12786    Upon success, the canonicalized path of the file is stored in the bfd,
12787    same as symfile_bfd_open.  */
12788
12789 static gdb_bfd_ref_ptr
12790 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12791                const char *file_name, const char *comp_dir)
12792 {
12793   if (IS_ABSOLUTE_PATH (file_name))
12794     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12795                                0 /*is_dwp*/, 0 /*search_cwd*/);
12796
12797   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12798
12799   if (comp_dir != NULL)
12800     {
12801       char *path_to_try = concat (comp_dir, SLASH_STRING,
12802                                   file_name, (char *) NULL);
12803
12804       /* NOTE: If comp_dir is a relative path, this will also try the
12805          search path, which seems useful.  */
12806       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12807                                                 path_to_try,
12808                                                 0 /*is_dwp*/,
12809                                                 1 /*search_cwd*/));
12810       xfree (path_to_try);
12811       if (abfd != NULL)
12812         return abfd;
12813     }
12814
12815   /* That didn't work, try debug-file-directory, which, despite its name,
12816      is a list of paths.  */
12817
12818   if (*debug_file_directory == '\0')
12819     return NULL;
12820
12821   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12822                              0 /*is_dwp*/, 1 /*search_cwd*/);
12823 }
12824
12825 /* This function is mapped across the sections and remembers the offset and
12826    size of each of the DWO debugging sections we are interested in.  */
12827
12828 static void
12829 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12830 {
12831   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12832   const struct dwop_section_names *names = &dwop_section_names;
12833
12834   if (section_is_p (sectp->name, &names->abbrev_dwo))
12835     {
12836       dwo_sections->abbrev.s.section = sectp;
12837       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12838     }
12839   else if (section_is_p (sectp->name, &names->info_dwo))
12840     {
12841       dwo_sections->info.s.section = sectp;
12842       dwo_sections->info.size = bfd_get_section_size (sectp);
12843     }
12844   else if (section_is_p (sectp->name, &names->line_dwo))
12845     {
12846       dwo_sections->line.s.section = sectp;
12847       dwo_sections->line.size = bfd_get_section_size (sectp);
12848     }
12849   else if (section_is_p (sectp->name, &names->loc_dwo))
12850     {
12851       dwo_sections->loc.s.section = sectp;
12852       dwo_sections->loc.size = bfd_get_section_size (sectp);
12853     }
12854   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12855     {
12856       dwo_sections->macinfo.s.section = sectp;
12857       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12858     }
12859   else if (section_is_p (sectp->name, &names->macro_dwo))
12860     {
12861       dwo_sections->macro.s.section = sectp;
12862       dwo_sections->macro.size = bfd_get_section_size (sectp);
12863     }
12864   else if (section_is_p (sectp->name, &names->str_dwo))
12865     {
12866       dwo_sections->str.s.section = sectp;
12867       dwo_sections->str.size = bfd_get_section_size (sectp);
12868     }
12869   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12870     {
12871       dwo_sections->str_offsets.s.section = sectp;
12872       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12873     }
12874   else if (section_is_p (sectp->name, &names->types_dwo))
12875     {
12876       struct dwarf2_section_info type_section;
12877
12878       memset (&type_section, 0, sizeof (type_section));
12879       type_section.s.section = sectp;
12880       type_section.size = bfd_get_section_size (sectp);
12881       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12882                      &type_section);
12883     }
12884 }
12885
12886 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12887    by PER_CU.  This is for the non-DWP case.
12888    The result is NULL if DWO_NAME can't be found.  */
12889
12890 static struct dwo_file *
12891 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12892                         const char *dwo_name, const char *comp_dir)
12893 {
12894   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12895   struct objfile *objfile = dwarf2_per_objfile->objfile;
12896
12897   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12898   if (dbfd == NULL)
12899     {
12900       if (dwarf_read_debug)
12901         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12902       return NULL;
12903     }
12904
12905   /* We use a unique pointer here, despite the obstack allocation,
12906      because a dwo_file needs some cleanup if it is abandoned.  */
12907   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12908                                         struct dwo_file));
12909   dwo_file->dwo_name = dwo_name;
12910   dwo_file->comp_dir = comp_dir;
12911   dwo_file->dbfd = dbfd.release ();
12912
12913   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12914                          &dwo_file->sections);
12915
12916   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12917                          dwo_file->cus);
12918
12919   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12920                                  dwo_file->sections.types, dwo_file->tus);
12921
12922   if (dwarf_read_debug)
12923     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12924
12925   return dwo_file.release ();
12926 }
12927
12928 /* This function is mapped across the sections and remembers the offset and
12929    size of each of the DWP debugging sections common to version 1 and 2 that
12930    we are interested in.  */
12931
12932 static void
12933 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12934                                    void *dwp_file_ptr)
12935 {
12936   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12937   const struct dwop_section_names *names = &dwop_section_names;
12938   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12939
12940   /* Record the ELF section number for later lookup: this is what the
12941      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12942   gdb_assert (elf_section_nr < dwp_file->num_sections);
12943   dwp_file->elf_sections[elf_section_nr] = sectp;
12944
12945   /* Look for specific sections that we need.  */
12946   if (section_is_p (sectp->name, &names->str_dwo))
12947     {
12948       dwp_file->sections.str.s.section = sectp;
12949       dwp_file->sections.str.size = bfd_get_section_size (sectp);
12950     }
12951   else if (section_is_p (sectp->name, &names->cu_index))
12952     {
12953       dwp_file->sections.cu_index.s.section = sectp;
12954       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
12955     }
12956   else if (section_is_p (sectp->name, &names->tu_index))
12957     {
12958       dwp_file->sections.tu_index.s.section = sectp;
12959       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
12960     }
12961 }
12962
12963 /* This function is mapped across the sections and remembers the offset and
12964    size of each of the DWP version 2 debugging sections that we are interested
12965    in.  This is split into a separate function because we don't know if we
12966    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12967
12968 static void
12969 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12970 {
12971   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12972   const struct dwop_section_names *names = &dwop_section_names;
12973   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12974
12975   /* Record the ELF section number for later lookup: this is what the
12976      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12977   gdb_assert (elf_section_nr < dwp_file->num_sections);
12978   dwp_file->elf_sections[elf_section_nr] = sectp;
12979
12980   /* Look for specific sections that we need.  */
12981   if (section_is_p (sectp->name, &names->abbrev_dwo))
12982     {
12983       dwp_file->sections.abbrev.s.section = sectp;
12984       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
12985     }
12986   else if (section_is_p (sectp->name, &names->info_dwo))
12987     {
12988       dwp_file->sections.info.s.section = sectp;
12989       dwp_file->sections.info.size = bfd_get_section_size (sectp);
12990     }
12991   else if (section_is_p (sectp->name, &names->line_dwo))
12992     {
12993       dwp_file->sections.line.s.section = sectp;
12994       dwp_file->sections.line.size = bfd_get_section_size (sectp);
12995     }
12996   else if (section_is_p (sectp->name, &names->loc_dwo))
12997     {
12998       dwp_file->sections.loc.s.section = sectp;
12999       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13000     }
13001   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13002     {
13003       dwp_file->sections.macinfo.s.section = sectp;
13004       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13005     }
13006   else if (section_is_p (sectp->name, &names->macro_dwo))
13007     {
13008       dwp_file->sections.macro.s.section = sectp;
13009       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13010     }
13011   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13012     {
13013       dwp_file->sections.str_offsets.s.section = sectp;
13014       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13015     }
13016   else if (section_is_p (sectp->name, &names->types_dwo))
13017     {
13018       dwp_file->sections.types.s.section = sectp;
13019       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13020     }
13021 }
13022
13023 /* Hash function for dwp_file loaded CUs/TUs.  */
13024
13025 static hashval_t
13026 hash_dwp_loaded_cutus (const void *item)
13027 {
13028   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13029
13030   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13031   return dwo_unit->signature;
13032 }
13033
13034 /* Equality function for dwp_file loaded CUs/TUs.  */
13035
13036 static int
13037 eq_dwp_loaded_cutus (const void *a, const void *b)
13038 {
13039   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13040   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13041
13042   return dua->signature == dub->signature;
13043 }
13044
13045 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13046
13047 static htab_t
13048 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13049 {
13050   return htab_create_alloc_ex (3,
13051                                hash_dwp_loaded_cutus,
13052                                eq_dwp_loaded_cutus,
13053                                NULL,
13054                                &objfile->objfile_obstack,
13055                                hashtab_obstack_allocate,
13056                                dummy_obstack_deallocate);
13057 }
13058
13059 /* Try to open DWP file FILE_NAME.
13060    The result is the bfd handle of the file.
13061    If there is a problem finding or opening the file, return NULL.
13062    Upon success, the canonicalized path of the file is stored in the bfd,
13063    same as symfile_bfd_open.  */
13064
13065 static gdb_bfd_ref_ptr
13066 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13067                const char *file_name)
13068 {
13069   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13070                                             1 /*is_dwp*/,
13071                                             1 /*search_cwd*/));
13072   if (abfd != NULL)
13073     return abfd;
13074
13075   /* Work around upstream bug 15652.
13076      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13077      [Whether that's a "bug" is debatable, but it is getting in our way.]
13078      We have no real idea where the dwp file is, because gdb's realpath-ing
13079      of the executable's path may have discarded the needed info.
13080      [IWBN if the dwp file name was recorded in the executable, akin to
13081      .gnu_debuglink, but that doesn't exist yet.]
13082      Strip the directory from FILE_NAME and search again.  */
13083   if (*debug_file_directory != '\0')
13084     {
13085       /* Don't implicitly search the current directory here.
13086          If the user wants to search "." to handle this case,
13087          it must be added to debug-file-directory.  */
13088       return try_open_dwop_file (dwarf2_per_objfile,
13089                                  lbasename (file_name), 1 /*is_dwp*/,
13090                                  0 /*search_cwd*/);
13091     }
13092
13093   return NULL;
13094 }
13095
13096 /* Initialize the use of the DWP file for the current objfile.
13097    By convention the name of the DWP file is ${objfile}.dwp.
13098    The result is NULL if it can't be found.  */
13099
13100 static std::unique_ptr<struct dwp_file>
13101 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13102 {
13103   struct objfile *objfile = dwarf2_per_objfile->objfile;
13104
13105   /* Try to find first .dwp for the binary file before any symbolic links
13106      resolving.  */
13107
13108   /* If the objfile is a debug file, find the name of the real binary
13109      file and get the name of dwp file from there.  */
13110   std::string dwp_name;
13111   if (objfile->separate_debug_objfile_backlink != NULL)
13112     {
13113       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13114       const char *backlink_basename = lbasename (backlink->original_name);
13115
13116       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13117     }
13118   else
13119     dwp_name = objfile->original_name;
13120
13121   dwp_name += ".dwp";
13122
13123   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13124   if (dbfd == NULL
13125       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13126     {
13127       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13128       dwp_name = objfile_name (objfile);
13129       dwp_name += ".dwp";
13130       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13131     }
13132
13133   if (dbfd == NULL)
13134     {
13135       if (dwarf_read_debug)
13136         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13137       return std::unique_ptr<dwp_file> ();
13138     }
13139
13140   const char *name = bfd_get_filename (dbfd.get ());
13141   std::unique_ptr<struct dwp_file> dwp_file
13142     (new struct dwp_file (name, std::move (dbfd)));
13143
13144   /* +1: section 0 is unused */
13145   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13146   dwp_file->elf_sections =
13147     OBSTACK_CALLOC (&objfile->objfile_obstack,
13148                     dwp_file->num_sections, asection *);
13149
13150   bfd_map_over_sections (dwp_file->dbfd.get (),
13151                          dwarf2_locate_common_dwp_sections,
13152                          dwp_file.get ());
13153
13154   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13155                                          0);
13156
13157   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13158                                          1);
13159
13160   /* The DWP file version is stored in the hash table.  Oh well.  */
13161   if (dwp_file->cus && dwp_file->tus
13162       && dwp_file->cus->version != dwp_file->tus->version)
13163     {
13164       /* Technically speaking, we should try to limp along, but this is
13165          pretty bizarre.  We use pulongest here because that's the established
13166          portability solution (e.g, we cannot use %u for uint32_t).  */
13167       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13168                " TU version %s [in DWP file %s]"),
13169              pulongest (dwp_file->cus->version),
13170              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13171     }
13172
13173   if (dwp_file->cus)
13174     dwp_file->version = dwp_file->cus->version;
13175   else if (dwp_file->tus)
13176     dwp_file->version = dwp_file->tus->version;
13177   else
13178     dwp_file->version = 2;
13179
13180   if (dwp_file->version == 2)
13181     bfd_map_over_sections (dwp_file->dbfd.get (),
13182                            dwarf2_locate_v2_dwp_sections,
13183                            dwp_file.get ());
13184
13185   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13186   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13187
13188   if (dwarf_read_debug)
13189     {
13190       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13191       fprintf_unfiltered (gdb_stdlog,
13192                           "    %s CUs, %s TUs\n",
13193                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13194                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13195     }
13196
13197   return dwp_file;
13198 }
13199
13200 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13201
13202 static struct dwp_file *
13203 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13204 {
13205   if (! dwarf2_per_objfile->dwp_checked)
13206     {
13207       dwarf2_per_objfile->dwp_file
13208         = open_and_init_dwp_file (dwarf2_per_objfile);
13209       dwarf2_per_objfile->dwp_checked = 1;
13210     }
13211   return dwarf2_per_objfile->dwp_file.get ();
13212 }
13213
13214 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13215    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13216    or in the DWP file for the objfile, referenced by THIS_UNIT.
13217    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13218    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13219
13220    This is called, for example, when wanting to read a variable with a
13221    complex location.  Therefore we don't want to do file i/o for every call.
13222    Therefore we don't want to look for a DWO file on every call.
13223    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13224    then we check if we've already seen DWO_NAME, and only THEN do we check
13225    for a DWO file.
13226
13227    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13228    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13229
13230 static struct dwo_unit *
13231 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13232                  const char *dwo_name, const char *comp_dir,
13233                  ULONGEST signature, int is_debug_types)
13234 {
13235   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13236   struct objfile *objfile = dwarf2_per_objfile->objfile;
13237   const char *kind = is_debug_types ? "TU" : "CU";
13238   void **dwo_file_slot;
13239   struct dwo_file *dwo_file;
13240   struct dwp_file *dwp_file;
13241
13242   /* First see if there's a DWP file.
13243      If we have a DWP file but didn't find the DWO inside it, don't
13244      look for the original DWO file.  It makes gdb behave differently
13245      depending on whether one is debugging in the build tree.  */
13246
13247   dwp_file = get_dwp_file (dwarf2_per_objfile);
13248   if (dwp_file != NULL)
13249     {
13250       const struct dwp_hash_table *dwp_htab =
13251         is_debug_types ? dwp_file->tus : dwp_file->cus;
13252
13253       if (dwp_htab != NULL)
13254         {
13255           struct dwo_unit *dwo_cutu =
13256             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13257                                     signature, is_debug_types);
13258
13259           if (dwo_cutu != NULL)
13260             {
13261               if (dwarf_read_debug)
13262                 {
13263                   fprintf_unfiltered (gdb_stdlog,
13264                                       "Virtual DWO %s %s found: @%s\n",
13265                                       kind, hex_string (signature),
13266                                       host_address_to_string (dwo_cutu));
13267                 }
13268               return dwo_cutu;
13269             }
13270         }
13271     }
13272   else
13273     {
13274       /* No DWP file, look for the DWO file.  */
13275
13276       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13277                                             dwo_name, comp_dir);
13278       if (*dwo_file_slot == NULL)
13279         {
13280           /* Read in the file and build a table of the CUs/TUs it contains.  */
13281           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13282         }
13283       /* NOTE: This will be NULL if unable to open the file.  */
13284       dwo_file = (struct dwo_file *) *dwo_file_slot;
13285
13286       if (dwo_file != NULL)
13287         {
13288           struct dwo_unit *dwo_cutu = NULL;
13289
13290           if (is_debug_types && dwo_file->tus)
13291             {
13292               struct dwo_unit find_dwo_cutu;
13293
13294               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13295               find_dwo_cutu.signature = signature;
13296               dwo_cutu
13297                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13298             }
13299           else if (!is_debug_types && dwo_file->cus)
13300             {
13301               struct dwo_unit find_dwo_cutu;
13302
13303               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13304               find_dwo_cutu.signature = signature;
13305               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13306                                                        &find_dwo_cutu);
13307             }
13308
13309           if (dwo_cutu != NULL)
13310             {
13311               if (dwarf_read_debug)
13312                 {
13313                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13314                                       kind, dwo_name, hex_string (signature),
13315                                       host_address_to_string (dwo_cutu));
13316                 }
13317               return dwo_cutu;
13318             }
13319         }
13320     }
13321
13322   /* We didn't find it.  This could mean a dwo_id mismatch, or
13323      someone deleted the DWO/DWP file, or the search path isn't set up
13324      correctly to find the file.  */
13325
13326   if (dwarf_read_debug)
13327     {
13328       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13329                           kind, dwo_name, hex_string (signature));
13330     }
13331
13332   /* This is a warning and not a complaint because it can be caused by
13333      pilot error (e.g., user accidentally deleting the DWO).  */
13334   {
13335     /* Print the name of the DWP file if we looked there, helps the user
13336        better diagnose the problem.  */
13337     std::string dwp_text;
13338
13339     if (dwp_file != NULL)
13340       dwp_text = string_printf (" [in DWP file %s]",
13341                                 lbasename (dwp_file->name));
13342
13343     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13344                " [in module %s]"),
13345              kind, dwo_name, hex_string (signature),
13346              dwp_text.c_str (),
13347              this_unit->is_debug_types ? "TU" : "CU",
13348              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13349   }
13350   return NULL;
13351 }
13352
13353 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13354    See lookup_dwo_cutu_unit for details.  */
13355
13356 static struct dwo_unit *
13357 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13358                       const char *dwo_name, const char *comp_dir,
13359                       ULONGEST signature)
13360 {
13361   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13362 }
13363
13364 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13365    See lookup_dwo_cutu_unit for details.  */
13366
13367 static struct dwo_unit *
13368 lookup_dwo_type_unit (struct signatured_type *this_tu,
13369                       const char *dwo_name, const char *comp_dir)
13370 {
13371   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13372 }
13373
13374 /* Traversal function for queue_and_load_all_dwo_tus.  */
13375
13376 static int
13377 queue_and_load_dwo_tu (void **slot, void *info)
13378 {
13379   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13380   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13381   ULONGEST signature = dwo_unit->signature;
13382   struct signatured_type *sig_type =
13383     lookup_dwo_signatured_type (per_cu->cu, signature);
13384
13385   if (sig_type != NULL)
13386     {
13387       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13388
13389       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13390          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13391          while processing PER_CU.  */
13392       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13393         load_full_type_unit (sig_cu);
13394       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13395     }
13396
13397   return 1;
13398 }
13399
13400 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13401    The DWO may have the only definition of the type, though it may not be
13402    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13403    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13404
13405 static void
13406 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13407 {
13408   struct dwo_unit *dwo_unit;
13409   struct dwo_file *dwo_file;
13410
13411   gdb_assert (!per_cu->is_debug_types);
13412   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13413   gdb_assert (per_cu->cu != NULL);
13414
13415   dwo_unit = per_cu->cu->dwo_unit;
13416   gdb_assert (dwo_unit != NULL);
13417
13418   dwo_file = dwo_unit->dwo_file;
13419   if (dwo_file->tus != NULL)
13420     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13421 }
13422
13423 /* Free all resources associated with DWO_FILE.
13424    Close the DWO file and munmap the sections.  */
13425
13426 static void
13427 free_dwo_file (struct dwo_file *dwo_file)
13428 {
13429   /* Note: dbfd is NULL for virtual DWO files.  */
13430   gdb_bfd_unref (dwo_file->dbfd);
13431
13432   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13433 }
13434
13435 /* Traversal function for free_dwo_files.  */
13436
13437 static int
13438 free_dwo_file_from_slot (void **slot, void *info)
13439 {
13440   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13441
13442   free_dwo_file (dwo_file);
13443
13444   return 1;
13445 }
13446
13447 /* Free all resources associated with DWO_FILES.  */
13448
13449 static void
13450 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13451 {
13452   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13453 }
13454 \f
13455 /* Read in various DIEs.  */
13456
13457 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13458    Inherit only the children of the DW_AT_abstract_origin DIE not being
13459    already referenced by DW_AT_abstract_origin from the children of the
13460    current DIE.  */
13461
13462 static void
13463 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13464 {
13465   struct die_info *child_die;
13466   sect_offset *offsetp;
13467   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13468   struct die_info *origin_die;
13469   /* Iterator of the ORIGIN_DIE children.  */
13470   struct die_info *origin_child_die;
13471   struct attribute *attr;
13472   struct dwarf2_cu *origin_cu;
13473   struct pending **origin_previous_list_in_scope;
13474
13475   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13476   if (!attr)
13477     return;
13478
13479   /* Note that following die references may follow to a die in a
13480      different cu.  */
13481
13482   origin_cu = cu;
13483   origin_die = follow_die_ref (die, attr, &origin_cu);
13484
13485   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13486      symbols in.  */
13487   origin_previous_list_in_scope = origin_cu->list_in_scope;
13488   origin_cu->list_in_scope = cu->list_in_scope;
13489
13490   if (die->tag != origin_die->tag
13491       && !(die->tag == DW_TAG_inlined_subroutine
13492            && origin_die->tag == DW_TAG_subprogram))
13493     complaint (_("DIE %s and its abstract origin %s have different tags"),
13494                sect_offset_str (die->sect_off),
13495                sect_offset_str (origin_die->sect_off));
13496
13497   std::vector<sect_offset> offsets;
13498
13499   for (child_die = die->child;
13500        child_die && child_die->tag;
13501        child_die = sibling_die (child_die))
13502     {
13503       struct die_info *child_origin_die;
13504       struct dwarf2_cu *child_origin_cu;
13505
13506       /* We are trying to process concrete instance entries:
13507          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13508          it's not relevant to our analysis here. i.e. detecting DIEs that are
13509          present in the abstract instance but not referenced in the concrete
13510          one.  */
13511       if (child_die->tag == DW_TAG_call_site
13512           || child_die->tag == DW_TAG_GNU_call_site)
13513         continue;
13514
13515       /* For each CHILD_DIE, find the corresponding child of
13516          ORIGIN_DIE.  If there is more than one layer of
13517          DW_AT_abstract_origin, follow them all; there shouldn't be,
13518          but GCC versions at least through 4.4 generate this (GCC PR
13519          40573).  */
13520       child_origin_die = child_die;
13521       child_origin_cu = cu;
13522       while (1)
13523         {
13524           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13525                               child_origin_cu);
13526           if (attr == NULL)
13527             break;
13528           child_origin_die = follow_die_ref (child_origin_die, attr,
13529                                              &child_origin_cu);
13530         }
13531
13532       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13533          counterpart may exist.  */
13534       if (child_origin_die != child_die)
13535         {
13536           if (child_die->tag != child_origin_die->tag
13537               && !(child_die->tag == DW_TAG_inlined_subroutine
13538                    && child_origin_die->tag == DW_TAG_subprogram))
13539             complaint (_("Child DIE %s and its abstract origin %s have "
13540                          "different tags"),
13541                        sect_offset_str (child_die->sect_off),
13542                        sect_offset_str (child_origin_die->sect_off));
13543           if (child_origin_die->parent != origin_die)
13544             complaint (_("Child DIE %s and its abstract origin %s have "
13545                          "different parents"),
13546                        sect_offset_str (child_die->sect_off),
13547                        sect_offset_str (child_origin_die->sect_off));
13548           else
13549             offsets.push_back (child_origin_die->sect_off);
13550         }
13551     }
13552   std::sort (offsets.begin (), offsets.end ());
13553   sect_offset *offsets_end = offsets.data () + offsets.size ();
13554   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13555     if (offsetp[-1] == *offsetp)
13556       complaint (_("Multiple children of DIE %s refer "
13557                    "to DIE %s as their abstract origin"),
13558                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13559
13560   offsetp = offsets.data ();
13561   origin_child_die = origin_die->child;
13562   while (origin_child_die && origin_child_die->tag)
13563     {
13564       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13565       while (offsetp < offsets_end
13566              && *offsetp < origin_child_die->sect_off)
13567         offsetp++;
13568       if (offsetp >= offsets_end
13569           || *offsetp > origin_child_die->sect_off)
13570         {
13571           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13572              Check whether we're already processing ORIGIN_CHILD_DIE.
13573              This can happen with mutually referenced abstract_origins.
13574              PR 16581.  */
13575           if (!origin_child_die->in_process)
13576             process_die (origin_child_die, origin_cu);
13577         }
13578       origin_child_die = sibling_die (origin_child_die);
13579     }
13580   origin_cu->list_in_scope = origin_previous_list_in_scope;
13581 }
13582
13583 static void
13584 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13585 {
13586   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13587   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13588   struct context_stack *newobj;
13589   CORE_ADDR lowpc;
13590   CORE_ADDR highpc;
13591   struct die_info *child_die;
13592   struct attribute *attr, *call_line, *call_file;
13593   const char *name;
13594   CORE_ADDR baseaddr;
13595   struct block *block;
13596   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13597   std::vector<struct symbol *> template_args;
13598   struct template_symbol *templ_func = NULL;
13599
13600   if (inlined_func)
13601     {
13602       /* If we do not have call site information, we can't show the
13603          caller of this inlined function.  That's too confusing, so
13604          only use the scope for local variables.  */
13605       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13606       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13607       if (call_line == NULL || call_file == NULL)
13608         {
13609           read_lexical_block_scope (die, cu);
13610           return;
13611         }
13612     }
13613
13614   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13615
13616   name = dwarf2_name (die, cu);
13617
13618   /* Ignore functions with missing or empty names.  These are actually
13619      illegal according to the DWARF standard.  */
13620   if (name == NULL)
13621     {
13622       complaint (_("missing name for subprogram DIE at %s"),
13623                  sect_offset_str (die->sect_off));
13624       return;
13625     }
13626
13627   /* Ignore functions with missing or invalid low and high pc attributes.  */
13628   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13629       <= PC_BOUNDS_INVALID)
13630     {
13631       attr = dwarf2_attr (die, DW_AT_external, cu);
13632       if (!attr || !DW_UNSND (attr))
13633         complaint (_("cannot get low and high bounds "
13634                      "for subprogram DIE at %s"),
13635                    sect_offset_str (die->sect_off));
13636       return;
13637     }
13638
13639   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13640   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13641
13642   /* If we have any template arguments, then we must allocate a
13643      different sort of symbol.  */
13644   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13645     {
13646       if (child_die->tag == DW_TAG_template_type_param
13647           || child_die->tag == DW_TAG_template_value_param)
13648         {
13649           templ_func = allocate_template_symbol (objfile);
13650           templ_func->subclass = SYMBOL_TEMPLATE;
13651           break;
13652         }
13653     }
13654
13655   newobj = cu->builder->push_context (0, lowpc);
13656   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13657                              (struct symbol *) templ_func);
13658
13659   /* If there is a location expression for DW_AT_frame_base, record
13660      it.  */
13661   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13662   if (attr)
13663     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13664
13665   /* If there is a location for the static link, record it.  */
13666   newobj->static_link = NULL;
13667   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13668   if (attr)
13669     {
13670       newobj->static_link
13671         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13672       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13673     }
13674
13675   cu->list_in_scope = cu->builder->get_local_symbols ();
13676
13677   if (die->child != NULL)
13678     {
13679       child_die = die->child;
13680       while (child_die && child_die->tag)
13681         {
13682           if (child_die->tag == DW_TAG_template_type_param
13683               || child_die->tag == DW_TAG_template_value_param)
13684             {
13685               struct symbol *arg = new_symbol (child_die, NULL, cu);
13686
13687               if (arg != NULL)
13688                 template_args.push_back (arg);
13689             }
13690           else
13691             process_die (child_die, cu);
13692           child_die = sibling_die (child_die);
13693         }
13694     }
13695
13696   inherit_abstract_dies (die, cu);
13697
13698   /* If we have a DW_AT_specification, we might need to import using
13699      directives from the context of the specification DIE.  See the
13700      comment in determine_prefix.  */
13701   if (cu->language == language_cplus
13702       && dwarf2_attr (die, DW_AT_specification, cu))
13703     {
13704       struct dwarf2_cu *spec_cu = cu;
13705       struct die_info *spec_die = die_specification (die, &spec_cu);
13706
13707       while (spec_die)
13708         {
13709           child_die = spec_die->child;
13710           while (child_die && child_die->tag)
13711             {
13712               if (child_die->tag == DW_TAG_imported_module)
13713                 process_die (child_die, spec_cu);
13714               child_die = sibling_die (child_die);
13715             }
13716
13717           /* In some cases, GCC generates specification DIEs that
13718              themselves contain DW_AT_specification attributes.  */
13719           spec_die = die_specification (spec_die, &spec_cu);
13720         }
13721     }
13722
13723   struct context_stack cstk = cu->builder->pop_context ();
13724   /* Make a block for the local symbols within.  */
13725   block = cu->builder->finish_block (cstk.name, cstk.old_blocks,
13726                                      cstk.static_link, lowpc, highpc);
13727
13728   /* For C++, set the block's scope.  */
13729   if ((cu->language == language_cplus
13730        || cu->language == language_fortran
13731        || cu->language == language_d
13732        || cu->language == language_rust)
13733       && cu->processing_has_namespace_info)
13734     block_set_scope (block, determine_prefix (die, cu),
13735                      &objfile->objfile_obstack);
13736
13737   /* If we have address ranges, record them.  */
13738   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13739
13740   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13741
13742   /* Attach template arguments to function.  */
13743   if (!template_args.empty ())
13744     {
13745       gdb_assert (templ_func != NULL);
13746
13747       templ_func->n_template_arguments = template_args.size ();
13748       templ_func->template_arguments
13749         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13750                      templ_func->n_template_arguments);
13751       memcpy (templ_func->template_arguments,
13752               template_args.data (),
13753               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13754
13755       /* Make sure that the symtab is set on the new symbols.  Even
13756          though they don't appear in this symtab directly, other parts
13757          of gdb assume that symbols do, and this is reasonably
13758          true.  */
13759       for (struct symbol *sym : template_args)
13760         symbol_set_symtab (sym, symbol_symtab (templ_func));
13761     }
13762
13763   /* In C++, we can have functions nested inside functions (e.g., when
13764      a function declares a class that has methods).  This means that
13765      when we finish processing a function scope, we may need to go
13766      back to building a containing block's symbol lists.  */
13767   *cu->builder->get_local_symbols () = cstk.locals;
13768   cu->builder->set_local_using_directives (cstk.local_using_directives);
13769
13770   /* If we've finished processing a top-level function, subsequent
13771      symbols go in the file symbol list.  */
13772   if (cu->builder->outermost_context_p ())
13773     cu->list_in_scope = cu->builder->get_file_symbols ();
13774 }
13775
13776 /* Process all the DIES contained within a lexical block scope.  Start
13777    a new scope, process the dies, and then close the scope.  */
13778
13779 static void
13780 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13781 {
13782   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13783   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13784   CORE_ADDR lowpc, highpc;
13785   struct die_info *child_die;
13786   CORE_ADDR baseaddr;
13787
13788   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13789
13790   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13791   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13792      as multiple lexical blocks?  Handling children in a sane way would
13793      be nasty.  Might be easier to properly extend generic blocks to
13794      describe ranges.  */
13795   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13796     {
13797     case PC_BOUNDS_NOT_PRESENT:
13798       /* DW_TAG_lexical_block has no attributes, process its children as if
13799          there was no wrapping by that DW_TAG_lexical_block.
13800          GCC does no longer produces such DWARF since GCC r224161.  */
13801       for (child_die = die->child;
13802            child_die != NULL && child_die->tag;
13803            child_die = sibling_die (child_die))
13804         process_die (child_die, cu);
13805       return;
13806     case PC_BOUNDS_INVALID:
13807       return;
13808     }
13809   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13810   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13811
13812   cu->builder->push_context (0, lowpc);
13813   if (die->child != NULL)
13814     {
13815       child_die = die->child;
13816       while (child_die && child_die->tag)
13817         {
13818           process_die (child_die, cu);
13819           child_die = sibling_die (child_die);
13820         }
13821     }
13822   inherit_abstract_dies (die, cu);
13823   struct context_stack cstk = cu->builder->pop_context ();
13824
13825   if (*cu->builder->get_local_symbols () != NULL
13826       || (*cu->builder->get_local_using_directives ()) != NULL)
13827     {
13828       struct block *block
13829         = cu->builder->finish_block (0, cstk.old_blocks, NULL,
13830                                      cstk.start_addr, highpc);
13831
13832       /* Note that recording ranges after traversing children, as we
13833          do here, means that recording a parent's ranges entails
13834          walking across all its children's ranges as they appear in
13835          the address map, which is quadratic behavior.
13836
13837          It would be nicer to record the parent's ranges before
13838          traversing its children, simply overriding whatever you find
13839          there.  But since we don't even decide whether to create a
13840          block until after we've traversed its children, that's hard
13841          to do.  */
13842       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13843     }
13844   *cu->builder->get_local_symbols () = cstk.locals;
13845   cu->builder->set_local_using_directives (cstk.local_using_directives);
13846 }
13847
13848 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13849
13850 static void
13851 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13852 {
13853   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13854   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13855   CORE_ADDR pc, baseaddr;
13856   struct attribute *attr;
13857   struct call_site *call_site, call_site_local;
13858   void **slot;
13859   int nparams;
13860   struct die_info *child_die;
13861
13862   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13863
13864   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13865   if (attr == NULL)
13866     {
13867       /* This was a pre-DWARF-5 GNU extension alias
13868          for DW_AT_call_return_pc.  */
13869       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13870     }
13871   if (!attr)
13872     {
13873       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13874                    "DIE %s [in module %s]"),
13875                  sect_offset_str (die->sect_off), objfile_name (objfile));
13876       return;
13877     }
13878   pc = attr_value_as_address (attr) + baseaddr;
13879   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13880
13881   if (cu->call_site_htab == NULL)
13882     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13883                                                NULL, &objfile->objfile_obstack,
13884                                                hashtab_obstack_allocate, NULL);
13885   call_site_local.pc = pc;
13886   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13887   if (*slot != NULL)
13888     {
13889       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13890                    "DIE %s [in module %s]"),
13891                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13892                  objfile_name (objfile));
13893       return;
13894     }
13895
13896   /* Count parameters at the caller.  */
13897
13898   nparams = 0;
13899   for (child_die = die->child; child_die && child_die->tag;
13900        child_die = sibling_die (child_die))
13901     {
13902       if (child_die->tag != DW_TAG_call_site_parameter
13903           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13904         {
13905           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13906                        "DW_TAG_call_site child DIE %s [in module %s]"),
13907                      child_die->tag, sect_offset_str (child_die->sect_off),
13908                      objfile_name (objfile));
13909           continue;
13910         }
13911
13912       nparams++;
13913     }
13914
13915   call_site
13916     = ((struct call_site *)
13917        obstack_alloc (&objfile->objfile_obstack,
13918                       sizeof (*call_site)
13919                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13920   *slot = call_site;
13921   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13922   call_site->pc = pc;
13923
13924   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13925       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13926     {
13927       struct die_info *func_die;
13928
13929       /* Skip also over DW_TAG_inlined_subroutine.  */
13930       for (func_die = die->parent;
13931            func_die && func_die->tag != DW_TAG_subprogram
13932            && func_die->tag != DW_TAG_subroutine_type;
13933            func_die = func_die->parent);
13934
13935       /* DW_AT_call_all_calls is a superset
13936          of DW_AT_call_all_tail_calls.  */
13937       if (func_die
13938           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13939           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13940           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13941           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13942         {
13943           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13944              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13945              both the initial caller containing the real return address PC and
13946              the final callee containing the current PC of a chain of tail
13947              calls do not need to have the tail call list complete.  But any
13948              function candidate for a virtual tail call frame searched via
13949              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13950              determined unambiguously.  */
13951         }
13952       else
13953         {
13954           struct type *func_type = NULL;
13955
13956           if (func_die)
13957             func_type = get_die_type (func_die, cu);
13958           if (func_type != NULL)
13959             {
13960               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13961
13962               /* Enlist this call site to the function.  */
13963               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13964               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13965             }
13966           else
13967             complaint (_("Cannot find function owning DW_TAG_call_site "
13968                          "DIE %s [in module %s]"),
13969                        sect_offset_str (die->sect_off), objfile_name (objfile));
13970         }
13971     }
13972
13973   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13974   if (attr == NULL)
13975     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13976   if (attr == NULL)
13977     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13978   if (attr == NULL)
13979     {
13980       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13981       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13982     }
13983   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13984   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
13985     /* Keep NULL DWARF_BLOCK.  */;
13986   else if (attr_form_is_block (attr))
13987     {
13988       struct dwarf2_locexpr_baton *dlbaton;
13989
13990       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13991       dlbaton->data = DW_BLOCK (attr)->data;
13992       dlbaton->size = DW_BLOCK (attr)->size;
13993       dlbaton->per_cu = cu->per_cu;
13994
13995       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13996     }
13997   else if (attr_form_is_ref (attr))
13998     {
13999       struct dwarf2_cu *target_cu = cu;
14000       struct die_info *target_die;
14001
14002       target_die = follow_die_ref (die, attr, &target_cu);
14003       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14004       if (die_is_declaration (target_die, target_cu))
14005         {
14006           const char *target_physname;
14007
14008           /* Prefer the mangled name; otherwise compute the demangled one.  */
14009           target_physname = dw2_linkage_name (target_die, target_cu);
14010           if (target_physname == NULL)
14011             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14012           if (target_physname == NULL)
14013             complaint (_("DW_AT_call_target target DIE has invalid "
14014                          "physname, for referencing DIE %s [in module %s]"),
14015                        sect_offset_str (die->sect_off), objfile_name (objfile));
14016           else
14017             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14018         }
14019       else
14020         {
14021           CORE_ADDR lowpc;
14022
14023           /* DW_AT_entry_pc should be preferred.  */
14024           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14025               <= PC_BOUNDS_INVALID)
14026             complaint (_("DW_AT_call_target target DIE has invalid "
14027                          "low pc, for referencing DIE %s [in module %s]"),
14028                        sect_offset_str (die->sect_off), objfile_name (objfile));
14029           else
14030             {
14031               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14032               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14033             }
14034         }
14035     }
14036   else
14037     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
14038                  "block nor reference, for DIE %s [in module %s]"),
14039                sect_offset_str (die->sect_off), objfile_name (objfile));
14040
14041   call_site->per_cu = cu->per_cu;
14042
14043   for (child_die = die->child;
14044        child_die && child_die->tag;
14045        child_die = sibling_die (child_die))
14046     {
14047       struct call_site_parameter *parameter;
14048       struct attribute *loc, *origin;
14049
14050       if (child_die->tag != DW_TAG_call_site_parameter
14051           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14052         {
14053           /* Already printed the complaint above.  */
14054           continue;
14055         }
14056
14057       gdb_assert (call_site->parameter_count < nparams);
14058       parameter = &call_site->parameter[call_site->parameter_count];
14059
14060       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14061          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14062          register is contained in DW_AT_call_value.  */
14063
14064       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14065       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14066       if (origin == NULL)
14067         {
14068           /* This was a pre-DWARF-5 GNU extension alias
14069              for DW_AT_call_parameter.  */
14070           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14071         }
14072       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14073         {
14074           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14075
14076           sect_offset sect_off
14077             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14078           if (!offset_in_cu_p (&cu->header, sect_off))
14079             {
14080               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14081                  binding can be done only inside one CU.  Such referenced DIE
14082                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14083               complaint (_("DW_AT_call_parameter offset is not in CU for "
14084                            "DW_TAG_call_site child DIE %s [in module %s]"),
14085                          sect_offset_str (child_die->sect_off),
14086                          objfile_name (objfile));
14087               continue;
14088             }
14089           parameter->u.param_cu_off
14090             = (cu_offset) (sect_off - cu->header.sect_off);
14091         }
14092       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14093         {
14094           complaint (_("No DW_FORM_block* DW_AT_location for "
14095                        "DW_TAG_call_site child DIE %s [in module %s]"),
14096                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14097           continue;
14098         }
14099       else
14100         {
14101           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14102             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14103           if (parameter->u.dwarf_reg != -1)
14104             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14105           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14106                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14107                                              &parameter->u.fb_offset))
14108             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14109           else
14110             {
14111               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14112                            "for DW_FORM_block* DW_AT_location is supported for "
14113                            "DW_TAG_call_site child DIE %s "
14114                            "[in module %s]"),
14115                          sect_offset_str (child_die->sect_off),
14116                          objfile_name (objfile));
14117               continue;
14118             }
14119         }
14120
14121       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14122       if (attr == NULL)
14123         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14124       if (!attr_form_is_block (attr))
14125         {
14126           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14127                        "DW_TAG_call_site child DIE %s [in module %s]"),
14128                      sect_offset_str (child_die->sect_off),
14129                      objfile_name (objfile));
14130           continue;
14131         }
14132       parameter->value = DW_BLOCK (attr)->data;
14133       parameter->value_size = DW_BLOCK (attr)->size;
14134
14135       /* Parameters are not pre-cleared by memset above.  */
14136       parameter->data_value = NULL;
14137       parameter->data_value_size = 0;
14138       call_site->parameter_count++;
14139
14140       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14141       if (attr == NULL)
14142         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14143       if (attr)
14144         {
14145           if (!attr_form_is_block (attr))
14146             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14147                          "DW_TAG_call_site child DIE %s [in module %s]"),
14148                        sect_offset_str (child_die->sect_off),
14149                        objfile_name (objfile));
14150           else
14151             {
14152               parameter->data_value = DW_BLOCK (attr)->data;
14153               parameter->data_value_size = DW_BLOCK (attr)->size;
14154             }
14155         }
14156     }
14157 }
14158
14159 /* Helper function for read_variable.  If DIE represents a virtual
14160    table, then return the type of the concrete object that is
14161    associated with the virtual table.  Otherwise, return NULL.  */
14162
14163 static struct type *
14164 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14165 {
14166   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14167   if (attr == NULL)
14168     return NULL;
14169
14170   /* Find the type DIE.  */
14171   struct die_info *type_die = NULL;
14172   struct dwarf2_cu *type_cu = cu;
14173
14174   if (attr_form_is_ref (attr))
14175     type_die = follow_die_ref (die, attr, &type_cu);
14176   if (type_die == NULL)
14177     return NULL;
14178
14179   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14180     return NULL;
14181   return die_containing_type (type_die, type_cu);
14182 }
14183
14184 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14185
14186 static void
14187 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14188 {
14189   struct rust_vtable_symbol *storage = NULL;
14190
14191   if (cu->language == language_rust)
14192     {
14193       struct type *containing_type = rust_containing_type (die, cu);
14194
14195       if (containing_type != NULL)
14196         {
14197           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14198
14199           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14200                                     struct rust_vtable_symbol);
14201           initialize_objfile_symbol (storage);
14202           storage->concrete_type = containing_type;
14203           storage->subclass = SYMBOL_RUST_VTABLE;
14204         }
14205     }
14206
14207   new_symbol (die, NULL, cu, storage);
14208 }
14209
14210 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14211    reading .debug_rnglists.
14212    Callback's type should be:
14213     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14214    Return true if the attributes are present and valid, otherwise,
14215    return false.  */
14216
14217 template <typename Callback>
14218 static bool
14219 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14220                          Callback &&callback)
14221 {
14222   struct dwarf2_per_objfile *dwarf2_per_objfile
14223     = cu->per_cu->dwarf2_per_objfile;
14224   struct objfile *objfile = dwarf2_per_objfile->objfile;
14225   bfd *obfd = objfile->obfd;
14226   /* Base address selection entry.  */
14227   CORE_ADDR base;
14228   int found_base;
14229   const gdb_byte *buffer;
14230   CORE_ADDR baseaddr;
14231   bool overflow = false;
14232
14233   found_base = cu->base_known;
14234   base = cu->base_address;
14235
14236   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14237   if (offset >= dwarf2_per_objfile->rnglists.size)
14238     {
14239       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14240                  offset);
14241       return false;
14242     }
14243   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14244
14245   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14246
14247   while (1)
14248     {
14249       /* Initialize it due to a false compiler warning.  */
14250       CORE_ADDR range_beginning = 0, range_end = 0;
14251       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14252                                  + dwarf2_per_objfile->rnglists.size);
14253       unsigned int bytes_read;
14254
14255       if (buffer == buf_end)
14256         {
14257           overflow = true;
14258           break;
14259         }
14260       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14261       switch (rlet)
14262         {
14263         case DW_RLE_end_of_list:
14264           break;
14265         case DW_RLE_base_address:
14266           if (buffer + cu->header.addr_size > buf_end)
14267             {
14268               overflow = true;
14269               break;
14270             }
14271           base = read_address (obfd, buffer, cu, &bytes_read);
14272           found_base = 1;
14273           buffer += bytes_read;
14274           break;
14275         case DW_RLE_start_length:
14276           if (buffer + cu->header.addr_size > buf_end)
14277             {
14278               overflow = true;
14279               break;
14280             }
14281           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14282           buffer += bytes_read;
14283           range_end = (range_beginning
14284                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14285           buffer += bytes_read;
14286           if (buffer > buf_end)
14287             {
14288               overflow = true;
14289               break;
14290             }
14291           break;
14292         case DW_RLE_offset_pair:
14293           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14294           buffer += bytes_read;
14295           if (buffer > buf_end)
14296             {
14297               overflow = true;
14298               break;
14299             }
14300           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14301           buffer += bytes_read;
14302           if (buffer > buf_end)
14303             {
14304               overflow = true;
14305               break;
14306             }
14307           break;
14308         case DW_RLE_start_end:
14309           if (buffer + 2 * cu->header.addr_size > buf_end)
14310             {
14311               overflow = true;
14312               break;
14313             }
14314           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14315           buffer += bytes_read;
14316           range_end = read_address (obfd, buffer, cu, &bytes_read);
14317           buffer += bytes_read;
14318           break;
14319         default:
14320           complaint (_("Invalid .debug_rnglists data (no base address)"));
14321           return false;
14322         }
14323       if (rlet == DW_RLE_end_of_list || overflow)
14324         break;
14325       if (rlet == DW_RLE_base_address)
14326         continue;
14327
14328       if (!found_base)
14329         {
14330           /* We have no valid base address for the ranges
14331              data.  */
14332           complaint (_("Invalid .debug_rnglists data (no base address)"));
14333           return false;
14334         }
14335
14336       if (range_beginning > range_end)
14337         {
14338           /* Inverted range entries are invalid.  */
14339           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14340           return false;
14341         }
14342
14343       /* Empty range entries have no effect.  */
14344       if (range_beginning == range_end)
14345         continue;
14346
14347       range_beginning += base;
14348       range_end += base;
14349
14350       /* A not-uncommon case of bad debug info.
14351          Don't pollute the addrmap with bad data.  */
14352       if (range_beginning + baseaddr == 0
14353           && !dwarf2_per_objfile->has_section_at_zero)
14354         {
14355           complaint (_(".debug_rnglists entry has start address of zero"
14356                        " [in module %s]"), objfile_name (objfile));
14357           continue;
14358         }
14359
14360       callback (range_beginning, range_end);
14361     }
14362
14363   if (overflow)
14364     {
14365       complaint (_("Offset %d is not terminated "
14366                    "for DW_AT_ranges attribute"),
14367                  offset);
14368       return false;
14369     }
14370
14371   return true;
14372 }
14373
14374 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14375    Callback's type should be:
14376     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14377    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14378
14379 template <typename Callback>
14380 static int
14381 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14382                        Callback &&callback)
14383 {
14384   struct dwarf2_per_objfile *dwarf2_per_objfile
14385       = cu->per_cu->dwarf2_per_objfile;
14386   struct objfile *objfile = dwarf2_per_objfile->objfile;
14387   struct comp_unit_head *cu_header = &cu->header;
14388   bfd *obfd = objfile->obfd;
14389   unsigned int addr_size = cu_header->addr_size;
14390   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14391   /* Base address selection entry.  */
14392   CORE_ADDR base;
14393   int found_base;
14394   unsigned int dummy;
14395   const gdb_byte *buffer;
14396   CORE_ADDR baseaddr;
14397
14398   if (cu_header->version >= 5)
14399     return dwarf2_rnglists_process (offset, cu, callback);
14400
14401   found_base = cu->base_known;
14402   base = cu->base_address;
14403
14404   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14405   if (offset >= dwarf2_per_objfile->ranges.size)
14406     {
14407       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14408                  offset);
14409       return 0;
14410     }
14411   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14412
14413   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14414
14415   while (1)
14416     {
14417       CORE_ADDR range_beginning, range_end;
14418
14419       range_beginning = read_address (obfd, buffer, cu, &dummy);
14420       buffer += addr_size;
14421       range_end = read_address (obfd, buffer, cu, &dummy);
14422       buffer += addr_size;
14423       offset += 2 * addr_size;
14424
14425       /* An end of list marker is a pair of zero addresses.  */
14426       if (range_beginning == 0 && range_end == 0)
14427         /* Found the end of list entry.  */
14428         break;
14429
14430       /* Each base address selection entry is a pair of 2 values.
14431          The first is the largest possible address, the second is
14432          the base address.  Check for a base address here.  */
14433       if ((range_beginning & mask) == mask)
14434         {
14435           /* If we found the largest possible address, then we already
14436              have the base address in range_end.  */
14437           base = range_end;
14438           found_base = 1;
14439           continue;
14440         }
14441
14442       if (!found_base)
14443         {
14444           /* We have no valid base address for the ranges
14445              data.  */
14446           complaint (_("Invalid .debug_ranges data (no base address)"));
14447           return 0;
14448         }
14449
14450       if (range_beginning > range_end)
14451         {
14452           /* Inverted range entries are invalid.  */
14453           complaint (_("Invalid .debug_ranges data (inverted range)"));
14454           return 0;
14455         }
14456
14457       /* Empty range entries have no effect.  */
14458       if (range_beginning == range_end)
14459         continue;
14460
14461       range_beginning += base;
14462       range_end += base;
14463
14464       /* A not-uncommon case of bad debug info.
14465          Don't pollute the addrmap with bad data.  */
14466       if (range_beginning + baseaddr == 0
14467           && !dwarf2_per_objfile->has_section_at_zero)
14468         {
14469           complaint (_(".debug_ranges entry has start address of zero"
14470                        " [in module %s]"), objfile_name (objfile));
14471           continue;
14472         }
14473
14474       callback (range_beginning, range_end);
14475     }
14476
14477   return 1;
14478 }
14479
14480 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14481    Return 1 if the attributes are present and valid, otherwise, return 0.
14482    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14483
14484 static int
14485 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14486                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14487                     struct partial_symtab *ranges_pst)
14488 {
14489   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14490   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14491   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14492                                        SECT_OFF_TEXT (objfile));
14493   int low_set = 0;
14494   CORE_ADDR low = 0;
14495   CORE_ADDR high = 0;
14496   int retval;
14497
14498   retval = dwarf2_ranges_process (offset, cu,
14499     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14500     {
14501       if (ranges_pst != NULL)
14502         {
14503           CORE_ADDR lowpc;
14504           CORE_ADDR highpc;
14505
14506           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14507                                                range_beginning + baseaddr)
14508                    - baseaddr);
14509           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14510                                                 range_end + baseaddr)
14511                     - baseaddr);
14512           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14513                              ranges_pst);
14514         }
14515
14516       /* FIXME: This is recording everything as a low-high
14517          segment of consecutive addresses.  We should have a
14518          data structure for discontiguous block ranges
14519          instead.  */
14520       if (! low_set)
14521         {
14522           low = range_beginning;
14523           high = range_end;
14524           low_set = 1;
14525         }
14526       else
14527         {
14528           if (range_beginning < low)
14529             low = range_beginning;
14530           if (range_end > high)
14531             high = range_end;
14532         }
14533     });
14534   if (!retval)
14535     return 0;
14536
14537   if (! low_set)
14538     /* If the first entry is an end-of-list marker, the range
14539        describes an empty scope, i.e. no instructions.  */
14540     return 0;
14541
14542   if (low_return)
14543     *low_return = low;
14544   if (high_return)
14545     *high_return = high;
14546   return 1;
14547 }
14548
14549 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14550    definition for the return value.  *LOWPC and *HIGHPC are set iff
14551    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14552
14553 static enum pc_bounds_kind
14554 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14555                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14556                       struct partial_symtab *pst)
14557 {
14558   struct dwarf2_per_objfile *dwarf2_per_objfile
14559     = cu->per_cu->dwarf2_per_objfile;
14560   struct attribute *attr;
14561   struct attribute *attr_high;
14562   CORE_ADDR low = 0;
14563   CORE_ADDR high = 0;
14564   enum pc_bounds_kind ret;
14565
14566   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14567   if (attr_high)
14568     {
14569       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14570       if (attr)
14571         {
14572           low = attr_value_as_address (attr);
14573           high = attr_value_as_address (attr_high);
14574           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14575             high += low;
14576         }
14577       else
14578         /* Found high w/o low attribute.  */
14579         return PC_BOUNDS_INVALID;
14580
14581       /* Found consecutive range of addresses.  */
14582       ret = PC_BOUNDS_HIGH_LOW;
14583     }
14584   else
14585     {
14586       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14587       if (attr != NULL)
14588         {
14589           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14590              We take advantage of the fact that DW_AT_ranges does not appear
14591              in DW_TAG_compile_unit of DWO files.  */
14592           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14593           unsigned int ranges_offset = (DW_UNSND (attr)
14594                                         + (need_ranges_base
14595                                            ? cu->ranges_base
14596                                            : 0));
14597
14598           /* Value of the DW_AT_ranges attribute is the offset in the
14599              .debug_ranges section.  */
14600           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14601             return PC_BOUNDS_INVALID;
14602           /* Found discontinuous range of addresses.  */
14603           ret = PC_BOUNDS_RANGES;
14604         }
14605       else
14606         return PC_BOUNDS_NOT_PRESENT;
14607     }
14608
14609   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14610   if (high <= low)
14611     return PC_BOUNDS_INVALID;
14612
14613   /* When using the GNU linker, .gnu.linkonce. sections are used to
14614      eliminate duplicate copies of functions and vtables and such.
14615      The linker will arbitrarily choose one and discard the others.
14616      The AT_*_pc values for such functions refer to local labels in
14617      these sections.  If the section from that file was discarded, the
14618      labels are not in the output, so the relocs get a value of 0.
14619      If this is a discarded function, mark the pc bounds as invalid,
14620      so that GDB will ignore it.  */
14621   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14622     return PC_BOUNDS_INVALID;
14623
14624   *lowpc = low;
14625   if (highpc)
14626     *highpc = high;
14627   return ret;
14628 }
14629
14630 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14631    its low and high PC addresses.  Do nothing if these addresses could not
14632    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14633    and HIGHPC to the high address if greater than HIGHPC.  */
14634
14635 static void
14636 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14637                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14638                                  struct dwarf2_cu *cu)
14639 {
14640   CORE_ADDR low, high;
14641   struct die_info *child = die->child;
14642
14643   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14644     {
14645       *lowpc = std::min (*lowpc, low);
14646       *highpc = std::max (*highpc, high);
14647     }
14648
14649   /* If the language does not allow nested subprograms (either inside
14650      subprograms or lexical blocks), we're done.  */
14651   if (cu->language != language_ada)
14652     return;
14653
14654   /* Check all the children of the given DIE.  If it contains nested
14655      subprograms, then check their pc bounds.  Likewise, we need to
14656      check lexical blocks as well, as they may also contain subprogram
14657      definitions.  */
14658   while (child && child->tag)
14659     {
14660       if (child->tag == DW_TAG_subprogram
14661           || child->tag == DW_TAG_lexical_block)
14662         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14663       child = sibling_die (child);
14664     }
14665 }
14666
14667 /* Get the low and high pc's represented by the scope DIE, and store
14668    them in *LOWPC and *HIGHPC.  If the correct values can't be
14669    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14670
14671 static void
14672 get_scope_pc_bounds (struct die_info *die,
14673                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14674                      struct dwarf2_cu *cu)
14675 {
14676   CORE_ADDR best_low = (CORE_ADDR) -1;
14677   CORE_ADDR best_high = (CORE_ADDR) 0;
14678   CORE_ADDR current_low, current_high;
14679
14680   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14681       >= PC_BOUNDS_RANGES)
14682     {
14683       best_low = current_low;
14684       best_high = current_high;
14685     }
14686   else
14687     {
14688       struct die_info *child = die->child;
14689
14690       while (child && child->tag)
14691         {
14692           switch (child->tag) {
14693           case DW_TAG_subprogram:
14694             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14695             break;
14696           case DW_TAG_namespace:
14697           case DW_TAG_module:
14698             /* FIXME: carlton/2004-01-16: Should we do this for
14699                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14700                that current GCC's always emit the DIEs corresponding
14701                to definitions of methods of classes as children of a
14702                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14703                the DIEs giving the declarations, which could be
14704                anywhere).  But I don't see any reason why the
14705                standards says that they have to be there.  */
14706             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14707
14708             if (current_low != ((CORE_ADDR) -1))
14709               {
14710                 best_low = std::min (best_low, current_low);
14711                 best_high = std::max (best_high, current_high);
14712               }
14713             break;
14714           default:
14715             /* Ignore.  */
14716             break;
14717           }
14718
14719           child = sibling_die (child);
14720         }
14721     }
14722
14723   *lowpc = best_low;
14724   *highpc = best_high;
14725 }
14726
14727 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14728    in DIE.  */
14729
14730 static void
14731 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14732                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14733 {
14734   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14735   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14736   struct attribute *attr;
14737   struct attribute *attr_high;
14738
14739   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14740   if (attr_high)
14741     {
14742       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14743       if (attr)
14744         {
14745           CORE_ADDR low = attr_value_as_address (attr);
14746           CORE_ADDR high = attr_value_as_address (attr_high);
14747
14748           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14749             high += low;
14750
14751           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14752           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14753           cu->builder->record_block_range (block, low, high - 1);
14754         }
14755     }
14756
14757   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14758   if (attr)
14759     {
14760       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14761          We take advantage of the fact that DW_AT_ranges does not appear
14762          in DW_TAG_compile_unit of DWO files.  */
14763       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14764
14765       /* The value of the DW_AT_ranges attribute is the offset of the
14766          address range list in the .debug_ranges section.  */
14767       unsigned long offset = (DW_UNSND (attr)
14768                               + (need_ranges_base ? cu->ranges_base : 0));
14769
14770       dwarf2_ranges_process (offset, cu,
14771         [&] (CORE_ADDR start, CORE_ADDR end)
14772         {
14773           start += baseaddr;
14774           end += baseaddr;
14775           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14776           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14777           cu->builder->record_block_range (block, start, end - 1);
14778         });
14779     }
14780 }
14781
14782 /* Check whether the producer field indicates either of GCC < 4.6, or the
14783    Intel C/C++ compiler, and cache the result in CU.  */
14784
14785 static void
14786 check_producer (struct dwarf2_cu *cu)
14787 {
14788   int major, minor;
14789
14790   if (cu->producer == NULL)
14791     {
14792       /* For unknown compilers expect their behavior is DWARF version
14793          compliant.
14794
14795          GCC started to support .debug_types sections by -gdwarf-4 since
14796          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14797          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14798          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14799          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14800     }
14801   else if (producer_is_gcc (cu->producer, &major, &minor))
14802     {
14803       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14804       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14805     }
14806   else if (producer_is_icc (cu->producer, &major, &minor))
14807     cu->producer_is_icc_lt_14 = major < 14;
14808   else
14809     {
14810       /* For other non-GCC compilers, expect their behavior is DWARF version
14811          compliant.  */
14812     }
14813
14814   cu->checked_producer = 1;
14815 }
14816
14817 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14818    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14819    during 4.6.0 experimental.  */
14820
14821 static int
14822 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14823 {
14824   if (!cu->checked_producer)
14825     check_producer (cu);
14826
14827   return cu->producer_is_gxx_lt_4_6;
14828 }
14829
14830 /* Return the default accessibility type if it is not overriden by
14831    DW_AT_accessibility.  */
14832
14833 static enum dwarf_access_attribute
14834 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14835 {
14836   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14837     {
14838       /* The default DWARF 2 accessibility for members is public, the default
14839          accessibility for inheritance is private.  */
14840
14841       if (die->tag != DW_TAG_inheritance)
14842         return DW_ACCESS_public;
14843       else
14844         return DW_ACCESS_private;
14845     }
14846   else
14847     {
14848       /* DWARF 3+ defines the default accessibility a different way.  The same
14849          rules apply now for DW_TAG_inheritance as for the members and it only
14850          depends on the container kind.  */
14851
14852       if (die->parent->tag == DW_TAG_class_type)
14853         return DW_ACCESS_private;
14854       else
14855         return DW_ACCESS_public;
14856     }
14857 }
14858
14859 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14860    offset.  If the attribute was not found return 0, otherwise return
14861    1.  If it was found but could not properly be handled, set *OFFSET
14862    to 0.  */
14863
14864 static int
14865 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14866                              LONGEST *offset)
14867 {
14868   struct attribute *attr;
14869
14870   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14871   if (attr != NULL)
14872     {
14873       *offset = 0;
14874
14875       /* Note that we do not check for a section offset first here.
14876          This is because DW_AT_data_member_location is new in DWARF 4,
14877          so if we see it, we can assume that a constant form is really
14878          a constant and not a section offset.  */
14879       if (attr_form_is_constant (attr))
14880         *offset = dwarf2_get_attr_constant_value (attr, 0);
14881       else if (attr_form_is_section_offset (attr))
14882         dwarf2_complex_location_expr_complaint ();
14883       else if (attr_form_is_block (attr))
14884         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14885       else
14886         dwarf2_complex_location_expr_complaint ();
14887
14888       return 1;
14889     }
14890
14891   return 0;
14892 }
14893
14894 /* Add an aggregate field to the field list.  */
14895
14896 static void
14897 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14898                   struct dwarf2_cu *cu)
14899 {
14900   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14901   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14902   struct nextfield *new_field;
14903   struct attribute *attr;
14904   struct field *fp;
14905   const char *fieldname = "";
14906
14907   if (die->tag == DW_TAG_inheritance)
14908     {
14909       fip->baseclasses.emplace_back ();
14910       new_field = &fip->baseclasses.back ();
14911     }
14912   else
14913     {
14914       fip->fields.emplace_back ();
14915       new_field = &fip->fields.back ();
14916     }
14917
14918   fip->nfields++;
14919
14920   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14921   if (attr)
14922     new_field->accessibility = DW_UNSND (attr);
14923   else
14924     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14925   if (new_field->accessibility != DW_ACCESS_public)
14926     fip->non_public_fields = 1;
14927
14928   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14929   if (attr)
14930     new_field->virtuality = DW_UNSND (attr);
14931   else
14932     new_field->virtuality = DW_VIRTUALITY_none;
14933
14934   fp = &new_field->field;
14935
14936   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14937     {
14938       LONGEST offset;
14939
14940       /* Data member other than a C++ static data member.  */
14941
14942       /* Get type of field.  */
14943       fp->type = die_type (die, cu);
14944
14945       SET_FIELD_BITPOS (*fp, 0);
14946
14947       /* Get bit size of field (zero if none).  */
14948       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14949       if (attr)
14950         {
14951           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14952         }
14953       else
14954         {
14955           FIELD_BITSIZE (*fp) = 0;
14956         }
14957
14958       /* Get bit offset of field.  */
14959       if (handle_data_member_location (die, cu, &offset))
14960         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14961       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14962       if (attr)
14963         {
14964           if (gdbarch_bits_big_endian (gdbarch))
14965             {
14966               /* For big endian bits, the DW_AT_bit_offset gives the
14967                  additional bit offset from the MSB of the containing
14968                  anonymous object to the MSB of the field.  We don't
14969                  have to do anything special since we don't need to
14970                  know the size of the anonymous object.  */
14971               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
14972             }
14973           else
14974             {
14975               /* For little endian bits, compute the bit offset to the
14976                  MSB of the anonymous object, subtract off the number of
14977                  bits from the MSB of the field to the MSB of the
14978                  object, and then subtract off the number of bits of
14979                  the field itself.  The result is the bit offset of
14980                  the LSB of the field.  */
14981               int anonymous_size;
14982               int bit_offset = DW_UNSND (attr);
14983
14984               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14985               if (attr)
14986                 {
14987                   /* The size of the anonymous object containing
14988                      the bit field is explicit, so use the
14989                      indicated size (in bytes).  */
14990                   anonymous_size = DW_UNSND (attr);
14991                 }
14992               else
14993                 {
14994                   /* The size of the anonymous object containing
14995                      the bit field must be inferred from the type
14996                      attribute of the data member containing the
14997                      bit field.  */
14998                   anonymous_size = TYPE_LENGTH (fp->type);
14999                 }
15000               SET_FIELD_BITPOS (*fp,
15001                                 (FIELD_BITPOS (*fp)
15002                                  + anonymous_size * bits_per_byte
15003                                  - bit_offset - FIELD_BITSIZE (*fp)));
15004             }
15005         }
15006       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15007       if (attr != NULL)
15008         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15009                                 + dwarf2_get_attr_constant_value (attr, 0)));
15010
15011       /* Get name of field.  */
15012       fieldname = dwarf2_name (die, cu);
15013       if (fieldname == NULL)
15014         fieldname = "";
15015
15016       /* The name is already allocated along with this objfile, so we don't
15017          need to duplicate it for the type.  */
15018       fp->name = fieldname;
15019
15020       /* Change accessibility for artificial fields (e.g. virtual table
15021          pointer or virtual base class pointer) to private.  */
15022       if (dwarf2_attr (die, DW_AT_artificial, cu))
15023         {
15024           FIELD_ARTIFICIAL (*fp) = 1;
15025           new_field->accessibility = DW_ACCESS_private;
15026           fip->non_public_fields = 1;
15027         }
15028     }
15029   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15030     {
15031       /* C++ static member.  */
15032
15033       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15034          is a declaration, but all versions of G++ as of this writing
15035          (so through at least 3.2.1) incorrectly generate
15036          DW_TAG_variable tags.  */
15037
15038       const char *physname;
15039
15040       /* Get name of field.  */
15041       fieldname = dwarf2_name (die, cu);
15042       if (fieldname == NULL)
15043         return;
15044
15045       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15046       if (attr
15047           /* Only create a symbol if this is an external value.
15048              new_symbol checks this and puts the value in the global symbol
15049              table, which we want.  If it is not external, new_symbol
15050              will try to put the value in cu->list_in_scope which is wrong.  */
15051           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15052         {
15053           /* A static const member, not much different than an enum as far as
15054              we're concerned, except that we can support more types.  */
15055           new_symbol (die, NULL, cu);
15056         }
15057
15058       /* Get physical name.  */
15059       physname = dwarf2_physname (fieldname, die, cu);
15060
15061       /* The name is already allocated along with this objfile, so we don't
15062          need to duplicate it for the type.  */
15063       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15064       FIELD_TYPE (*fp) = die_type (die, cu);
15065       FIELD_NAME (*fp) = fieldname;
15066     }
15067   else if (die->tag == DW_TAG_inheritance)
15068     {
15069       LONGEST offset;
15070
15071       /* C++ base class field.  */
15072       if (handle_data_member_location (die, cu, &offset))
15073         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15074       FIELD_BITSIZE (*fp) = 0;
15075       FIELD_TYPE (*fp) = die_type (die, cu);
15076       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15077     }
15078   else if (die->tag == DW_TAG_variant_part)
15079     {
15080       /* process_structure_scope will treat this DIE as a union.  */
15081       process_structure_scope (die, cu);
15082
15083       /* The variant part is relative to the start of the enclosing
15084          structure.  */
15085       SET_FIELD_BITPOS (*fp, 0);
15086       fp->type = get_die_type (die, cu);
15087       fp->artificial = 1;
15088       fp->name = "<<variant>>";
15089     }
15090   else
15091     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15092 }
15093
15094 /* Can the type given by DIE define another type?  */
15095
15096 static bool
15097 type_can_define_types (const struct die_info *die)
15098 {
15099   switch (die->tag)
15100     {
15101     case DW_TAG_typedef:
15102     case DW_TAG_class_type:
15103     case DW_TAG_structure_type:
15104     case DW_TAG_union_type:
15105     case DW_TAG_enumeration_type:
15106       return true;
15107
15108     default:
15109       return false;
15110     }
15111 }
15112
15113 /* Add a type definition defined in the scope of the FIP's class.  */
15114
15115 static void
15116 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15117                       struct dwarf2_cu *cu)
15118 {
15119   struct decl_field fp;
15120   memset (&fp, 0, sizeof (fp));
15121
15122   gdb_assert (type_can_define_types (die));
15123
15124   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15125   fp.name = dwarf2_name (die, cu);
15126   fp.type = read_type_die (die, cu);
15127
15128   /* Save accessibility.  */
15129   enum dwarf_access_attribute accessibility;
15130   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15131   if (attr != NULL)
15132     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15133   else
15134     accessibility = dwarf2_default_access_attribute (die, cu);
15135   switch (accessibility)
15136     {
15137     case DW_ACCESS_public:
15138       /* The assumed value if neither private nor protected.  */
15139       break;
15140     case DW_ACCESS_private:
15141       fp.is_private = 1;
15142       break;
15143     case DW_ACCESS_protected:
15144       fp.is_protected = 1;
15145       break;
15146     default:
15147       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15148     }
15149
15150   if (die->tag == DW_TAG_typedef)
15151     fip->typedef_field_list.push_back (fp);
15152   else
15153     fip->nested_types_list.push_back (fp);
15154 }
15155
15156 /* Create the vector of fields, and attach it to the type.  */
15157
15158 static void
15159 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15160                               struct dwarf2_cu *cu)
15161 {
15162   int nfields = fip->nfields;
15163
15164   /* Record the field count, allocate space for the array of fields,
15165      and create blank accessibility bitfields if necessary.  */
15166   TYPE_NFIELDS (type) = nfields;
15167   TYPE_FIELDS (type) = (struct field *)
15168     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15169
15170   if (fip->non_public_fields && cu->language != language_ada)
15171     {
15172       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15173
15174       TYPE_FIELD_PRIVATE_BITS (type) =
15175         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15176       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15177
15178       TYPE_FIELD_PROTECTED_BITS (type) =
15179         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15180       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15181
15182       TYPE_FIELD_IGNORE_BITS (type) =
15183         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15184       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15185     }
15186
15187   /* If the type has baseclasses, allocate and clear a bit vector for
15188      TYPE_FIELD_VIRTUAL_BITS.  */
15189   if (!fip->baseclasses.empty () && cu->language != language_ada)
15190     {
15191       int num_bytes = B_BYTES (fip->baseclasses.size ());
15192       unsigned char *pointer;
15193
15194       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15195       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15196       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15197       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15198       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15199     }
15200
15201   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15202     {
15203       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15204
15205       for (int index = 0; index < nfields; ++index)
15206         {
15207           struct nextfield &field = fip->fields[index];
15208
15209           if (field.variant.is_discriminant)
15210             di->discriminant_index = index;
15211           else if (field.variant.default_branch)
15212             di->default_index = index;
15213           else
15214             di->discriminants[index] = field.variant.discriminant_value;
15215         }
15216     }
15217
15218   /* Copy the saved-up fields into the field vector.  */
15219   for (int i = 0; i < nfields; ++i)
15220     {
15221       struct nextfield &field
15222         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15223            : fip->fields[i - fip->baseclasses.size ()]);
15224
15225       TYPE_FIELD (type, i) = field.field;
15226       switch (field.accessibility)
15227         {
15228         case DW_ACCESS_private:
15229           if (cu->language != language_ada)
15230             SET_TYPE_FIELD_PRIVATE (type, i);
15231           break;
15232
15233         case DW_ACCESS_protected:
15234           if (cu->language != language_ada)
15235             SET_TYPE_FIELD_PROTECTED (type, i);
15236           break;
15237
15238         case DW_ACCESS_public:
15239           break;
15240
15241         default:
15242           /* Unknown accessibility.  Complain and treat it as public.  */
15243           {
15244             complaint (_("unsupported accessibility %d"),
15245                        field.accessibility);
15246           }
15247           break;
15248         }
15249       if (i < fip->baseclasses.size ())
15250         {
15251           switch (field.virtuality)
15252             {
15253             case DW_VIRTUALITY_virtual:
15254             case DW_VIRTUALITY_pure_virtual:
15255               if (cu->language == language_ada)
15256                 error (_("unexpected virtuality in component of Ada type"));
15257               SET_TYPE_FIELD_VIRTUAL (type, i);
15258               break;
15259             }
15260         }
15261     }
15262 }
15263
15264 /* Return true if this member function is a constructor, false
15265    otherwise.  */
15266
15267 static int
15268 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15269 {
15270   const char *fieldname;
15271   const char *type_name;
15272   int len;
15273
15274   if (die->parent == NULL)
15275     return 0;
15276
15277   if (die->parent->tag != DW_TAG_structure_type
15278       && die->parent->tag != DW_TAG_union_type
15279       && die->parent->tag != DW_TAG_class_type)
15280     return 0;
15281
15282   fieldname = dwarf2_name (die, cu);
15283   type_name = dwarf2_name (die->parent, cu);
15284   if (fieldname == NULL || type_name == NULL)
15285     return 0;
15286
15287   len = strlen (fieldname);
15288   return (strncmp (fieldname, type_name, len) == 0
15289           && (type_name[len] == '\0' || type_name[len] == '<'));
15290 }
15291
15292 /* Add a member function to the proper fieldlist.  */
15293
15294 static void
15295 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15296                       struct type *type, struct dwarf2_cu *cu)
15297 {
15298   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15299   struct attribute *attr;
15300   int i;
15301   struct fnfieldlist *flp = nullptr;
15302   struct fn_field *fnp;
15303   const char *fieldname;
15304   struct type *this_type;
15305   enum dwarf_access_attribute accessibility;
15306
15307   if (cu->language == language_ada)
15308     error (_("unexpected member function in Ada type"));
15309
15310   /* Get name of member function.  */
15311   fieldname = dwarf2_name (die, cu);
15312   if (fieldname == NULL)
15313     return;
15314
15315   /* Look up member function name in fieldlist.  */
15316   for (i = 0; i < fip->fnfieldlists.size (); i++)
15317     {
15318       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15319         {
15320           flp = &fip->fnfieldlists[i];
15321           break;
15322         }
15323     }
15324
15325   /* Create a new fnfieldlist if necessary.  */
15326   if (flp == nullptr)
15327     {
15328       fip->fnfieldlists.emplace_back ();
15329       flp = &fip->fnfieldlists.back ();
15330       flp->name = fieldname;
15331       i = fip->fnfieldlists.size () - 1;
15332     }
15333
15334   /* Create a new member function field and add it to the vector of
15335      fnfieldlists.  */
15336   flp->fnfields.emplace_back ();
15337   fnp = &flp->fnfields.back ();
15338
15339   /* Delay processing of the physname until later.  */
15340   if (cu->language == language_cplus)
15341     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15342                         die, cu);
15343   else
15344     {
15345       const char *physname = dwarf2_physname (fieldname, die, cu);
15346       fnp->physname = physname ? physname : "";
15347     }
15348
15349   fnp->type = alloc_type (objfile);
15350   this_type = read_type_die (die, cu);
15351   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15352     {
15353       int nparams = TYPE_NFIELDS (this_type);
15354
15355       /* TYPE is the domain of this method, and THIS_TYPE is the type
15356            of the method itself (TYPE_CODE_METHOD).  */
15357       smash_to_method_type (fnp->type, type,
15358                             TYPE_TARGET_TYPE (this_type),
15359                             TYPE_FIELDS (this_type),
15360                             TYPE_NFIELDS (this_type),
15361                             TYPE_VARARGS (this_type));
15362
15363       /* Handle static member functions.
15364          Dwarf2 has no clean way to discern C++ static and non-static
15365          member functions.  G++ helps GDB by marking the first
15366          parameter for non-static member functions (which is the this
15367          pointer) as artificial.  We obtain this information from
15368          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15369       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15370         fnp->voffset = VOFFSET_STATIC;
15371     }
15372   else
15373     complaint (_("member function type missing for '%s'"),
15374                dwarf2_full_name (fieldname, die, cu));
15375
15376   /* Get fcontext from DW_AT_containing_type if present.  */
15377   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15378     fnp->fcontext = die_containing_type (die, cu);
15379
15380   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15381      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15382
15383   /* Get accessibility.  */
15384   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15385   if (attr)
15386     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15387   else
15388     accessibility = dwarf2_default_access_attribute (die, cu);
15389   switch (accessibility)
15390     {
15391     case DW_ACCESS_private:
15392       fnp->is_private = 1;
15393       break;
15394     case DW_ACCESS_protected:
15395       fnp->is_protected = 1;
15396       break;
15397     }
15398
15399   /* Check for artificial methods.  */
15400   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15401   if (attr && DW_UNSND (attr) != 0)
15402     fnp->is_artificial = 1;
15403
15404   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15405
15406   /* Get index in virtual function table if it is a virtual member
15407      function.  For older versions of GCC, this is an offset in the
15408      appropriate virtual table, as specified by DW_AT_containing_type.
15409      For everyone else, it is an expression to be evaluated relative
15410      to the object address.  */
15411
15412   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15413   if (attr)
15414     {
15415       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15416         {
15417           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15418             {
15419               /* Old-style GCC.  */
15420               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15421             }
15422           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15423                    || (DW_BLOCK (attr)->size > 1
15424                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15425                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15426             {
15427               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15428               if ((fnp->voffset % cu->header.addr_size) != 0)
15429                 dwarf2_complex_location_expr_complaint ();
15430               else
15431                 fnp->voffset /= cu->header.addr_size;
15432               fnp->voffset += 2;
15433             }
15434           else
15435             dwarf2_complex_location_expr_complaint ();
15436
15437           if (!fnp->fcontext)
15438             {
15439               /* If there is no `this' field and no DW_AT_containing_type,
15440                  we cannot actually find a base class context for the
15441                  vtable!  */
15442               if (TYPE_NFIELDS (this_type) == 0
15443                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15444                 {
15445                   complaint (_("cannot determine context for virtual member "
15446                                "function \"%s\" (offset %s)"),
15447                              fieldname, sect_offset_str (die->sect_off));
15448                 }
15449               else
15450                 {
15451                   fnp->fcontext
15452                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15453                 }
15454             }
15455         }
15456       else if (attr_form_is_section_offset (attr))
15457         {
15458           dwarf2_complex_location_expr_complaint ();
15459         }
15460       else
15461         {
15462           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15463                                                  fieldname);
15464         }
15465     }
15466   else
15467     {
15468       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15469       if (attr && DW_UNSND (attr))
15470         {
15471           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15472           complaint (_("Member function \"%s\" (offset %s) is virtual "
15473                        "but the vtable offset is not specified"),
15474                      fieldname, sect_offset_str (die->sect_off));
15475           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15476           TYPE_CPLUS_DYNAMIC (type) = 1;
15477         }
15478     }
15479 }
15480
15481 /* Create the vector of member function fields, and attach it to the type.  */
15482
15483 static void
15484 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15485                                  struct dwarf2_cu *cu)
15486 {
15487   if (cu->language == language_ada)
15488     error (_("unexpected member functions in Ada type"));
15489
15490   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15491   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15492     TYPE_ALLOC (type,
15493                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15494
15495   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15496     {
15497       struct fnfieldlist &nf = fip->fnfieldlists[i];
15498       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15499
15500       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15501       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15502       fn_flp->fn_fields = (struct fn_field *)
15503         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15504
15505       for (int k = 0; k < nf.fnfields.size (); ++k)
15506         fn_flp->fn_fields[k] = nf.fnfields[k];
15507     }
15508
15509   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15510 }
15511
15512 /* Returns non-zero if NAME is the name of a vtable member in CU's
15513    language, zero otherwise.  */
15514 static int
15515 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15516 {
15517   static const char vptr[] = "_vptr";
15518
15519   /* Look for the C++ form of the vtable.  */
15520   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15521     return 1;
15522
15523   return 0;
15524 }
15525
15526 /* GCC outputs unnamed structures that are really pointers to member
15527    functions, with the ABI-specified layout.  If TYPE describes
15528    such a structure, smash it into a member function type.
15529
15530    GCC shouldn't do this; it should just output pointer to member DIEs.
15531    This is GCC PR debug/28767.  */
15532
15533 static void
15534 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15535 {
15536   struct type *pfn_type, *self_type, *new_type;
15537
15538   /* Check for a structure with no name and two children.  */
15539   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15540     return;
15541
15542   /* Check for __pfn and __delta members.  */
15543   if (TYPE_FIELD_NAME (type, 0) == NULL
15544       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15545       || TYPE_FIELD_NAME (type, 1) == NULL
15546       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15547     return;
15548
15549   /* Find the type of the method.  */
15550   pfn_type = TYPE_FIELD_TYPE (type, 0);
15551   if (pfn_type == NULL
15552       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15553       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15554     return;
15555
15556   /* Look for the "this" argument.  */
15557   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15558   if (TYPE_NFIELDS (pfn_type) == 0
15559       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15560       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15561     return;
15562
15563   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15564   new_type = alloc_type (objfile);
15565   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15566                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15567                         TYPE_VARARGS (pfn_type));
15568   smash_to_methodptr_type (type, new_type);
15569 }
15570
15571 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15572    appropriate error checking and issuing complaints if there is a
15573    problem.  */
15574
15575 static ULONGEST
15576 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15577 {
15578   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15579
15580   if (attr == nullptr)
15581     return 0;
15582
15583   if (!attr_form_is_constant (attr))
15584     {
15585       complaint (_("DW_AT_alignment must have constant form"
15586                    " - DIE at %s [in module %s]"),
15587                  sect_offset_str (die->sect_off),
15588                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15589       return 0;
15590     }
15591
15592   ULONGEST align;
15593   if (attr->form == DW_FORM_sdata)
15594     {
15595       LONGEST val = DW_SND (attr);
15596       if (val < 0)
15597         {
15598           complaint (_("DW_AT_alignment value must not be negative"
15599                        " - DIE at %s [in module %s]"),
15600                      sect_offset_str (die->sect_off),
15601                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15602           return 0;
15603         }
15604       align = val;
15605     }
15606   else
15607     align = DW_UNSND (attr);
15608
15609   if (align == 0)
15610     {
15611       complaint (_("DW_AT_alignment value must not be zero"
15612                    " - DIE at %s [in module %s]"),
15613                  sect_offset_str (die->sect_off),
15614                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15615       return 0;
15616     }
15617   if ((align & (align - 1)) != 0)
15618     {
15619       complaint (_("DW_AT_alignment value must be a power of 2"
15620                    " - DIE at %s [in module %s]"),
15621                  sect_offset_str (die->sect_off),
15622                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15623       return 0;
15624     }
15625
15626   return align;
15627 }
15628
15629 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15630    the alignment for TYPE.  */
15631
15632 static void
15633 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15634                      struct type *type)
15635 {
15636   if (!set_type_align (type, get_alignment (cu, die)))
15637     complaint (_("DW_AT_alignment value too large"
15638                  " - DIE at %s [in module %s]"),
15639                sect_offset_str (die->sect_off),
15640                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15641 }
15642
15643 /* Called when we find the DIE that starts a structure or union scope
15644    (definition) to create a type for the structure or union.  Fill in
15645    the type's name and general properties; the members will not be
15646    processed until process_structure_scope.  A symbol table entry for
15647    the type will also not be done until process_structure_scope (assuming
15648    the type has a name).
15649
15650    NOTE: we need to call these functions regardless of whether or not the
15651    DIE has a DW_AT_name attribute, since it might be an anonymous
15652    structure or union.  This gets the type entered into our set of
15653    user defined types.  */
15654
15655 static struct type *
15656 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15657 {
15658   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15659   struct type *type;
15660   struct attribute *attr;
15661   const char *name;
15662
15663   /* If the definition of this type lives in .debug_types, read that type.
15664      Don't follow DW_AT_specification though, that will take us back up
15665      the chain and we want to go down.  */
15666   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15667   if (attr)
15668     {
15669       type = get_DW_AT_signature_type (die, attr, cu);
15670
15671       /* The type's CU may not be the same as CU.
15672          Ensure TYPE is recorded with CU in die_type_hash.  */
15673       return set_die_type (die, type, cu);
15674     }
15675
15676   type = alloc_type (objfile);
15677   INIT_CPLUS_SPECIFIC (type);
15678
15679   name = dwarf2_name (die, cu);
15680   if (name != NULL)
15681     {
15682       if (cu->language == language_cplus
15683           || cu->language == language_d
15684           || cu->language == language_rust)
15685         {
15686           const char *full_name = dwarf2_full_name (name, die, cu);
15687
15688           /* dwarf2_full_name might have already finished building the DIE's
15689              type.  If so, there is no need to continue.  */
15690           if (get_die_type (die, cu) != NULL)
15691             return get_die_type (die, cu);
15692
15693           TYPE_NAME (type) = full_name;
15694         }
15695       else
15696         {
15697           /* The name is already allocated along with this objfile, so
15698              we don't need to duplicate it for the type.  */
15699           TYPE_NAME (type) = name;
15700         }
15701     }
15702
15703   if (die->tag == DW_TAG_structure_type)
15704     {
15705       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15706     }
15707   else if (die->tag == DW_TAG_union_type)
15708     {
15709       TYPE_CODE (type) = TYPE_CODE_UNION;
15710     }
15711   else if (die->tag == DW_TAG_variant_part)
15712     {
15713       TYPE_CODE (type) = TYPE_CODE_UNION;
15714       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15715     }
15716   else
15717     {
15718       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15719     }
15720
15721   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15722     TYPE_DECLARED_CLASS (type) = 1;
15723
15724   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15725   if (attr)
15726     {
15727       if (attr_form_is_constant (attr))
15728         TYPE_LENGTH (type) = DW_UNSND (attr);
15729       else
15730         {
15731           /* For the moment, dynamic type sizes are not supported
15732              by GDB's struct type.  The actual size is determined
15733              on-demand when resolving the type of a given object,
15734              so set the type's length to zero for now.  Otherwise,
15735              we record an expression as the length, and that expression
15736              could lead to a very large value, which could eventually
15737              lead to us trying to allocate that much memory when creating
15738              a value of that type.  */
15739           TYPE_LENGTH (type) = 0;
15740         }
15741     }
15742   else
15743     {
15744       TYPE_LENGTH (type) = 0;
15745     }
15746
15747   maybe_set_alignment (cu, die, type);
15748
15749   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15750     {
15751       /* ICC<14 does not output the required DW_AT_declaration on
15752          incomplete types, but gives them a size of zero.  */
15753       TYPE_STUB (type) = 1;
15754     }
15755   else
15756     TYPE_STUB_SUPPORTED (type) = 1;
15757
15758   if (die_is_declaration (die, cu))
15759     TYPE_STUB (type) = 1;
15760   else if (attr == NULL && die->child == NULL
15761            && producer_is_realview (cu->producer))
15762     /* RealView does not output the required DW_AT_declaration
15763        on incomplete types.  */
15764     TYPE_STUB (type) = 1;
15765
15766   /* We need to add the type field to the die immediately so we don't
15767      infinitely recurse when dealing with pointers to the structure
15768      type within the structure itself.  */
15769   set_die_type (die, type, cu);
15770
15771   /* set_die_type should be already done.  */
15772   set_descriptive_type (type, die, cu);
15773
15774   return type;
15775 }
15776
15777 /* A helper for process_structure_scope that handles a single member
15778    DIE.  */
15779
15780 static void
15781 handle_struct_member_die (struct die_info *child_die, struct type *type,
15782                           struct field_info *fi,
15783                           std::vector<struct symbol *> *template_args,
15784                           struct dwarf2_cu *cu)
15785 {
15786   if (child_die->tag == DW_TAG_member
15787       || child_die->tag == DW_TAG_variable
15788       || child_die->tag == DW_TAG_variant_part)
15789     {
15790       /* NOTE: carlton/2002-11-05: A C++ static data member
15791          should be a DW_TAG_member that is a declaration, but
15792          all versions of G++ as of this writing (so through at
15793          least 3.2.1) incorrectly generate DW_TAG_variable
15794          tags for them instead.  */
15795       dwarf2_add_field (fi, child_die, cu);
15796     }
15797   else if (child_die->tag == DW_TAG_subprogram)
15798     {
15799       /* Rust doesn't have member functions in the C++ sense.
15800          However, it does emit ordinary functions as children
15801          of a struct DIE.  */
15802       if (cu->language == language_rust)
15803         read_func_scope (child_die, cu);
15804       else
15805         {
15806           /* C++ member function.  */
15807           dwarf2_add_member_fn (fi, child_die, type, cu);
15808         }
15809     }
15810   else if (child_die->tag == DW_TAG_inheritance)
15811     {
15812       /* C++ base class field.  */
15813       dwarf2_add_field (fi, child_die, cu);
15814     }
15815   else if (type_can_define_types (child_die))
15816     dwarf2_add_type_defn (fi, child_die, cu);
15817   else if (child_die->tag == DW_TAG_template_type_param
15818            || child_die->tag == DW_TAG_template_value_param)
15819     {
15820       struct symbol *arg = new_symbol (child_die, NULL, cu);
15821
15822       if (arg != NULL)
15823         template_args->push_back (arg);
15824     }
15825   else if (child_die->tag == DW_TAG_variant)
15826     {
15827       /* In a variant we want to get the discriminant and also add a
15828          field for our sole member child.  */
15829       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15830
15831       for (struct die_info *variant_child = child_die->child;
15832            variant_child != NULL;
15833            variant_child = sibling_die (variant_child))
15834         {
15835           if (variant_child->tag == DW_TAG_member)
15836             {
15837               handle_struct_member_die (variant_child, type, fi,
15838                                         template_args, cu);
15839               /* Only handle the one.  */
15840               break;
15841             }
15842         }
15843
15844       /* We don't handle this but we might as well report it if we see
15845          it.  */
15846       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15847           complaint (_("DW_AT_discr_list is not supported yet"
15848                        " - DIE at %s [in module %s]"),
15849                      sect_offset_str (child_die->sect_off),
15850                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15851
15852       /* The first field was just added, so we can stash the
15853          discriminant there.  */
15854       gdb_assert (!fi->fields.empty ());
15855       if (discr == NULL)
15856         fi->fields.back ().variant.default_branch = true;
15857       else
15858         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15859     }
15860 }
15861
15862 /* Finish creating a structure or union type, including filling in
15863    its members and creating a symbol for it.  */
15864
15865 static void
15866 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15867 {
15868   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15869   struct die_info *child_die;
15870   struct type *type;
15871
15872   type = get_die_type (die, cu);
15873   if (type == NULL)
15874     type = read_structure_type (die, cu);
15875
15876   /* When reading a DW_TAG_variant_part, we need to notice when we
15877      read the discriminant member, so we can record it later in the
15878      discriminant_info.  */
15879   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15880   sect_offset discr_offset;
15881   bool has_template_parameters = false;
15882
15883   if (is_variant_part)
15884     {
15885       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15886       if (discr == NULL)
15887         {
15888           /* Maybe it's a univariant form, an extension we support.
15889              In this case arrange not to check the offset.  */
15890           is_variant_part = false;
15891         }
15892       else if (attr_form_is_ref (discr))
15893         {
15894           struct dwarf2_cu *target_cu = cu;
15895           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15896
15897           discr_offset = target_die->sect_off;
15898         }
15899       else
15900         {
15901           complaint (_("DW_AT_discr does not have DIE reference form"
15902                        " - DIE at %s [in module %s]"),
15903                      sect_offset_str (die->sect_off),
15904                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15905           is_variant_part = false;
15906         }
15907     }
15908
15909   if (die->child != NULL && ! die_is_declaration (die, cu))
15910     {
15911       struct field_info fi;
15912       std::vector<struct symbol *> template_args;
15913
15914       child_die = die->child;
15915
15916       while (child_die && child_die->tag)
15917         {
15918           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15919
15920           if (is_variant_part && discr_offset == child_die->sect_off)
15921             fi.fields.back ().variant.is_discriminant = true;
15922
15923           child_die = sibling_die (child_die);
15924         }
15925
15926       /* Attach template arguments to type.  */
15927       if (!template_args.empty ())
15928         {
15929           has_template_parameters = true;
15930           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15931           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15932           TYPE_TEMPLATE_ARGUMENTS (type)
15933             = XOBNEWVEC (&objfile->objfile_obstack,
15934                          struct symbol *,
15935                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15936           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15937                   template_args.data (),
15938                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15939                    * sizeof (struct symbol *)));
15940         }
15941
15942       /* Attach fields and member functions to the type.  */
15943       if (fi.nfields)
15944         dwarf2_attach_fields_to_type (&fi, type, cu);
15945       if (!fi.fnfieldlists.empty ())
15946         {
15947           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15948
15949           /* Get the type which refers to the base class (possibly this
15950              class itself) which contains the vtable pointer for the current
15951              class from the DW_AT_containing_type attribute.  This use of
15952              DW_AT_containing_type is a GNU extension.  */
15953
15954           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15955             {
15956               struct type *t = die_containing_type (die, cu);
15957
15958               set_type_vptr_basetype (type, t);
15959               if (type == t)
15960                 {
15961                   int i;
15962
15963                   /* Our own class provides vtbl ptr.  */
15964                   for (i = TYPE_NFIELDS (t) - 1;
15965                        i >= TYPE_N_BASECLASSES (t);
15966                        --i)
15967                     {
15968                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15969
15970                       if (is_vtable_name (fieldname, cu))
15971                         {
15972                           set_type_vptr_fieldno (type, i);
15973                           break;
15974                         }
15975                     }
15976
15977                   /* Complain if virtual function table field not found.  */
15978                   if (i < TYPE_N_BASECLASSES (t))
15979                     complaint (_("virtual function table pointer "
15980                                  "not found when defining class '%s'"),
15981                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
15982                 }
15983               else
15984                 {
15985                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15986                 }
15987             }
15988           else if (cu->producer
15989                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15990             {
15991               /* The IBM XLC compiler does not provide direct indication
15992                  of the containing type, but the vtable pointer is
15993                  always named __vfp.  */
15994
15995               int i;
15996
15997               for (i = TYPE_NFIELDS (type) - 1;
15998                    i >= TYPE_N_BASECLASSES (type);
15999                    --i)
16000                 {
16001                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16002                     {
16003                       set_type_vptr_fieldno (type, i);
16004                       set_type_vptr_basetype (type, type);
16005                       break;
16006                     }
16007                 }
16008             }
16009         }
16010
16011       /* Copy fi.typedef_field_list linked list elements content into the
16012          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16013       if (!fi.typedef_field_list.empty ())
16014         {
16015           int count = fi.typedef_field_list.size ();
16016
16017           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16018           TYPE_TYPEDEF_FIELD_ARRAY (type)
16019             = ((struct decl_field *)
16020                TYPE_ALLOC (type,
16021                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16022           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16023
16024           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16025             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16026         }
16027
16028       /* Copy fi.nested_types_list linked list elements content into the
16029          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16030       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16031         {
16032           int count = fi.nested_types_list.size ();
16033
16034           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16035           TYPE_NESTED_TYPES_ARRAY (type)
16036             = ((struct decl_field *)
16037                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16038           TYPE_NESTED_TYPES_COUNT (type) = count;
16039
16040           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16041             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16042         }
16043     }
16044
16045   quirk_gcc_member_function_pointer (type, objfile);
16046   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16047     cu->rust_unions.push_back (type);
16048
16049   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16050      snapshots) has been known to create a die giving a declaration
16051      for a class that has, as a child, a die giving a definition for a
16052      nested class.  So we have to process our children even if the
16053      current die is a declaration.  Normally, of course, a declaration
16054      won't have any children at all.  */
16055
16056   child_die = die->child;
16057
16058   while (child_die != NULL && child_die->tag)
16059     {
16060       if (child_die->tag == DW_TAG_member
16061           || child_die->tag == DW_TAG_variable
16062           || child_die->tag == DW_TAG_inheritance
16063           || child_die->tag == DW_TAG_template_value_param
16064           || child_die->tag == DW_TAG_template_type_param)
16065         {
16066           /* Do nothing.  */
16067         }
16068       else
16069         process_die (child_die, cu);
16070
16071       child_die = sibling_die (child_die);
16072     }
16073
16074   /* Do not consider external references.  According to the DWARF standard,
16075      these DIEs are identified by the fact that they have no byte_size
16076      attribute, and a declaration attribute.  */
16077   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16078       || !die_is_declaration (die, cu))
16079     {
16080       struct symbol *sym = new_symbol (die, type, cu);
16081
16082       if (has_template_parameters)
16083         {
16084           /* Make sure that the symtab is set on the new symbols.
16085              Even though they don't appear in this symtab directly,
16086              other parts of gdb assume that symbols do, and this is
16087              reasonably true.  */
16088           for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
16089             symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i),
16090                                symbol_symtab (sym));
16091         }
16092     }
16093 }
16094
16095 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16096    update TYPE using some information only available in DIE's children.  */
16097
16098 static void
16099 update_enumeration_type_from_children (struct die_info *die,
16100                                        struct type *type,
16101                                        struct dwarf2_cu *cu)
16102 {
16103   struct die_info *child_die;
16104   int unsigned_enum = 1;
16105   int flag_enum = 1;
16106   ULONGEST mask = 0;
16107
16108   auto_obstack obstack;
16109
16110   for (child_die = die->child;
16111        child_die != NULL && child_die->tag;
16112        child_die = sibling_die (child_die))
16113     {
16114       struct attribute *attr;
16115       LONGEST value;
16116       const gdb_byte *bytes;
16117       struct dwarf2_locexpr_baton *baton;
16118       const char *name;
16119
16120       if (child_die->tag != DW_TAG_enumerator)
16121         continue;
16122
16123       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16124       if (attr == NULL)
16125         continue;
16126
16127       name = dwarf2_name (child_die, cu);
16128       if (name == NULL)
16129         name = "<anonymous enumerator>";
16130
16131       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16132                                &value, &bytes, &baton);
16133       if (value < 0)
16134         {
16135           unsigned_enum = 0;
16136           flag_enum = 0;
16137         }
16138       else if ((mask & value) != 0)
16139         flag_enum = 0;
16140       else
16141         mask |= value;
16142
16143       /* If we already know that the enum type is neither unsigned, nor
16144          a flag type, no need to look at the rest of the enumerates.  */
16145       if (!unsigned_enum && !flag_enum)
16146         break;
16147     }
16148
16149   if (unsigned_enum)
16150     TYPE_UNSIGNED (type) = 1;
16151   if (flag_enum)
16152     TYPE_FLAG_ENUM (type) = 1;
16153 }
16154
16155 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16156    complete the type's fields yet, or create any symbols.  */
16157
16158 static struct type *
16159 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16160 {
16161   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16162   struct type *type;
16163   struct attribute *attr;
16164   const char *name;
16165
16166   /* If the definition of this type lives in .debug_types, read that type.
16167      Don't follow DW_AT_specification though, that will take us back up
16168      the chain and we want to go down.  */
16169   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16170   if (attr)
16171     {
16172       type = get_DW_AT_signature_type (die, attr, cu);
16173
16174       /* The type's CU may not be the same as CU.
16175          Ensure TYPE is recorded with CU in die_type_hash.  */
16176       return set_die_type (die, type, cu);
16177     }
16178
16179   type = alloc_type (objfile);
16180
16181   TYPE_CODE (type) = TYPE_CODE_ENUM;
16182   name = dwarf2_full_name (NULL, die, cu);
16183   if (name != NULL)
16184     TYPE_NAME (type) = name;
16185
16186   attr = dwarf2_attr (die, DW_AT_type, cu);
16187   if (attr != NULL)
16188     {
16189       struct type *underlying_type = die_type (die, cu);
16190
16191       TYPE_TARGET_TYPE (type) = underlying_type;
16192     }
16193
16194   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16195   if (attr)
16196     {
16197       TYPE_LENGTH (type) = DW_UNSND (attr);
16198     }
16199   else
16200     {
16201       TYPE_LENGTH (type) = 0;
16202     }
16203
16204   maybe_set_alignment (cu, die, type);
16205
16206   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16207      declared as private in the package spec, and then defined only
16208      inside the package body.  Such types are known as Taft Amendment
16209      Types.  When another package uses such a type, an incomplete DIE
16210      may be generated by the compiler.  */
16211   if (die_is_declaration (die, cu))
16212     TYPE_STUB (type) = 1;
16213
16214   /* Finish the creation of this type by using the enum's children.
16215      We must call this even when the underlying type has been provided
16216      so that we can determine if we're looking at a "flag" enum.  */
16217   update_enumeration_type_from_children (die, type, cu);
16218
16219   /* If this type has an underlying type that is not a stub, then we
16220      may use its attributes.  We always use the "unsigned" attribute
16221      in this situation, because ordinarily we guess whether the type
16222      is unsigned -- but the guess can be wrong and the underlying type
16223      can tell us the reality.  However, we defer to a local size
16224      attribute if one exists, because this lets the compiler override
16225      the underlying type if needed.  */
16226   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16227     {
16228       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16229       if (TYPE_LENGTH (type) == 0)
16230         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16231       if (TYPE_RAW_ALIGN (type) == 0
16232           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16233         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16234     }
16235
16236   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16237
16238   return set_die_type (die, type, cu);
16239 }
16240
16241 /* Given a pointer to a die which begins an enumeration, process all
16242    the dies that define the members of the enumeration, and create the
16243    symbol for the enumeration type.
16244
16245    NOTE: We reverse the order of the element list.  */
16246
16247 static void
16248 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16249 {
16250   struct type *this_type;
16251
16252   this_type = get_die_type (die, cu);
16253   if (this_type == NULL)
16254     this_type = read_enumeration_type (die, cu);
16255
16256   if (die->child != NULL)
16257     {
16258       struct die_info *child_die;
16259       struct symbol *sym;
16260       struct field *fields = NULL;
16261       int num_fields = 0;
16262       const char *name;
16263
16264       child_die = die->child;
16265       while (child_die && child_die->tag)
16266         {
16267           if (child_die->tag != DW_TAG_enumerator)
16268             {
16269               process_die (child_die, cu);
16270             }
16271           else
16272             {
16273               name = dwarf2_name (child_die, cu);
16274               if (name)
16275                 {
16276                   sym = new_symbol (child_die, this_type, cu);
16277
16278                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16279                     {
16280                       fields = (struct field *)
16281                         xrealloc (fields,
16282                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16283                                   * sizeof (struct field));
16284                     }
16285
16286                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16287                   FIELD_TYPE (fields[num_fields]) = NULL;
16288                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16289                   FIELD_BITSIZE (fields[num_fields]) = 0;
16290
16291                   num_fields++;
16292                 }
16293             }
16294
16295           child_die = sibling_die (child_die);
16296         }
16297
16298       if (num_fields)
16299         {
16300           TYPE_NFIELDS (this_type) = num_fields;
16301           TYPE_FIELDS (this_type) = (struct field *)
16302             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16303           memcpy (TYPE_FIELDS (this_type), fields,
16304                   sizeof (struct field) * num_fields);
16305           xfree (fields);
16306         }
16307     }
16308
16309   /* If we are reading an enum from a .debug_types unit, and the enum
16310      is a declaration, and the enum is not the signatured type in the
16311      unit, then we do not want to add a symbol for it.  Adding a
16312      symbol would in some cases obscure the true definition of the
16313      enum, giving users an incomplete type when the definition is
16314      actually available.  Note that we do not want to do this for all
16315      enums which are just declarations, because C++0x allows forward
16316      enum declarations.  */
16317   if (cu->per_cu->is_debug_types
16318       && die_is_declaration (die, cu))
16319     {
16320       struct signatured_type *sig_type;
16321
16322       sig_type = (struct signatured_type *) cu->per_cu;
16323       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16324       if (sig_type->type_offset_in_section != die->sect_off)
16325         return;
16326     }
16327
16328   new_symbol (die, this_type, cu);
16329 }
16330
16331 /* Extract all information from a DW_TAG_array_type DIE and put it in
16332    the DIE's type field.  For now, this only handles one dimensional
16333    arrays.  */
16334
16335 static struct type *
16336 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16337 {
16338   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16339   struct die_info *child_die;
16340   struct type *type;
16341   struct type *element_type, *range_type, *index_type;
16342   struct attribute *attr;
16343   const char *name;
16344   struct dynamic_prop *byte_stride_prop = NULL;
16345   unsigned int bit_stride = 0;
16346
16347   element_type = die_type (die, cu);
16348
16349   /* The die_type call above may have already set the type for this DIE.  */
16350   type = get_die_type (die, cu);
16351   if (type)
16352     return type;
16353
16354   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16355   if (attr != NULL)
16356     {
16357       int stride_ok;
16358
16359       byte_stride_prop
16360         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16361       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16362       if (!stride_ok)
16363         {
16364           complaint (_("unable to read array DW_AT_byte_stride "
16365                        " - DIE at %s [in module %s]"),
16366                      sect_offset_str (die->sect_off),
16367                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16368           /* Ignore this attribute.  We will likely not be able to print
16369              arrays of this type correctly, but there is little we can do
16370              to help if we cannot read the attribute's value.  */
16371           byte_stride_prop = NULL;
16372         }
16373     }
16374
16375   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16376   if (attr != NULL)
16377     bit_stride = DW_UNSND (attr);
16378
16379   /* Irix 6.2 native cc creates array types without children for
16380      arrays with unspecified length.  */
16381   if (die->child == NULL)
16382     {
16383       index_type = objfile_type (objfile)->builtin_int;
16384       range_type = create_static_range_type (NULL, index_type, 0, -1);
16385       type = create_array_type_with_stride (NULL, element_type, range_type,
16386                                             byte_stride_prop, bit_stride);
16387       return set_die_type (die, type, cu);
16388     }
16389
16390   std::vector<struct type *> range_types;
16391   child_die = die->child;
16392   while (child_die && child_die->tag)
16393     {
16394       if (child_die->tag == DW_TAG_subrange_type)
16395         {
16396           struct type *child_type = read_type_die (child_die, cu);
16397
16398           if (child_type != NULL)
16399             {
16400               /* The range type was succesfully read.  Save it for the
16401                  array type creation.  */
16402               range_types.push_back (child_type);
16403             }
16404         }
16405       child_die = sibling_die (child_die);
16406     }
16407
16408   /* Dwarf2 dimensions are output from left to right, create the
16409      necessary array types in backwards order.  */
16410
16411   type = element_type;
16412
16413   if (read_array_order (die, cu) == DW_ORD_col_major)
16414     {
16415       int i = 0;
16416
16417       while (i < range_types.size ())
16418         type = create_array_type_with_stride (NULL, type, range_types[i++],
16419                                               byte_stride_prop, bit_stride);
16420     }
16421   else
16422     {
16423       size_t ndim = range_types.size ();
16424       while (ndim-- > 0)
16425         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16426                                               byte_stride_prop, bit_stride);
16427     }
16428
16429   /* Understand Dwarf2 support for vector types (like they occur on
16430      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16431      array type.  This is not part of the Dwarf2/3 standard yet, but a
16432      custom vendor extension.  The main difference between a regular
16433      array and the vector variant is that vectors are passed by value
16434      to functions.  */
16435   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16436   if (attr)
16437     make_vector_type (type);
16438
16439   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16440      implementation may choose to implement triple vectors using this
16441      attribute.  */
16442   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16443   if (attr)
16444     {
16445       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16446         TYPE_LENGTH (type) = DW_UNSND (attr);
16447       else
16448         complaint (_("DW_AT_byte_size for array type smaller "
16449                      "than the total size of elements"));
16450     }
16451
16452   name = dwarf2_name (die, cu);
16453   if (name)
16454     TYPE_NAME (type) = name;
16455
16456   maybe_set_alignment (cu, die, type);
16457
16458   /* Install the type in the die.  */
16459   set_die_type (die, type, cu);
16460
16461   /* set_die_type should be already done.  */
16462   set_descriptive_type (type, die, cu);
16463
16464   return type;
16465 }
16466
16467 static enum dwarf_array_dim_ordering
16468 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16469 {
16470   struct attribute *attr;
16471
16472   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16473
16474   if (attr)
16475     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16476
16477   /* GNU F77 is a special case, as at 08/2004 array type info is the
16478      opposite order to the dwarf2 specification, but data is still
16479      laid out as per normal fortran.
16480
16481      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16482      version checking.  */
16483
16484   if (cu->language == language_fortran
16485       && cu->producer && strstr (cu->producer, "GNU F77"))
16486     {
16487       return DW_ORD_row_major;
16488     }
16489
16490   switch (cu->language_defn->la_array_ordering)
16491     {
16492     case array_column_major:
16493       return DW_ORD_col_major;
16494     case array_row_major:
16495     default:
16496       return DW_ORD_row_major;
16497     };
16498 }
16499
16500 /* Extract all information from a DW_TAG_set_type DIE and put it in
16501    the DIE's type field.  */
16502
16503 static struct type *
16504 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16505 {
16506   struct type *domain_type, *set_type;
16507   struct attribute *attr;
16508
16509   domain_type = die_type (die, cu);
16510
16511   /* The die_type call above may have already set the type for this DIE.  */
16512   set_type = get_die_type (die, cu);
16513   if (set_type)
16514     return set_type;
16515
16516   set_type = create_set_type (NULL, domain_type);
16517
16518   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16519   if (attr)
16520     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16521
16522   maybe_set_alignment (cu, die, set_type);
16523
16524   return set_die_type (die, set_type, cu);
16525 }
16526
16527 /* A helper for read_common_block that creates a locexpr baton.
16528    SYM is the symbol which we are marking as computed.
16529    COMMON_DIE is the DIE for the common block.
16530    COMMON_LOC is the location expression attribute for the common
16531    block itself.
16532    MEMBER_LOC is the location expression attribute for the particular
16533    member of the common block that we are processing.
16534    CU is the CU from which the above come.  */
16535
16536 static void
16537 mark_common_block_symbol_computed (struct symbol *sym,
16538                                    struct die_info *common_die,
16539                                    struct attribute *common_loc,
16540                                    struct attribute *member_loc,
16541                                    struct dwarf2_cu *cu)
16542 {
16543   struct dwarf2_per_objfile *dwarf2_per_objfile
16544     = cu->per_cu->dwarf2_per_objfile;
16545   struct objfile *objfile = dwarf2_per_objfile->objfile;
16546   struct dwarf2_locexpr_baton *baton;
16547   gdb_byte *ptr;
16548   unsigned int cu_off;
16549   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16550   LONGEST offset = 0;
16551
16552   gdb_assert (common_loc && member_loc);
16553   gdb_assert (attr_form_is_block (common_loc));
16554   gdb_assert (attr_form_is_block (member_loc)
16555               || attr_form_is_constant (member_loc));
16556
16557   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16558   baton->per_cu = cu->per_cu;
16559   gdb_assert (baton->per_cu);
16560
16561   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16562
16563   if (attr_form_is_constant (member_loc))
16564     {
16565       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16566       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16567     }
16568   else
16569     baton->size += DW_BLOCK (member_loc)->size;
16570
16571   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16572   baton->data = ptr;
16573
16574   *ptr++ = DW_OP_call4;
16575   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16576   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16577   ptr += 4;
16578
16579   if (attr_form_is_constant (member_loc))
16580     {
16581       *ptr++ = DW_OP_addr;
16582       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16583       ptr += cu->header.addr_size;
16584     }
16585   else
16586     {
16587       /* We have to copy the data here, because DW_OP_call4 will only
16588          use a DW_AT_location attribute.  */
16589       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16590       ptr += DW_BLOCK (member_loc)->size;
16591     }
16592
16593   *ptr++ = DW_OP_plus;
16594   gdb_assert (ptr - baton->data == baton->size);
16595
16596   SYMBOL_LOCATION_BATON (sym) = baton;
16597   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16598 }
16599
16600 /* Create appropriate locally-scoped variables for all the
16601    DW_TAG_common_block entries.  Also create a struct common_block
16602    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16603    is used to sepate the common blocks name namespace from regular
16604    variable names.  */
16605
16606 static void
16607 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16608 {
16609   struct attribute *attr;
16610
16611   attr = dwarf2_attr (die, DW_AT_location, cu);
16612   if (attr)
16613     {
16614       /* Support the .debug_loc offsets.  */
16615       if (attr_form_is_block (attr))
16616         {
16617           /* Ok.  */
16618         }
16619       else if (attr_form_is_section_offset (attr))
16620         {
16621           dwarf2_complex_location_expr_complaint ();
16622           attr = NULL;
16623         }
16624       else
16625         {
16626           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16627                                                  "common block member");
16628           attr = NULL;
16629         }
16630     }
16631
16632   if (die->child != NULL)
16633     {
16634       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16635       struct die_info *child_die;
16636       size_t n_entries = 0, size;
16637       struct common_block *common_block;
16638       struct symbol *sym;
16639
16640       for (child_die = die->child;
16641            child_die && child_die->tag;
16642            child_die = sibling_die (child_die))
16643         ++n_entries;
16644
16645       size = (sizeof (struct common_block)
16646               + (n_entries - 1) * sizeof (struct symbol *));
16647       common_block
16648         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16649                                                  size);
16650       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16651       common_block->n_entries = 0;
16652
16653       for (child_die = die->child;
16654            child_die && child_die->tag;
16655            child_die = sibling_die (child_die))
16656         {
16657           /* Create the symbol in the DW_TAG_common_block block in the current
16658              symbol scope.  */
16659           sym = new_symbol (child_die, NULL, cu);
16660           if (sym != NULL)
16661             {
16662               struct attribute *member_loc;
16663
16664               common_block->contents[common_block->n_entries++] = sym;
16665
16666               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16667                                         cu);
16668               if (member_loc)
16669                 {
16670                   /* GDB has handled this for a long time, but it is
16671                      not specified by DWARF.  It seems to have been
16672                      emitted by gfortran at least as recently as:
16673                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16674                   complaint (_("Variable in common block has "
16675                                "DW_AT_data_member_location "
16676                                "- DIE at %s [in module %s]"),
16677                                sect_offset_str (child_die->sect_off),
16678                              objfile_name (objfile));
16679
16680                   if (attr_form_is_section_offset (member_loc))
16681                     dwarf2_complex_location_expr_complaint ();
16682                   else if (attr_form_is_constant (member_loc)
16683                            || attr_form_is_block (member_loc))
16684                     {
16685                       if (attr)
16686                         mark_common_block_symbol_computed (sym, die, attr,
16687                                                            member_loc, cu);
16688                     }
16689                   else
16690                     dwarf2_complex_location_expr_complaint ();
16691                 }
16692             }
16693         }
16694
16695       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16696       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16697     }
16698 }
16699
16700 /* Create a type for a C++ namespace.  */
16701
16702 static struct type *
16703 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16704 {
16705   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16706   const char *previous_prefix, *name;
16707   int is_anonymous;
16708   struct type *type;
16709
16710   /* For extensions, reuse the type of the original namespace.  */
16711   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16712     {
16713       struct die_info *ext_die;
16714       struct dwarf2_cu *ext_cu = cu;
16715
16716       ext_die = dwarf2_extension (die, &ext_cu);
16717       type = read_type_die (ext_die, ext_cu);
16718
16719       /* EXT_CU may not be the same as CU.
16720          Ensure TYPE is recorded with CU in die_type_hash.  */
16721       return set_die_type (die, type, cu);
16722     }
16723
16724   name = namespace_name (die, &is_anonymous, cu);
16725
16726   /* Now build the name of the current namespace.  */
16727
16728   previous_prefix = determine_prefix (die, cu);
16729   if (previous_prefix[0] != '\0')
16730     name = typename_concat (&objfile->objfile_obstack,
16731                             previous_prefix, name, 0, cu);
16732
16733   /* Create the type.  */
16734   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16735
16736   return set_die_type (die, type, cu);
16737 }
16738
16739 /* Read a namespace scope.  */
16740
16741 static void
16742 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16743 {
16744   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16745   int is_anonymous;
16746
16747   /* Add a symbol associated to this if we haven't seen the namespace
16748      before.  Also, add a using directive if it's an anonymous
16749      namespace.  */
16750
16751   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16752     {
16753       struct type *type;
16754
16755       type = read_type_die (die, cu);
16756       new_symbol (die, type, cu);
16757
16758       namespace_name (die, &is_anonymous, cu);
16759       if (is_anonymous)
16760         {
16761           const char *previous_prefix = determine_prefix (die, cu);
16762
16763           std::vector<const char *> excludes;
16764           add_using_directive (using_directives (cu),
16765                                previous_prefix, TYPE_NAME (type), NULL,
16766                                NULL, excludes, 0, &objfile->objfile_obstack);
16767         }
16768     }
16769
16770   if (die->child != NULL)
16771     {
16772       struct die_info *child_die = die->child;
16773
16774       while (child_die && child_die->tag)
16775         {
16776           process_die (child_die, cu);
16777           child_die = sibling_die (child_die);
16778         }
16779     }
16780 }
16781
16782 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16783    imported module.  Still we need that type as local Fortran "use ... only"
16784    declaration imports depend on the created type in determine_prefix.  */
16785
16786 static struct type *
16787 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16788 {
16789   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16790   const char *module_name;
16791   struct type *type;
16792
16793   module_name = dwarf2_name (die, cu);
16794   if (!module_name)
16795     complaint (_("DW_TAG_module has no name, offset %s"),
16796                sect_offset_str (die->sect_off));
16797   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16798
16799   return set_die_type (die, type, cu);
16800 }
16801
16802 /* Read a Fortran module.  */
16803
16804 static void
16805 read_module (struct die_info *die, struct dwarf2_cu *cu)
16806 {
16807   struct die_info *child_die = die->child;
16808   struct type *type;
16809
16810   type = read_type_die (die, cu);
16811   new_symbol (die, type, cu);
16812
16813   while (child_die && child_die->tag)
16814     {
16815       process_die (child_die, cu);
16816       child_die = sibling_die (child_die);
16817     }
16818 }
16819
16820 /* Return the name of the namespace represented by DIE.  Set
16821    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16822    namespace.  */
16823
16824 static const char *
16825 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16826 {
16827   struct die_info *current_die;
16828   const char *name = NULL;
16829
16830   /* Loop through the extensions until we find a name.  */
16831
16832   for (current_die = die;
16833        current_die != NULL;
16834        current_die = dwarf2_extension (die, &cu))
16835     {
16836       /* We don't use dwarf2_name here so that we can detect the absence
16837          of a name -> anonymous namespace.  */
16838       name = dwarf2_string_attr (die, DW_AT_name, cu);
16839
16840       if (name != NULL)
16841         break;
16842     }
16843
16844   /* Is it an anonymous namespace?  */
16845
16846   *is_anonymous = (name == NULL);
16847   if (*is_anonymous)
16848     name = CP_ANONYMOUS_NAMESPACE_STR;
16849
16850   return name;
16851 }
16852
16853 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16854    the user defined type vector.  */
16855
16856 static struct type *
16857 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16858 {
16859   struct gdbarch *gdbarch
16860     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16861   struct comp_unit_head *cu_header = &cu->header;
16862   struct type *type;
16863   struct attribute *attr_byte_size;
16864   struct attribute *attr_address_class;
16865   int byte_size, addr_class;
16866   struct type *target_type;
16867
16868   target_type = die_type (die, cu);
16869
16870   /* The die_type call above may have already set the type for this DIE.  */
16871   type = get_die_type (die, cu);
16872   if (type)
16873     return type;
16874
16875   type = lookup_pointer_type (target_type);
16876
16877   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16878   if (attr_byte_size)
16879     byte_size = DW_UNSND (attr_byte_size);
16880   else
16881     byte_size = cu_header->addr_size;
16882
16883   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16884   if (attr_address_class)
16885     addr_class = DW_UNSND (attr_address_class);
16886   else
16887     addr_class = DW_ADDR_none;
16888
16889   ULONGEST alignment = get_alignment (cu, die);
16890
16891   /* If the pointer size, alignment, or address class is different
16892      than the default, create a type variant marked as such and set
16893      the length accordingly.  */
16894   if (TYPE_LENGTH (type) != byte_size
16895       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16896           && alignment != TYPE_RAW_ALIGN (type))
16897       || addr_class != DW_ADDR_none)
16898     {
16899       if (gdbarch_address_class_type_flags_p (gdbarch))
16900         {
16901           int type_flags;
16902
16903           type_flags = gdbarch_address_class_type_flags
16904                          (gdbarch, byte_size, addr_class);
16905           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16906                       == 0);
16907           type = make_type_with_address_space (type, type_flags);
16908         }
16909       else if (TYPE_LENGTH (type) != byte_size)
16910         {
16911           complaint (_("invalid pointer size %d"), byte_size);
16912         }
16913       else if (TYPE_RAW_ALIGN (type) != alignment)
16914         {
16915           complaint (_("Invalid DW_AT_alignment"
16916                        " - DIE at %s [in module %s]"),
16917                      sect_offset_str (die->sect_off),
16918                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16919         }
16920       else
16921         {
16922           /* Should we also complain about unhandled address classes?  */
16923         }
16924     }
16925
16926   TYPE_LENGTH (type) = byte_size;
16927   set_type_align (type, alignment);
16928   return set_die_type (die, type, cu);
16929 }
16930
16931 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16932    the user defined type vector.  */
16933
16934 static struct type *
16935 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16936 {
16937   struct type *type;
16938   struct type *to_type;
16939   struct type *domain;
16940
16941   to_type = die_type (die, cu);
16942   domain = die_containing_type (die, cu);
16943
16944   /* The calls above may have already set the type for this DIE.  */
16945   type = get_die_type (die, cu);
16946   if (type)
16947     return type;
16948
16949   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16950     type = lookup_methodptr_type (to_type);
16951   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16952     {
16953       struct type *new_type
16954         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16955
16956       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16957                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16958                             TYPE_VARARGS (to_type));
16959       type = lookup_methodptr_type (new_type);
16960     }
16961   else
16962     type = lookup_memberptr_type (to_type, domain);
16963
16964   return set_die_type (die, type, cu);
16965 }
16966
16967 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16968    the user defined type vector.  */
16969
16970 static struct type *
16971 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16972                           enum type_code refcode)
16973 {
16974   struct comp_unit_head *cu_header = &cu->header;
16975   struct type *type, *target_type;
16976   struct attribute *attr;
16977
16978   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16979
16980   target_type = die_type (die, cu);
16981
16982   /* The die_type call above may have already set the type for this DIE.  */
16983   type = get_die_type (die, cu);
16984   if (type)
16985     return type;
16986
16987   type = lookup_reference_type (target_type, refcode);
16988   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16989   if (attr)
16990     {
16991       TYPE_LENGTH (type) = DW_UNSND (attr);
16992     }
16993   else
16994     {
16995       TYPE_LENGTH (type) = cu_header->addr_size;
16996     }
16997   maybe_set_alignment (cu, die, type);
16998   return set_die_type (die, type, cu);
16999 }
17000
17001 /* Add the given cv-qualifiers to the element type of the array.  GCC
17002    outputs DWARF type qualifiers that apply to an array, not the
17003    element type.  But GDB relies on the array element type to carry
17004    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17005    specification.  */
17006
17007 static struct type *
17008 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17009                    struct type *base_type, int cnst, int voltl)
17010 {
17011   struct type *el_type, *inner_array;
17012
17013   base_type = copy_type (base_type);
17014   inner_array = base_type;
17015
17016   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17017     {
17018       TYPE_TARGET_TYPE (inner_array) =
17019         copy_type (TYPE_TARGET_TYPE (inner_array));
17020       inner_array = TYPE_TARGET_TYPE (inner_array);
17021     }
17022
17023   el_type = TYPE_TARGET_TYPE (inner_array);
17024   cnst |= TYPE_CONST (el_type);
17025   voltl |= TYPE_VOLATILE (el_type);
17026   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17027
17028   return set_die_type (die, base_type, cu);
17029 }
17030
17031 static struct type *
17032 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17033 {
17034   struct type *base_type, *cv_type;
17035
17036   base_type = die_type (die, cu);
17037
17038   /* The die_type call above may have already set the type for this DIE.  */
17039   cv_type = get_die_type (die, cu);
17040   if (cv_type)
17041     return cv_type;
17042
17043   /* In case the const qualifier is applied to an array type, the element type
17044      is so qualified, not the array type (section 6.7.3 of C99).  */
17045   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17046     return add_array_cv_type (die, cu, base_type, 1, 0);
17047
17048   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17049   return set_die_type (die, cv_type, cu);
17050 }
17051
17052 static struct type *
17053 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17054 {
17055   struct type *base_type, *cv_type;
17056
17057   base_type = die_type (die, cu);
17058
17059   /* The die_type call above may have already set the type for this DIE.  */
17060   cv_type = get_die_type (die, cu);
17061   if (cv_type)
17062     return cv_type;
17063
17064   /* In case the volatile qualifier is applied to an array type, the
17065      element type is so qualified, not the array type (section 6.7.3
17066      of C99).  */
17067   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17068     return add_array_cv_type (die, cu, base_type, 0, 1);
17069
17070   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17071   return set_die_type (die, cv_type, cu);
17072 }
17073
17074 /* Handle DW_TAG_restrict_type.  */
17075
17076 static struct type *
17077 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17078 {
17079   struct type *base_type, *cv_type;
17080
17081   base_type = die_type (die, cu);
17082
17083   /* The die_type call above may have already set the type for this DIE.  */
17084   cv_type = get_die_type (die, cu);
17085   if (cv_type)
17086     return cv_type;
17087
17088   cv_type = make_restrict_type (base_type);
17089   return set_die_type (die, cv_type, cu);
17090 }
17091
17092 /* Handle DW_TAG_atomic_type.  */
17093
17094 static struct type *
17095 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17096 {
17097   struct type *base_type, *cv_type;
17098
17099   base_type = die_type (die, cu);
17100
17101   /* The die_type call above may have already set the type for this DIE.  */
17102   cv_type = get_die_type (die, cu);
17103   if (cv_type)
17104     return cv_type;
17105
17106   cv_type = make_atomic_type (base_type);
17107   return set_die_type (die, cv_type, cu);
17108 }
17109
17110 /* Extract all information from a DW_TAG_string_type DIE and add to
17111    the user defined type vector.  It isn't really a user defined type,
17112    but it behaves like one, with other DIE's using an AT_user_def_type
17113    attribute to reference it.  */
17114
17115 static struct type *
17116 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17117 {
17118   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17119   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17120   struct type *type, *range_type, *index_type, *char_type;
17121   struct attribute *attr;
17122   unsigned int length;
17123
17124   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17125   if (attr)
17126     {
17127       length = DW_UNSND (attr);
17128     }
17129   else
17130     {
17131       /* Check for the DW_AT_byte_size attribute.  */
17132       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17133       if (attr)
17134         {
17135           length = DW_UNSND (attr);
17136         }
17137       else
17138         {
17139           length = 1;
17140         }
17141     }
17142
17143   index_type = objfile_type (objfile)->builtin_int;
17144   range_type = create_static_range_type (NULL, index_type, 1, length);
17145   char_type = language_string_char_type (cu->language_defn, gdbarch);
17146   type = create_string_type (NULL, char_type, range_type);
17147
17148   return set_die_type (die, type, cu);
17149 }
17150
17151 /* Assuming that DIE corresponds to a function, returns nonzero
17152    if the function is prototyped.  */
17153
17154 static int
17155 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17156 {
17157   struct attribute *attr;
17158
17159   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17160   if (attr && (DW_UNSND (attr) != 0))
17161     return 1;
17162
17163   /* The DWARF standard implies that the DW_AT_prototyped attribute
17164      is only meaninful for C, but the concept also extends to other
17165      languages that allow unprototyped functions (Eg: Objective C).
17166      For all other languages, assume that functions are always
17167      prototyped.  */
17168   if (cu->language != language_c
17169       && cu->language != language_objc
17170       && cu->language != language_opencl)
17171     return 1;
17172
17173   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17174      prototyped and unprototyped functions; default to prototyped,
17175      since that is more common in modern code (and RealView warns
17176      about unprototyped functions).  */
17177   if (producer_is_realview (cu->producer))
17178     return 1;
17179
17180   return 0;
17181 }
17182
17183 /* Handle DIES due to C code like:
17184
17185    struct foo
17186    {
17187    int (*funcp)(int a, long l);
17188    int b;
17189    };
17190
17191    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17192
17193 static struct type *
17194 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17195 {
17196   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17197   struct type *type;            /* Type that this function returns.  */
17198   struct type *ftype;           /* Function that returns above type.  */
17199   struct attribute *attr;
17200
17201   type = die_type (die, cu);
17202
17203   /* The die_type call above may have already set the type for this DIE.  */
17204   ftype = get_die_type (die, cu);
17205   if (ftype)
17206     return ftype;
17207
17208   ftype = lookup_function_type (type);
17209
17210   if (prototyped_function_p (die, cu))
17211     TYPE_PROTOTYPED (ftype) = 1;
17212
17213   /* Store the calling convention in the type if it's available in
17214      the subroutine die.  Otherwise set the calling convention to
17215      the default value DW_CC_normal.  */
17216   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17217   if (attr)
17218     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17219   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17220     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17221   else
17222     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17223
17224   /* Record whether the function returns normally to its caller or not
17225      if the DWARF producer set that information.  */
17226   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17227   if (attr && (DW_UNSND (attr) != 0))
17228     TYPE_NO_RETURN (ftype) = 1;
17229
17230   /* We need to add the subroutine type to the die immediately so
17231      we don't infinitely recurse when dealing with parameters
17232      declared as the same subroutine type.  */
17233   set_die_type (die, ftype, cu);
17234
17235   if (die->child != NULL)
17236     {
17237       struct type *void_type = objfile_type (objfile)->builtin_void;
17238       struct die_info *child_die;
17239       int nparams, iparams;
17240
17241       /* Count the number of parameters.
17242          FIXME: GDB currently ignores vararg functions, but knows about
17243          vararg member functions.  */
17244       nparams = 0;
17245       child_die = die->child;
17246       while (child_die && child_die->tag)
17247         {
17248           if (child_die->tag == DW_TAG_formal_parameter)
17249             nparams++;
17250           else if (child_die->tag == DW_TAG_unspecified_parameters)
17251             TYPE_VARARGS (ftype) = 1;
17252           child_die = sibling_die (child_die);
17253         }
17254
17255       /* Allocate storage for parameters and fill them in.  */
17256       TYPE_NFIELDS (ftype) = nparams;
17257       TYPE_FIELDS (ftype) = (struct field *)
17258         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17259
17260       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17261          even if we error out during the parameters reading below.  */
17262       for (iparams = 0; iparams < nparams; iparams++)
17263         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17264
17265       iparams = 0;
17266       child_die = die->child;
17267       while (child_die && child_die->tag)
17268         {
17269           if (child_die->tag == DW_TAG_formal_parameter)
17270             {
17271               struct type *arg_type;
17272
17273               /* DWARF version 2 has no clean way to discern C++
17274                  static and non-static member functions.  G++ helps
17275                  GDB by marking the first parameter for non-static
17276                  member functions (which is the this pointer) as
17277                  artificial.  We pass this information to
17278                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17279
17280                  DWARF version 3 added DW_AT_object_pointer, which GCC
17281                  4.5 does not yet generate.  */
17282               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17283               if (attr)
17284                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17285               else
17286                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17287               arg_type = die_type (child_die, cu);
17288
17289               /* RealView does not mark THIS as const, which the testsuite
17290                  expects.  GCC marks THIS as const in method definitions,
17291                  but not in the class specifications (GCC PR 43053).  */
17292               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17293                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17294                 {
17295                   int is_this = 0;
17296                   struct dwarf2_cu *arg_cu = cu;
17297                   const char *name = dwarf2_name (child_die, cu);
17298
17299                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17300                   if (attr)
17301                     {
17302                       /* If the compiler emits this, use it.  */
17303                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17304                         is_this = 1;
17305                     }
17306                   else if (name && strcmp (name, "this") == 0)
17307                     /* Function definitions will have the argument names.  */
17308                     is_this = 1;
17309                   else if (name == NULL && iparams == 0)
17310                     /* Declarations may not have the names, so like
17311                        elsewhere in GDB, assume an artificial first
17312                        argument is "this".  */
17313                     is_this = 1;
17314
17315                   if (is_this)
17316                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17317                                              arg_type, 0);
17318                 }
17319
17320               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17321               iparams++;
17322             }
17323           child_die = sibling_die (child_die);
17324         }
17325     }
17326
17327   return ftype;
17328 }
17329
17330 static struct type *
17331 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17332 {
17333   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17334   const char *name = NULL;
17335   struct type *this_type, *target_type;
17336
17337   name = dwarf2_full_name (NULL, die, cu);
17338   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17339   TYPE_TARGET_STUB (this_type) = 1;
17340   set_die_type (die, this_type, cu);
17341   target_type = die_type (die, cu);
17342   if (target_type != this_type)
17343     TYPE_TARGET_TYPE (this_type) = target_type;
17344   else
17345     {
17346       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17347          spec and cause infinite loops in GDB.  */
17348       complaint (_("Self-referential DW_TAG_typedef "
17349                    "- DIE at %s [in module %s]"),
17350                  sect_offset_str (die->sect_off), objfile_name (objfile));
17351       TYPE_TARGET_TYPE (this_type) = NULL;
17352     }
17353   return this_type;
17354 }
17355
17356 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17357    (which may be different from NAME) to the architecture back-end to allow
17358    it to guess the correct format if necessary.  */
17359
17360 static struct type *
17361 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17362                         const char *name_hint)
17363 {
17364   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17365   const struct floatformat **format;
17366   struct type *type;
17367
17368   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17369   if (format)
17370     type = init_float_type (objfile, bits, name, format);
17371   else
17372     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17373
17374   return type;
17375 }
17376
17377 /* Find a representation of a given base type and install
17378    it in the TYPE field of the die.  */
17379
17380 static struct type *
17381 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17382 {
17383   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17384   struct type *type;
17385   struct attribute *attr;
17386   int encoding = 0, bits = 0;
17387   const char *name;
17388
17389   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17390   if (attr)
17391     {
17392       encoding = DW_UNSND (attr);
17393     }
17394   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17395   if (attr)
17396     {
17397       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17398     }
17399   name = dwarf2_name (die, cu);
17400   if (!name)
17401     {
17402       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17403     }
17404
17405   switch (encoding)
17406     {
17407       case DW_ATE_address:
17408         /* Turn DW_ATE_address into a void * pointer.  */
17409         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17410         type = init_pointer_type (objfile, bits, name, type);
17411         break;
17412       case DW_ATE_boolean:
17413         type = init_boolean_type (objfile, bits, 1, name);
17414         break;
17415       case DW_ATE_complex_float:
17416         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17417         type = init_complex_type (objfile, name, type);
17418         break;
17419       case DW_ATE_decimal_float:
17420         type = init_decfloat_type (objfile, bits, name);
17421         break;
17422       case DW_ATE_float:
17423         type = dwarf2_init_float_type (objfile, bits, name, name);
17424         break;
17425       case DW_ATE_signed:
17426         type = init_integer_type (objfile, bits, 0, name);
17427         break;
17428       case DW_ATE_unsigned:
17429         if (cu->language == language_fortran
17430             && name
17431             && startswith (name, "character("))
17432           type = init_character_type (objfile, bits, 1, name);
17433         else
17434           type = init_integer_type (objfile, bits, 1, name);
17435         break;
17436       case DW_ATE_signed_char:
17437         if (cu->language == language_ada || cu->language == language_m2
17438             || cu->language == language_pascal
17439             || cu->language == language_fortran)
17440           type = init_character_type (objfile, bits, 0, name);
17441         else
17442           type = init_integer_type (objfile, bits, 0, name);
17443         break;
17444       case DW_ATE_unsigned_char:
17445         if (cu->language == language_ada || cu->language == language_m2
17446             || cu->language == language_pascal
17447             || cu->language == language_fortran
17448             || cu->language == language_rust)
17449           type = init_character_type (objfile, bits, 1, name);
17450         else
17451           type = init_integer_type (objfile, bits, 1, name);
17452         break;
17453       case DW_ATE_UTF:
17454         {
17455           gdbarch *arch = get_objfile_arch (objfile);
17456
17457           if (bits == 16)
17458             type = builtin_type (arch)->builtin_char16;
17459           else if (bits == 32)
17460             type = builtin_type (arch)->builtin_char32;
17461           else
17462             {
17463               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17464                          bits);
17465               type = init_integer_type (objfile, bits, 1, name);
17466             }
17467           return set_die_type (die, type, cu);
17468         }
17469         break;
17470
17471       default:
17472         complaint (_("unsupported DW_AT_encoding: '%s'"),
17473                    dwarf_type_encoding_name (encoding));
17474         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17475         break;
17476     }
17477
17478   if (name && strcmp (name, "char") == 0)
17479     TYPE_NOSIGN (type) = 1;
17480
17481   maybe_set_alignment (cu, die, type);
17482
17483   return set_die_type (die, type, cu);
17484 }
17485
17486 /* Parse dwarf attribute if it's a block, reference or constant and put the
17487    resulting value of the attribute into struct bound_prop.
17488    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17489
17490 static int
17491 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17492                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17493 {
17494   struct dwarf2_property_baton *baton;
17495   struct obstack *obstack
17496     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17497
17498   if (attr == NULL || prop == NULL)
17499     return 0;
17500
17501   if (attr_form_is_block (attr))
17502     {
17503       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17504       baton->referenced_type = NULL;
17505       baton->locexpr.per_cu = cu->per_cu;
17506       baton->locexpr.size = DW_BLOCK (attr)->size;
17507       baton->locexpr.data = DW_BLOCK (attr)->data;
17508       prop->data.baton = baton;
17509       prop->kind = PROP_LOCEXPR;
17510       gdb_assert (prop->data.baton != NULL);
17511     }
17512   else if (attr_form_is_ref (attr))
17513     {
17514       struct dwarf2_cu *target_cu = cu;
17515       struct die_info *target_die;
17516       struct attribute *target_attr;
17517
17518       target_die = follow_die_ref (die, attr, &target_cu);
17519       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17520       if (target_attr == NULL)
17521         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17522                                    target_cu);
17523       if (target_attr == NULL)
17524         return 0;
17525
17526       switch (target_attr->name)
17527         {
17528           case DW_AT_location:
17529             if (attr_form_is_section_offset (target_attr))
17530               {
17531                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17532                 baton->referenced_type = die_type (target_die, target_cu);
17533                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17534                 prop->data.baton = baton;
17535                 prop->kind = PROP_LOCLIST;
17536                 gdb_assert (prop->data.baton != NULL);
17537               }
17538             else if (attr_form_is_block (target_attr))
17539               {
17540                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17541                 baton->referenced_type = die_type (target_die, target_cu);
17542                 baton->locexpr.per_cu = cu->per_cu;
17543                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17544                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17545                 prop->data.baton = baton;
17546                 prop->kind = PROP_LOCEXPR;
17547                 gdb_assert (prop->data.baton != NULL);
17548               }
17549             else
17550               {
17551                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17552                                                        "dynamic property");
17553                 return 0;
17554               }
17555             break;
17556           case DW_AT_data_member_location:
17557             {
17558               LONGEST offset;
17559
17560               if (!handle_data_member_location (target_die, target_cu,
17561                                                 &offset))
17562                 return 0;
17563
17564               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17565               baton->referenced_type = read_type_die (target_die->parent,
17566                                                       target_cu);
17567               baton->offset_info.offset = offset;
17568               baton->offset_info.type = die_type (target_die, target_cu);
17569               prop->data.baton = baton;
17570               prop->kind = PROP_ADDR_OFFSET;
17571               break;
17572             }
17573         }
17574     }
17575   else if (attr_form_is_constant (attr))
17576     {
17577       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17578       prop->kind = PROP_CONST;
17579     }
17580   else
17581     {
17582       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17583                                              dwarf2_name (die, cu));
17584       return 0;
17585     }
17586
17587   return 1;
17588 }
17589
17590 /* Read the given DW_AT_subrange DIE.  */
17591
17592 static struct type *
17593 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17594 {
17595   struct type *base_type, *orig_base_type;
17596   struct type *range_type;
17597   struct attribute *attr;
17598   struct dynamic_prop low, high;
17599   int low_default_is_valid;
17600   int high_bound_is_count = 0;
17601   const char *name;
17602   LONGEST negative_mask;
17603
17604   orig_base_type = die_type (die, cu);
17605   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17606      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17607      creating the range type, but we use the result of check_typedef
17608      when examining properties of the type.  */
17609   base_type = check_typedef (orig_base_type);
17610
17611   /* The die_type call above may have already set the type for this DIE.  */
17612   range_type = get_die_type (die, cu);
17613   if (range_type)
17614     return range_type;
17615
17616   low.kind = PROP_CONST;
17617   high.kind = PROP_CONST;
17618   high.data.const_val = 0;
17619
17620   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17621      omitting DW_AT_lower_bound.  */
17622   switch (cu->language)
17623     {
17624     case language_c:
17625     case language_cplus:
17626       low.data.const_val = 0;
17627       low_default_is_valid = 1;
17628       break;
17629     case language_fortran:
17630       low.data.const_val = 1;
17631       low_default_is_valid = 1;
17632       break;
17633     case language_d:
17634     case language_objc:
17635     case language_rust:
17636       low.data.const_val = 0;
17637       low_default_is_valid = (cu->header.version >= 4);
17638       break;
17639     case language_ada:
17640     case language_m2:
17641     case language_pascal:
17642       low.data.const_val = 1;
17643       low_default_is_valid = (cu->header.version >= 4);
17644       break;
17645     default:
17646       low.data.const_val = 0;
17647       low_default_is_valid = 0;
17648       break;
17649     }
17650
17651   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17652   if (attr)
17653     attr_to_dynamic_prop (attr, die, cu, &low);
17654   else if (!low_default_is_valid)
17655     complaint (_("Missing DW_AT_lower_bound "
17656                                       "- DIE at %s [in module %s]"),
17657                sect_offset_str (die->sect_off),
17658                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17659
17660   struct attribute *attr_ub, *attr_count;
17661   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
17662   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17663     {
17664       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
17665       if (attr_to_dynamic_prop (attr, die, cu, &high))
17666         {
17667           /* If bounds are constant do the final calculation here.  */
17668           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17669             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17670           else
17671             high_bound_is_count = 1;
17672         }
17673       else
17674         {
17675           if (attr_ub != NULL)
17676             complaint (_("Unresolved DW_AT_upper_bound "
17677                          "- DIE at %s [in module %s]"),
17678                        sect_offset_str (die->sect_off),
17679                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17680           if (attr_count != NULL)
17681             complaint (_("Unresolved DW_AT_count "
17682                          "- DIE at %s [in module %s]"),
17683                        sect_offset_str (die->sect_off),
17684                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17685         }
17686         
17687     }
17688
17689   /* Dwarf-2 specifications explicitly allows to create subrange types
17690      without specifying a base type.
17691      In that case, the base type must be set to the type of
17692      the lower bound, upper bound or count, in that order, if any of these
17693      three attributes references an object that has a type.
17694      If no base type is found, the Dwarf-2 specifications say that
17695      a signed integer type of size equal to the size of an address should
17696      be used.
17697      For the following C code: `extern char gdb_int [];'
17698      GCC produces an empty range DIE.
17699      FIXME: muller/2010-05-28: Possible references to object for low bound,
17700      high bound or count are not yet handled by this code.  */
17701   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17702     {
17703       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17704       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17705       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17706       struct type *int_type = objfile_type (objfile)->builtin_int;
17707
17708       /* Test "int", "long int", and "long long int" objfile types,
17709          and select the first one having a size above or equal to the
17710          architecture address size.  */
17711       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17712         base_type = int_type;
17713       else
17714         {
17715           int_type = objfile_type (objfile)->builtin_long;
17716           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17717             base_type = int_type;
17718           else
17719             {
17720               int_type = objfile_type (objfile)->builtin_long_long;
17721               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17722                 base_type = int_type;
17723             }
17724         }
17725     }
17726
17727   /* Normally, the DWARF producers are expected to use a signed
17728      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17729      But this is unfortunately not always the case, as witnessed
17730      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17731      is used instead.  To work around that ambiguity, we treat
17732      the bounds as signed, and thus sign-extend their values, when
17733      the base type is signed.  */
17734   negative_mask =
17735     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17736   if (low.kind == PROP_CONST
17737       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17738     low.data.const_val |= negative_mask;
17739   if (high.kind == PROP_CONST
17740       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17741     high.data.const_val |= negative_mask;
17742
17743   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17744
17745   if (high_bound_is_count)
17746     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17747
17748   /* Ada expects an empty array on no boundary attributes.  */
17749   if (attr == NULL && cu->language != language_ada)
17750     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17751
17752   name = dwarf2_name (die, cu);
17753   if (name)
17754     TYPE_NAME (range_type) = name;
17755
17756   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17757   if (attr)
17758     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17759
17760   maybe_set_alignment (cu, die, range_type);
17761
17762   set_die_type (die, range_type, cu);
17763
17764   /* set_die_type should be already done.  */
17765   set_descriptive_type (range_type, die, cu);
17766
17767   return range_type;
17768 }
17769
17770 static struct type *
17771 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17772 {
17773   struct type *type;
17774
17775   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17776                     NULL);
17777   TYPE_NAME (type) = dwarf2_name (die, cu);
17778
17779   /* In Ada, an unspecified type is typically used when the description
17780      of the type is defered to a different unit.  When encountering
17781      such a type, we treat it as a stub, and try to resolve it later on,
17782      when needed.  */
17783   if (cu->language == language_ada)
17784     TYPE_STUB (type) = 1;
17785
17786   return set_die_type (die, type, cu);
17787 }
17788
17789 /* Read a single die and all its descendents.  Set the die's sibling
17790    field to NULL; set other fields in the die correctly, and set all
17791    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17792    location of the info_ptr after reading all of those dies.  PARENT
17793    is the parent of the die in question.  */
17794
17795 static struct die_info *
17796 read_die_and_children (const struct die_reader_specs *reader,
17797                        const gdb_byte *info_ptr,
17798                        const gdb_byte **new_info_ptr,
17799                        struct die_info *parent)
17800 {
17801   struct die_info *die;
17802   const gdb_byte *cur_ptr;
17803   int has_children;
17804
17805   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17806   if (die == NULL)
17807     {
17808       *new_info_ptr = cur_ptr;
17809       return NULL;
17810     }
17811   store_in_ref_table (die, reader->cu);
17812
17813   if (has_children)
17814     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17815   else
17816     {
17817       die->child = NULL;
17818       *new_info_ptr = cur_ptr;
17819     }
17820
17821   die->sibling = NULL;
17822   die->parent = parent;
17823   return die;
17824 }
17825
17826 /* Read a die, all of its descendents, and all of its siblings; set
17827    all of the fields of all of the dies correctly.  Arguments are as
17828    in read_die_and_children.  */
17829
17830 static struct die_info *
17831 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17832                          const gdb_byte *info_ptr,
17833                          const gdb_byte **new_info_ptr,
17834                          struct die_info *parent)
17835 {
17836   struct die_info *first_die, *last_sibling;
17837   const gdb_byte *cur_ptr;
17838
17839   cur_ptr = info_ptr;
17840   first_die = last_sibling = NULL;
17841
17842   while (1)
17843     {
17844       struct die_info *die
17845         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17846
17847       if (die == NULL)
17848         {
17849           *new_info_ptr = cur_ptr;
17850           return first_die;
17851         }
17852
17853       if (!first_die)
17854         first_die = die;
17855       else
17856         last_sibling->sibling = die;
17857
17858       last_sibling = die;
17859     }
17860 }
17861
17862 /* Read a die, all of its descendents, and all of its siblings; set
17863    all of the fields of all of the dies correctly.  Arguments are as
17864    in read_die_and_children.
17865    This the main entry point for reading a DIE and all its children.  */
17866
17867 static struct die_info *
17868 read_die_and_siblings (const struct die_reader_specs *reader,
17869                        const gdb_byte *info_ptr,
17870                        const gdb_byte **new_info_ptr,
17871                        struct die_info *parent)
17872 {
17873   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17874                                                   new_info_ptr, parent);
17875
17876   if (dwarf_die_debug)
17877     {
17878       fprintf_unfiltered (gdb_stdlog,
17879                           "Read die from %s@0x%x of %s:\n",
17880                           get_section_name (reader->die_section),
17881                           (unsigned) (info_ptr - reader->die_section->buffer),
17882                           bfd_get_filename (reader->abfd));
17883       dump_die (die, dwarf_die_debug);
17884     }
17885
17886   return die;
17887 }
17888
17889 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17890    attributes.
17891    The caller is responsible for filling in the extra attributes
17892    and updating (*DIEP)->num_attrs.
17893    Set DIEP to point to a newly allocated die with its information,
17894    except for its child, sibling, and parent fields.
17895    Set HAS_CHILDREN to tell whether the die has children or not.  */
17896
17897 static const gdb_byte *
17898 read_full_die_1 (const struct die_reader_specs *reader,
17899                  struct die_info **diep, const gdb_byte *info_ptr,
17900                  int *has_children, int num_extra_attrs)
17901 {
17902   unsigned int abbrev_number, bytes_read, i;
17903   struct abbrev_info *abbrev;
17904   struct die_info *die;
17905   struct dwarf2_cu *cu = reader->cu;
17906   bfd *abfd = reader->abfd;
17907
17908   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17909   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17910   info_ptr += bytes_read;
17911   if (!abbrev_number)
17912     {
17913       *diep = NULL;
17914       *has_children = 0;
17915       return info_ptr;
17916     }
17917
17918   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17919   if (!abbrev)
17920     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17921            abbrev_number,
17922            bfd_get_filename (abfd));
17923
17924   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17925   die->sect_off = sect_off;
17926   die->tag = abbrev->tag;
17927   die->abbrev = abbrev_number;
17928
17929   /* Make the result usable.
17930      The caller needs to update num_attrs after adding the extra
17931      attributes.  */
17932   die->num_attrs = abbrev->num_attrs;
17933
17934   for (i = 0; i < abbrev->num_attrs; ++i)
17935     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17936                                info_ptr);
17937
17938   *diep = die;
17939   *has_children = abbrev->has_children;
17940   return info_ptr;
17941 }
17942
17943 /* Read a die and all its attributes.
17944    Set DIEP to point to a newly allocated die with its information,
17945    except for its child, sibling, and parent fields.
17946    Set HAS_CHILDREN to tell whether the die has children or not.  */
17947
17948 static const gdb_byte *
17949 read_full_die (const struct die_reader_specs *reader,
17950                struct die_info **diep, const gdb_byte *info_ptr,
17951                int *has_children)
17952 {
17953   const gdb_byte *result;
17954
17955   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17956
17957   if (dwarf_die_debug)
17958     {
17959       fprintf_unfiltered (gdb_stdlog,
17960                           "Read die from %s@0x%x of %s:\n",
17961                           get_section_name (reader->die_section),
17962                           (unsigned) (info_ptr - reader->die_section->buffer),
17963                           bfd_get_filename (reader->abfd));
17964       dump_die (*diep, dwarf_die_debug);
17965     }
17966
17967   return result;
17968 }
17969 \f
17970 /* Abbreviation tables.
17971
17972    In DWARF version 2, the description of the debugging information is
17973    stored in a separate .debug_abbrev section.  Before we read any
17974    dies from a section we read in all abbreviations and install them
17975    in a hash table.  */
17976
17977 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17978
17979 struct abbrev_info *
17980 abbrev_table::alloc_abbrev ()
17981 {
17982   struct abbrev_info *abbrev;
17983
17984   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
17985   memset (abbrev, 0, sizeof (struct abbrev_info));
17986
17987   return abbrev;
17988 }
17989
17990 /* Add an abbreviation to the table.  */
17991
17992 void
17993 abbrev_table::add_abbrev (unsigned int abbrev_number,
17994                           struct abbrev_info *abbrev)
17995 {
17996   unsigned int hash_number;
17997
17998   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17999   abbrev->next = m_abbrevs[hash_number];
18000   m_abbrevs[hash_number] = abbrev;
18001 }
18002
18003 /* Look up an abbrev in the table.
18004    Returns NULL if the abbrev is not found.  */
18005
18006 struct abbrev_info *
18007 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18008 {
18009   unsigned int hash_number;
18010   struct abbrev_info *abbrev;
18011
18012   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18013   abbrev = m_abbrevs[hash_number];
18014
18015   while (abbrev)
18016     {
18017       if (abbrev->number == abbrev_number)
18018         return abbrev;
18019       abbrev = abbrev->next;
18020     }
18021   return NULL;
18022 }
18023
18024 /* Read in an abbrev table.  */
18025
18026 static abbrev_table_up
18027 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18028                          struct dwarf2_section_info *section,
18029                          sect_offset sect_off)
18030 {
18031   struct objfile *objfile = dwarf2_per_objfile->objfile;
18032   bfd *abfd = get_section_bfd_owner (section);
18033   const gdb_byte *abbrev_ptr;
18034   struct abbrev_info *cur_abbrev;
18035   unsigned int abbrev_number, bytes_read, abbrev_name;
18036   unsigned int abbrev_form;
18037   struct attr_abbrev *cur_attrs;
18038   unsigned int allocated_attrs;
18039
18040   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18041
18042   dwarf2_read_section (objfile, section);
18043   abbrev_ptr = section->buffer + to_underlying (sect_off);
18044   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18045   abbrev_ptr += bytes_read;
18046
18047   allocated_attrs = ATTR_ALLOC_CHUNK;
18048   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18049
18050   /* Loop until we reach an abbrev number of 0.  */
18051   while (abbrev_number)
18052     {
18053       cur_abbrev = abbrev_table->alloc_abbrev ();
18054
18055       /* read in abbrev header */
18056       cur_abbrev->number = abbrev_number;
18057       cur_abbrev->tag
18058         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18059       abbrev_ptr += bytes_read;
18060       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18061       abbrev_ptr += 1;
18062
18063       /* now read in declarations */
18064       for (;;)
18065         {
18066           LONGEST implicit_const;
18067
18068           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18069           abbrev_ptr += bytes_read;
18070           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18071           abbrev_ptr += bytes_read;
18072           if (abbrev_form == DW_FORM_implicit_const)
18073             {
18074               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18075                                                    &bytes_read);
18076               abbrev_ptr += bytes_read;
18077             }
18078           else
18079             {
18080               /* Initialize it due to a false compiler warning.  */
18081               implicit_const = -1;
18082             }
18083
18084           if (abbrev_name == 0)
18085             break;
18086
18087           if (cur_abbrev->num_attrs == allocated_attrs)
18088             {
18089               allocated_attrs += ATTR_ALLOC_CHUNK;
18090               cur_attrs
18091                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18092             }
18093
18094           cur_attrs[cur_abbrev->num_attrs].name
18095             = (enum dwarf_attribute) abbrev_name;
18096           cur_attrs[cur_abbrev->num_attrs].form
18097             = (enum dwarf_form) abbrev_form;
18098           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18099           ++cur_abbrev->num_attrs;
18100         }
18101
18102       cur_abbrev->attrs =
18103         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18104                    cur_abbrev->num_attrs);
18105       memcpy (cur_abbrev->attrs, cur_attrs,
18106               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18107
18108       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18109
18110       /* Get next abbreviation.
18111          Under Irix6 the abbreviations for a compilation unit are not
18112          always properly terminated with an abbrev number of 0.
18113          Exit loop if we encounter an abbreviation which we have
18114          already read (which means we are about to read the abbreviations
18115          for the next compile unit) or if the end of the abbreviation
18116          table is reached.  */
18117       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18118         break;
18119       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18120       abbrev_ptr += bytes_read;
18121       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18122         break;
18123     }
18124
18125   xfree (cur_attrs);
18126   return abbrev_table;
18127 }
18128
18129 /* Returns nonzero if TAG represents a type that we might generate a partial
18130    symbol for.  */
18131
18132 static int
18133 is_type_tag_for_partial (int tag)
18134 {
18135   switch (tag)
18136     {
18137 #if 0
18138     /* Some types that would be reasonable to generate partial symbols for,
18139        that we don't at present.  */
18140     case DW_TAG_array_type:
18141     case DW_TAG_file_type:
18142     case DW_TAG_ptr_to_member_type:
18143     case DW_TAG_set_type:
18144     case DW_TAG_string_type:
18145     case DW_TAG_subroutine_type:
18146 #endif
18147     case DW_TAG_base_type:
18148     case DW_TAG_class_type:
18149     case DW_TAG_interface_type:
18150     case DW_TAG_enumeration_type:
18151     case DW_TAG_structure_type:
18152     case DW_TAG_subrange_type:
18153     case DW_TAG_typedef:
18154     case DW_TAG_union_type:
18155       return 1;
18156     default:
18157       return 0;
18158     }
18159 }
18160
18161 /* Load all DIEs that are interesting for partial symbols into memory.  */
18162
18163 static struct partial_die_info *
18164 load_partial_dies (const struct die_reader_specs *reader,
18165                    const gdb_byte *info_ptr, int building_psymtab)
18166 {
18167   struct dwarf2_cu *cu = reader->cu;
18168   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18169   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18170   unsigned int bytes_read;
18171   unsigned int load_all = 0;
18172   int nesting_level = 1;
18173
18174   parent_die = NULL;
18175   last_die = NULL;
18176
18177   gdb_assert (cu->per_cu != NULL);
18178   if (cu->per_cu->load_all_dies)
18179     load_all = 1;
18180
18181   cu->partial_dies
18182     = htab_create_alloc_ex (cu->header.length / 12,
18183                             partial_die_hash,
18184                             partial_die_eq,
18185                             NULL,
18186                             &cu->comp_unit_obstack,
18187                             hashtab_obstack_allocate,
18188                             dummy_obstack_deallocate);
18189
18190   while (1)
18191     {
18192       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18193
18194       /* A NULL abbrev means the end of a series of children.  */
18195       if (abbrev == NULL)
18196         {
18197           if (--nesting_level == 0)
18198             return first_die;
18199
18200           info_ptr += bytes_read;
18201           last_die = parent_die;
18202           parent_die = parent_die->die_parent;
18203           continue;
18204         }
18205
18206       /* Check for template arguments.  We never save these; if
18207          they're seen, we just mark the parent, and go on our way.  */
18208       if (parent_die != NULL
18209           && cu->language == language_cplus
18210           && (abbrev->tag == DW_TAG_template_type_param
18211               || abbrev->tag == DW_TAG_template_value_param))
18212         {
18213           parent_die->has_template_arguments = 1;
18214
18215           if (!load_all)
18216             {
18217               /* We don't need a partial DIE for the template argument.  */
18218               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18219               continue;
18220             }
18221         }
18222
18223       /* We only recurse into c++ subprograms looking for template arguments.
18224          Skip their other children.  */
18225       if (!load_all
18226           && cu->language == language_cplus
18227           && parent_die != NULL
18228           && parent_die->tag == DW_TAG_subprogram)
18229         {
18230           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18231           continue;
18232         }
18233
18234       /* Check whether this DIE is interesting enough to save.  Normally
18235          we would not be interested in members here, but there may be
18236          later variables referencing them via DW_AT_specification (for
18237          static members).  */
18238       if (!load_all
18239           && !is_type_tag_for_partial (abbrev->tag)
18240           && abbrev->tag != DW_TAG_constant
18241           && abbrev->tag != DW_TAG_enumerator
18242           && abbrev->tag != DW_TAG_subprogram
18243           && abbrev->tag != DW_TAG_inlined_subroutine
18244           && abbrev->tag != DW_TAG_lexical_block
18245           && abbrev->tag != DW_TAG_variable
18246           && abbrev->tag != DW_TAG_namespace
18247           && abbrev->tag != DW_TAG_module
18248           && abbrev->tag != DW_TAG_member
18249           && abbrev->tag != DW_TAG_imported_unit
18250           && abbrev->tag != DW_TAG_imported_declaration)
18251         {
18252           /* Otherwise we skip to the next sibling, if any.  */
18253           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18254           continue;
18255         }
18256
18257       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18258                                    abbrev);
18259
18260       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18261
18262       /* This two-pass algorithm for processing partial symbols has a
18263          high cost in cache pressure.  Thus, handle some simple cases
18264          here which cover the majority of C partial symbols.  DIEs
18265          which neither have specification tags in them, nor could have
18266          specification tags elsewhere pointing at them, can simply be
18267          processed and discarded.
18268
18269          This segment is also optional; scan_partial_symbols and
18270          add_partial_symbol will handle these DIEs if we chain
18271          them in normally.  When compilers which do not emit large
18272          quantities of duplicate debug information are more common,
18273          this code can probably be removed.  */
18274
18275       /* Any complete simple types at the top level (pretty much all
18276          of them, for a language without namespaces), can be processed
18277          directly.  */
18278       if (parent_die == NULL
18279           && pdi.has_specification == 0
18280           && pdi.is_declaration == 0
18281           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18282               || pdi.tag == DW_TAG_base_type
18283               || pdi.tag == DW_TAG_subrange_type))
18284         {
18285           if (building_psymtab && pdi.name != NULL)
18286             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18287                                  VAR_DOMAIN, LOC_TYPEDEF, -1,
18288                                  &objfile->static_psymbols,
18289                                  0, cu->language, objfile);
18290           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18291           continue;
18292         }
18293
18294       /* The exception for DW_TAG_typedef with has_children above is
18295          a workaround of GCC PR debug/47510.  In the case of this complaint
18296          type_name_or_error will error on such types later.
18297
18298          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18299          it could not find the child DIEs referenced later, this is checked
18300          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18301
18302       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18303         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18304                      "- DIE at %s [in module %s]"),
18305                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18306
18307       /* If we're at the second level, and we're an enumerator, and
18308          our parent has no specification (meaning possibly lives in a
18309          namespace elsewhere), then we can add the partial symbol now
18310          instead of queueing it.  */
18311       if (pdi.tag == DW_TAG_enumerator
18312           && parent_die != NULL
18313           && parent_die->die_parent == NULL
18314           && parent_die->tag == DW_TAG_enumeration_type
18315           && parent_die->has_specification == 0)
18316         {
18317           if (pdi.name == NULL)
18318             complaint (_("malformed enumerator DIE ignored"));
18319           else if (building_psymtab)
18320             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18321                                  VAR_DOMAIN, LOC_CONST, -1,
18322                                  cu->language == language_cplus
18323                                  ? &objfile->global_psymbols
18324                                  : &objfile->static_psymbols,
18325                                  0, cu->language, objfile);
18326
18327           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18328           continue;
18329         }
18330
18331       struct partial_die_info *part_die
18332         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18333
18334       /* We'll save this DIE so link it in.  */
18335       part_die->die_parent = parent_die;
18336       part_die->die_sibling = NULL;
18337       part_die->die_child = NULL;
18338
18339       if (last_die && last_die == parent_die)
18340         last_die->die_child = part_die;
18341       else if (last_die)
18342         last_die->die_sibling = part_die;
18343
18344       last_die = part_die;
18345
18346       if (first_die == NULL)
18347         first_die = part_die;
18348
18349       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18350          find interesting need to be in the hash table, because we
18351          also have the parent/sibling/child chains; only those that we
18352          might refer to by offset later during partial symbol reading.
18353
18354          For now this means things that might have be the target of a
18355          DW_AT_specification, DW_AT_abstract_origin, or
18356          DW_AT_extension.  DW_AT_extension will refer only to
18357          namespaces; DW_AT_abstract_origin refers to functions (and
18358          many things under the function DIE, but we do not recurse
18359          into function DIEs during partial symbol reading) and
18360          possibly variables as well; DW_AT_specification refers to
18361          declarations.  Declarations ought to have the DW_AT_declaration
18362          flag.  It happens that GCC forgets to put it in sometimes, but
18363          only for functions, not for types.
18364
18365          Adding more things than necessary to the hash table is harmless
18366          except for the performance cost.  Adding too few will result in
18367          wasted time in find_partial_die, when we reread the compilation
18368          unit with load_all_dies set.  */
18369
18370       if (load_all
18371           || abbrev->tag == DW_TAG_constant
18372           || abbrev->tag == DW_TAG_subprogram
18373           || abbrev->tag == DW_TAG_variable
18374           || abbrev->tag == DW_TAG_namespace
18375           || part_die->is_declaration)
18376         {
18377           void **slot;
18378
18379           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18380                                            to_underlying (part_die->sect_off),
18381                                            INSERT);
18382           *slot = part_die;
18383         }
18384
18385       /* For some DIEs we want to follow their children (if any).  For C
18386          we have no reason to follow the children of structures; for other
18387          languages we have to, so that we can get at method physnames
18388          to infer fully qualified class names, for DW_AT_specification,
18389          and for C++ template arguments.  For C++, we also look one level
18390          inside functions to find template arguments (if the name of the
18391          function does not already contain the template arguments).
18392
18393          For Ada, we need to scan the children of subprograms and lexical
18394          blocks as well because Ada allows the definition of nested
18395          entities that could be interesting for the debugger, such as
18396          nested subprograms for instance.  */
18397       if (last_die->has_children
18398           && (load_all
18399               || last_die->tag == DW_TAG_namespace
18400               || last_die->tag == DW_TAG_module
18401               || last_die->tag == DW_TAG_enumeration_type
18402               || (cu->language == language_cplus
18403                   && last_die->tag == DW_TAG_subprogram
18404                   && (last_die->name == NULL
18405                       || strchr (last_die->name, '<') == NULL))
18406               || (cu->language != language_c
18407                   && (last_die->tag == DW_TAG_class_type
18408                       || last_die->tag == DW_TAG_interface_type
18409                       || last_die->tag == DW_TAG_structure_type
18410                       || last_die->tag == DW_TAG_union_type))
18411               || (cu->language == language_ada
18412                   && (last_die->tag == DW_TAG_subprogram
18413                       || last_die->tag == DW_TAG_lexical_block))))
18414         {
18415           nesting_level++;
18416           parent_die = last_die;
18417           continue;
18418         }
18419
18420       /* Otherwise we skip to the next sibling, if any.  */
18421       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18422
18423       /* Back to the top, do it again.  */
18424     }
18425 }
18426
18427 partial_die_info::partial_die_info (sect_offset sect_off_,
18428                                     struct abbrev_info *abbrev)
18429   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18430 {
18431 }
18432
18433 /* Read a minimal amount of information into the minimal die structure.
18434    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18435
18436 const gdb_byte *
18437 partial_die_info::read (const struct die_reader_specs *reader,
18438                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18439 {
18440   struct dwarf2_cu *cu = reader->cu;
18441   struct dwarf2_per_objfile *dwarf2_per_objfile
18442     = cu->per_cu->dwarf2_per_objfile;
18443   unsigned int i;
18444   int has_low_pc_attr = 0;
18445   int has_high_pc_attr = 0;
18446   int high_pc_relative = 0;
18447
18448   for (i = 0; i < abbrev.num_attrs; ++i)
18449     {
18450       struct attribute attr;
18451
18452       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18453
18454       /* Store the data if it is of an attribute we want to keep in a
18455          partial symbol table.  */
18456       switch (attr.name)
18457         {
18458         case DW_AT_name:
18459           switch (tag)
18460             {
18461             case DW_TAG_compile_unit:
18462             case DW_TAG_partial_unit:
18463             case DW_TAG_type_unit:
18464               /* Compilation units have a DW_AT_name that is a filename, not
18465                  a source language identifier.  */
18466             case DW_TAG_enumeration_type:
18467             case DW_TAG_enumerator:
18468               /* These tags always have simple identifiers already; no need
18469                  to canonicalize them.  */
18470               name = DW_STRING (&attr);
18471               break;
18472             default:
18473               {
18474                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18475
18476                 name
18477                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18478                                               &objfile->per_bfd->storage_obstack);
18479               }
18480               break;
18481             }
18482           break;
18483         case DW_AT_linkage_name:
18484         case DW_AT_MIPS_linkage_name:
18485           /* Note that both forms of linkage name might appear.  We
18486              assume they will be the same, and we only store the last
18487              one we see.  */
18488           if (cu->language == language_ada)
18489             name = DW_STRING (&attr);
18490           linkage_name = DW_STRING (&attr);
18491           break;
18492         case DW_AT_low_pc:
18493           has_low_pc_attr = 1;
18494           lowpc = attr_value_as_address (&attr);
18495           break;
18496         case DW_AT_high_pc:
18497           has_high_pc_attr = 1;
18498           highpc = attr_value_as_address (&attr);
18499           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18500                 high_pc_relative = 1;
18501           break;
18502         case DW_AT_location:
18503           /* Support the .debug_loc offsets.  */
18504           if (attr_form_is_block (&attr))
18505             {
18506                d.locdesc = DW_BLOCK (&attr);
18507             }
18508           else if (attr_form_is_section_offset (&attr))
18509             {
18510               dwarf2_complex_location_expr_complaint ();
18511             }
18512           else
18513             {
18514               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18515                                                      "partial symbol information");
18516             }
18517           break;
18518         case DW_AT_external:
18519           is_external = DW_UNSND (&attr);
18520           break;
18521         case DW_AT_declaration:
18522           is_declaration = DW_UNSND (&attr);
18523           break;
18524         case DW_AT_type:
18525           has_type = 1;
18526           break;
18527         case DW_AT_abstract_origin:
18528         case DW_AT_specification:
18529         case DW_AT_extension:
18530           has_specification = 1;
18531           spec_offset = dwarf2_get_ref_die_offset (&attr);
18532           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18533                                    || cu->per_cu->is_dwz);
18534           break;
18535         case DW_AT_sibling:
18536           /* Ignore absolute siblings, they might point outside of
18537              the current compile unit.  */
18538           if (attr.form == DW_FORM_ref_addr)
18539             complaint (_("ignoring absolute DW_AT_sibling"));
18540           else
18541             {
18542               const gdb_byte *buffer = reader->buffer;
18543               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18544               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18545
18546               if (sibling_ptr < info_ptr)
18547                 complaint (_("DW_AT_sibling points backwards"));
18548               else if (sibling_ptr > reader->buffer_end)
18549                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18550               else
18551                 sibling = sibling_ptr;
18552             }
18553           break;
18554         case DW_AT_byte_size:
18555           has_byte_size = 1;
18556           break;
18557         case DW_AT_const_value:
18558           has_const_value = 1;
18559           break;
18560         case DW_AT_calling_convention:
18561           /* DWARF doesn't provide a way to identify a program's source-level
18562              entry point.  DW_AT_calling_convention attributes are only meant
18563              to describe functions' calling conventions.
18564
18565              However, because it's a necessary piece of information in
18566              Fortran, and before DWARF 4 DW_CC_program was the only
18567              piece of debugging information whose definition refers to
18568              a 'main program' at all, several compilers marked Fortran
18569              main programs with DW_CC_program --- even when those
18570              functions use the standard calling conventions.
18571
18572              Although DWARF now specifies a way to provide this
18573              information, we support this practice for backward
18574              compatibility.  */
18575           if (DW_UNSND (&attr) == DW_CC_program
18576               && cu->language == language_fortran)
18577             main_subprogram = 1;
18578           break;
18579         case DW_AT_inline:
18580           if (DW_UNSND (&attr) == DW_INL_inlined
18581               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18582             may_be_inlined = 1;
18583           break;
18584
18585         case DW_AT_import:
18586           if (tag == DW_TAG_imported_unit)
18587             {
18588               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18589               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18590                                   || cu->per_cu->is_dwz);
18591             }
18592           break;
18593
18594         case DW_AT_main_subprogram:
18595           main_subprogram = DW_UNSND (&attr);
18596           break;
18597
18598         default:
18599           break;
18600         }
18601     }
18602
18603   if (high_pc_relative)
18604     highpc += lowpc;
18605
18606   if (has_low_pc_attr && has_high_pc_attr)
18607     {
18608       /* When using the GNU linker, .gnu.linkonce. sections are used to
18609          eliminate duplicate copies of functions and vtables and such.
18610          The linker will arbitrarily choose one and discard the others.
18611          The AT_*_pc values for such functions refer to local labels in
18612          these sections.  If the section from that file was discarded, the
18613          labels are not in the output, so the relocs get a value of 0.
18614          If this is a discarded function, mark the pc bounds as invalid,
18615          so that GDB will ignore it.  */
18616       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18617         {
18618           struct objfile *objfile = dwarf2_per_objfile->objfile;
18619           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18620
18621           complaint (_("DW_AT_low_pc %s is zero "
18622                        "for DIE at %s [in module %s]"),
18623                      paddress (gdbarch, lowpc),
18624                      sect_offset_str (sect_off),
18625                      objfile_name (objfile));
18626         }
18627       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18628       else if (lowpc >= highpc)
18629         {
18630           struct objfile *objfile = dwarf2_per_objfile->objfile;
18631           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18632
18633           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18634                        "for DIE at %s [in module %s]"),
18635                      paddress (gdbarch, lowpc),
18636                      paddress (gdbarch, highpc),
18637                      sect_offset_str (sect_off),
18638                      objfile_name (objfile));
18639         }
18640       else
18641         has_pc_info = 1;
18642     }
18643
18644   return info_ptr;
18645 }
18646
18647 /* Find a cached partial DIE at OFFSET in CU.  */
18648
18649 struct partial_die_info *
18650 dwarf2_cu::find_partial_die (sect_offset sect_off)
18651 {
18652   struct partial_die_info *lookup_die = NULL;
18653   struct partial_die_info part_die (sect_off);
18654
18655   lookup_die = ((struct partial_die_info *)
18656                 htab_find_with_hash (partial_dies, &part_die,
18657                                      to_underlying (sect_off)));
18658
18659   return lookup_die;
18660 }
18661
18662 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18663    except in the case of .debug_types DIEs which do not reference
18664    outside their CU (they do however referencing other types via
18665    DW_FORM_ref_sig8).  */
18666
18667 static struct partial_die_info *
18668 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18669 {
18670   struct dwarf2_per_objfile *dwarf2_per_objfile
18671     = cu->per_cu->dwarf2_per_objfile;
18672   struct objfile *objfile = dwarf2_per_objfile->objfile;
18673   struct dwarf2_per_cu_data *per_cu = NULL;
18674   struct partial_die_info *pd = NULL;
18675
18676   if (offset_in_dwz == cu->per_cu->is_dwz
18677       && offset_in_cu_p (&cu->header, sect_off))
18678     {
18679       pd = cu->find_partial_die (sect_off);
18680       if (pd != NULL)
18681         return pd;
18682       /* We missed recording what we needed.
18683          Load all dies and try again.  */
18684       per_cu = cu->per_cu;
18685     }
18686   else
18687     {
18688       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18689       if (cu->per_cu->is_debug_types)
18690         {
18691           error (_("Dwarf Error: Type Unit at offset %s contains"
18692                    " external reference to offset %s [in module %s].\n"),
18693                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18694                  bfd_get_filename (objfile->obfd));
18695         }
18696       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18697                                                  dwarf2_per_objfile);
18698
18699       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18700         load_partial_comp_unit (per_cu);
18701
18702       per_cu->cu->last_used = 0;
18703       pd = per_cu->cu->find_partial_die (sect_off);
18704     }
18705
18706   /* If we didn't find it, and not all dies have been loaded,
18707      load them all and try again.  */
18708
18709   if (pd == NULL && per_cu->load_all_dies == 0)
18710     {
18711       per_cu->load_all_dies = 1;
18712
18713       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18714          THIS_CU->cu may already be in use.  So we can't just free it and
18715          replace its DIEs with the ones we read in.  Instead, we leave those
18716          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18717          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18718          set.  */
18719       load_partial_comp_unit (per_cu);
18720
18721       pd = per_cu->cu->find_partial_die (sect_off);
18722     }
18723
18724   if (pd == NULL)
18725     internal_error (__FILE__, __LINE__,
18726                     _("could not find partial DIE %s "
18727                       "in cache [from module %s]\n"),
18728                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18729   return pd;
18730 }
18731
18732 /* See if we can figure out if the class lives in a namespace.  We do
18733    this by looking for a member function; its demangled name will
18734    contain namespace info, if there is any.  */
18735
18736 static void
18737 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18738                                   struct dwarf2_cu *cu)
18739 {
18740   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18741      what template types look like, because the demangler
18742      frequently doesn't give the same name as the debug info.  We
18743      could fix this by only using the demangled name to get the
18744      prefix (but see comment in read_structure_type).  */
18745
18746   struct partial_die_info *real_pdi;
18747   struct partial_die_info *child_pdi;
18748
18749   /* If this DIE (this DIE's specification, if any) has a parent, then
18750      we should not do this.  We'll prepend the parent's fully qualified
18751      name when we create the partial symbol.  */
18752
18753   real_pdi = struct_pdi;
18754   while (real_pdi->has_specification)
18755     real_pdi = find_partial_die (real_pdi->spec_offset,
18756                                  real_pdi->spec_is_dwz, cu);
18757
18758   if (real_pdi->die_parent != NULL)
18759     return;
18760
18761   for (child_pdi = struct_pdi->die_child;
18762        child_pdi != NULL;
18763        child_pdi = child_pdi->die_sibling)
18764     {
18765       if (child_pdi->tag == DW_TAG_subprogram
18766           && child_pdi->linkage_name != NULL)
18767         {
18768           char *actual_class_name
18769             = language_class_name_from_physname (cu->language_defn,
18770                                                  child_pdi->linkage_name);
18771           if (actual_class_name != NULL)
18772             {
18773               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18774               struct_pdi->name
18775                 = ((const char *)
18776                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18777                                   actual_class_name,
18778                                   strlen (actual_class_name)));
18779               xfree (actual_class_name);
18780             }
18781           break;
18782         }
18783     }
18784 }
18785
18786 void
18787 partial_die_info::fixup (struct dwarf2_cu *cu)
18788 {
18789   /* Once we've fixed up a die, there's no point in doing so again.
18790      This also avoids a memory leak if we were to call
18791      guess_partial_die_structure_name multiple times.  */
18792   if (fixup_called)
18793     return;
18794
18795   /* If we found a reference attribute and the DIE has no name, try
18796      to find a name in the referred to DIE.  */
18797
18798   if (name == NULL && has_specification)
18799     {
18800       struct partial_die_info *spec_die;
18801
18802       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18803
18804       spec_die->fixup (cu);
18805
18806       if (spec_die->name)
18807         {
18808           name = spec_die->name;
18809
18810           /* Copy DW_AT_external attribute if it is set.  */
18811           if (spec_die->is_external)
18812             is_external = spec_die->is_external;
18813         }
18814     }
18815
18816   /* Set default names for some unnamed DIEs.  */
18817
18818   if (name == NULL && tag == DW_TAG_namespace)
18819     name = CP_ANONYMOUS_NAMESPACE_STR;
18820
18821   /* If there is no parent die to provide a namespace, and there are
18822      children, see if we can determine the namespace from their linkage
18823      name.  */
18824   if (cu->language == language_cplus
18825       && !VEC_empty (dwarf2_section_info_def,
18826                      cu->per_cu->dwarf2_per_objfile->types)
18827       && die_parent == NULL
18828       && has_children
18829       && (tag == DW_TAG_class_type
18830           || tag == DW_TAG_structure_type
18831           || tag == DW_TAG_union_type))
18832     guess_partial_die_structure_name (this, cu);
18833
18834   /* GCC might emit a nameless struct or union that has a linkage
18835      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18836   if (name == NULL
18837       && (tag == DW_TAG_class_type
18838           || tag == DW_TAG_interface_type
18839           || tag == DW_TAG_structure_type
18840           || tag == DW_TAG_union_type)
18841       && linkage_name != NULL)
18842     {
18843       char *demangled;
18844
18845       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18846       if (demangled)
18847         {
18848           const char *base;
18849
18850           /* Strip any leading namespaces/classes, keep only the base name.
18851              DW_AT_name for named DIEs does not contain the prefixes.  */
18852           base = strrchr (demangled, ':');
18853           if (base && base > demangled && base[-1] == ':')
18854             base++;
18855           else
18856             base = demangled;
18857
18858           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18859           name
18860             = ((const char *)
18861                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18862                               base, strlen (base)));
18863           xfree (demangled);
18864         }
18865     }
18866
18867   fixup_called = 1;
18868 }
18869
18870 /* Read an attribute value described by an attribute form.  */
18871
18872 static const gdb_byte *
18873 read_attribute_value (const struct die_reader_specs *reader,
18874                       struct attribute *attr, unsigned form,
18875                       LONGEST implicit_const, const gdb_byte *info_ptr)
18876 {
18877   struct dwarf2_cu *cu = reader->cu;
18878   struct dwarf2_per_objfile *dwarf2_per_objfile
18879     = cu->per_cu->dwarf2_per_objfile;
18880   struct objfile *objfile = dwarf2_per_objfile->objfile;
18881   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18882   bfd *abfd = reader->abfd;
18883   struct comp_unit_head *cu_header = &cu->header;
18884   unsigned int bytes_read;
18885   struct dwarf_block *blk;
18886
18887   attr->form = (enum dwarf_form) form;
18888   switch (form)
18889     {
18890     case DW_FORM_ref_addr:
18891       if (cu->header.version == 2)
18892         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18893       else
18894         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18895                                        &cu->header, &bytes_read);
18896       info_ptr += bytes_read;
18897       break;
18898     case DW_FORM_GNU_ref_alt:
18899       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18900       info_ptr += bytes_read;
18901       break;
18902     case DW_FORM_addr:
18903       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18904       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18905       info_ptr += bytes_read;
18906       break;
18907     case DW_FORM_block2:
18908       blk = dwarf_alloc_block (cu);
18909       blk->size = read_2_bytes (abfd, info_ptr);
18910       info_ptr += 2;
18911       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18912       info_ptr += blk->size;
18913       DW_BLOCK (attr) = blk;
18914       break;
18915     case DW_FORM_block4:
18916       blk = dwarf_alloc_block (cu);
18917       blk->size = read_4_bytes (abfd, info_ptr);
18918       info_ptr += 4;
18919       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18920       info_ptr += blk->size;
18921       DW_BLOCK (attr) = blk;
18922       break;
18923     case DW_FORM_data2:
18924       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18925       info_ptr += 2;
18926       break;
18927     case DW_FORM_data4:
18928       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18929       info_ptr += 4;
18930       break;
18931     case DW_FORM_data8:
18932       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18933       info_ptr += 8;
18934       break;
18935     case DW_FORM_data16:
18936       blk = dwarf_alloc_block (cu);
18937       blk->size = 16;
18938       blk->data = read_n_bytes (abfd, info_ptr, 16);
18939       info_ptr += 16;
18940       DW_BLOCK (attr) = blk;
18941       break;
18942     case DW_FORM_sec_offset:
18943       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18944       info_ptr += bytes_read;
18945       break;
18946     case DW_FORM_string:
18947       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18948       DW_STRING_IS_CANONICAL (attr) = 0;
18949       info_ptr += bytes_read;
18950       break;
18951     case DW_FORM_strp:
18952       if (!cu->per_cu->is_dwz)
18953         {
18954           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18955                                                    abfd, info_ptr, cu_header,
18956                                                    &bytes_read);
18957           DW_STRING_IS_CANONICAL (attr) = 0;
18958           info_ptr += bytes_read;
18959           break;
18960         }
18961       /* FALLTHROUGH */
18962     case DW_FORM_line_strp:
18963       if (!cu->per_cu->is_dwz)
18964         {
18965           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18966                                                         abfd, info_ptr,
18967                                                         cu_header, &bytes_read);
18968           DW_STRING_IS_CANONICAL (attr) = 0;
18969           info_ptr += bytes_read;
18970           break;
18971         }
18972       /* FALLTHROUGH */
18973     case DW_FORM_GNU_strp_alt:
18974       {
18975         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
18976         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18977                                           &bytes_read);
18978
18979         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
18980                                                           dwz, str_offset);
18981         DW_STRING_IS_CANONICAL (attr) = 0;
18982         info_ptr += bytes_read;
18983       }
18984       break;
18985     case DW_FORM_exprloc:
18986     case DW_FORM_block:
18987       blk = dwarf_alloc_block (cu);
18988       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18989       info_ptr += bytes_read;
18990       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18991       info_ptr += blk->size;
18992       DW_BLOCK (attr) = blk;
18993       break;
18994     case DW_FORM_block1:
18995       blk = dwarf_alloc_block (cu);
18996       blk->size = read_1_byte (abfd, info_ptr);
18997       info_ptr += 1;
18998       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18999       info_ptr += blk->size;
19000       DW_BLOCK (attr) = blk;
19001       break;
19002     case DW_FORM_data1:
19003       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19004       info_ptr += 1;
19005       break;
19006     case DW_FORM_flag:
19007       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19008       info_ptr += 1;
19009       break;
19010     case DW_FORM_flag_present:
19011       DW_UNSND (attr) = 1;
19012       break;
19013     case DW_FORM_sdata:
19014       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19015       info_ptr += bytes_read;
19016       break;
19017     case DW_FORM_udata:
19018       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19019       info_ptr += bytes_read;
19020       break;
19021     case DW_FORM_ref1:
19022       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19023                          + read_1_byte (abfd, info_ptr));
19024       info_ptr += 1;
19025       break;
19026     case DW_FORM_ref2:
19027       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19028                          + read_2_bytes (abfd, info_ptr));
19029       info_ptr += 2;
19030       break;
19031     case DW_FORM_ref4:
19032       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19033                          + read_4_bytes (abfd, info_ptr));
19034       info_ptr += 4;
19035       break;
19036     case DW_FORM_ref8:
19037       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19038                          + read_8_bytes (abfd, info_ptr));
19039       info_ptr += 8;
19040       break;
19041     case DW_FORM_ref_sig8:
19042       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19043       info_ptr += 8;
19044       break;
19045     case DW_FORM_ref_udata:
19046       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19047                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19048       info_ptr += bytes_read;
19049       break;
19050     case DW_FORM_indirect:
19051       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19052       info_ptr += bytes_read;
19053       if (form == DW_FORM_implicit_const)
19054         {
19055           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19056           info_ptr += bytes_read;
19057         }
19058       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19059                                        info_ptr);
19060       break;
19061     case DW_FORM_implicit_const:
19062       DW_SND (attr) = implicit_const;
19063       break;
19064     case DW_FORM_GNU_addr_index:
19065       if (reader->dwo_file == NULL)
19066         {
19067           /* For now flag a hard error.
19068              Later we can turn this into a complaint.  */
19069           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19070                  dwarf_form_name (form),
19071                  bfd_get_filename (abfd));
19072         }
19073       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19074       info_ptr += bytes_read;
19075       break;
19076     case DW_FORM_GNU_str_index:
19077       if (reader->dwo_file == NULL)
19078         {
19079           /* For now flag a hard error.
19080              Later we can turn this into a complaint if warranted.  */
19081           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19082                  dwarf_form_name (form),
19083                  bfd_get_filename (abfd));
19084         }
19085       {
19086         ULONGEST str_index =
19087           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19088
19089         DW_STRING (attr) = read_str_index (reader, str_index);
19090         DW_STRING_IS_CANONICAL (attr) = 0;
19091         info_ptr += bytes_read;
19092       }
19093       break;
19094     default:
19095       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19096              dwarf_form_name (form),
19097              bfd_get_filename (abfd));
19098     }
19099
19100   /* Super hack.  */
19101   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19102     attr->form = DW_FORM_GNU_ref_alt;
19103
19104   /* We have seen instances where the compiler tried to emit a byte
19105      size attribute of -1 which ended up being encoded as an unsigned
19106      0xffffffff.  Although 0xffffffff is technically a valid size value,
19107      an object of this size seems pretty unlikely so we can relatively
19108      safely treat these cases as if the size attribute was invalid and
19109      treat them as zero by default.  */
19110   if (attr->name == DW_AT_byte_size
19111       && form == DW_FORM_data4
19112       && DW_UNSND (attr) >= 0xffffffff)
19113     {
19114       complaint
19115         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19116          hex_string (DW_UNSND (attr)));
19117       DW_UNSND (attr) = 0;
19118     }
19119
19120   return info_ptr;
19121 }
19122
19123 /* Read an attribute described by an abbreviated attribute.  */
19124
19125 static const gdb_byte *
19126 read_attribute (const struct die_reader_specs *reader,
19127                 struct attribute *attr, struct attr_abbrev *abbrev,
19128                 const gdb_byte *info_ptr)
19129 {
19130   attr->name = abbrev->name;
19131   return read_attribute_value (reader, attr, abbrev->form,
19132                                abbrev->implicit_const, info_ptr);
19133 }
19134
19135 /* Read dwarf information from a buffer.  */
19136
19137 static unsigned int
19138 read_1_byte (bfd *abfd, const gdb_byte *buf)
19139 {
19140   return bfd_get_8 (abfd, buf);
19141 }
19142
19143 static int
19144 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19145 {
19146   return bfd_get_signed_8 (abfd, buf);
19147 }
19148
19149 static unsigned int
19150 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19151 {
19152   return bfd_get_16 (abfd, buf);
19153 }
19154
19155 static int
19156 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19157 {
19158   return bfd_get_signed_16 (abfd, buf);
19159 }
19160
19161 static unsigned int
19162 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19163 {
19164   return bfd_get_32 (abfd, buf);
19165 }
19166
19167 static int
19168 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19169 {
19170   return bfd_get_signed_32 (abfd, buf);
19171 }
19172
19173 static ULONGEST
19174 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19175 {
19176   return bfd_get_64 (abfd, buf);
19177 }
19178
19179 static CORE_ADDR
19180 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19181               unsigned int *bytes_read)
19182 {
19183   struct comp_unit_head *cu_header = &cu->header;
19184   CORE_ADDR retval = 0;
19185
19186   if (cu_header->signed_addr_p)
19187     {
19188       switch (cu_header->addr_size)
19189         {
19190         case 2:
19191           retval = bfd_get_signed_16 (abfd, buf);
19192           break;
19193         case 4:
19194           retval = bfd_get_signed_32 (abfd, buf);
19195           break;
19196         case 8:
19197           retval = bfd_get_signed_64 (abfd, buf);
19198           break;
19199         default:
19200           internal_error (__FILE__, __LINE__,
19201                           _("read_address: bad switch, signed [in module %s]"),
19202                           bfd_get_filename (abfd));
19203         }
19204     }
19205   else
19206     {
19207       switch (cu_header->addr_size)
19208         {
19209         case 2:
19210           retval = bfd_get_16 (abfd, buf);
19211           break;
19212         case 4:
19213           retval = bfd_get_32 (abfd, buf);
19214           break;
19215         case 8:
19216           retval = bfd_get_64 (abfd, buf);
19217           break;
19218         default:
19219           internal_error (__FILE__, __LINE__,
19220                           _("read_address: bad switch, "
19221                             "unsigned [in module %s]"),
19222                           bfd_get_filename (abfd));
19223         }
19224     }
19225
19226   *bytes_read = cu_header->addr_size;
19227   return retval;
19228 }
19229
19230 /* Read the initial length from a section.  The (draft) DWARF 3
19231    specification allows the initial length to take up either 4 bytes
19232    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19233    bytes describe the length and all offsets will be 8 bytes in length
19234    instead of 4.
19235
19236    An older, non-standard 64-bit format is also handled by this
19237    function.  The older format in question stores the initial length
19238    as an 8-byte quantity without an escape value.  Lengths greater
19239    than 2^32 aren't very common which means that the initial 4 bytes
19240    is almost always zero.  Since a length value of zero doesn't make
19241    sense for the 32-bit format, this initial zero can be considered to
19242    be an escape value which indicates the presence of the older 64-bit
19243    format.  As written, the code can't detect (old format) lengths
19244    greater than 4GB.  If it becomes necessary to handle lengths
19245    somewhat larger than 4GB, we could allow other small values (such
19246    as the non-sensical values of 1, 2, and 3) to also be used as
19247    escape values indicating the presence of the old format.
19248
19249    The value returned via bytes_read should be used to increment the
19250    relevant pointer after calling read_initial_length().
19251
19252    [ Note:  read_initial_length() and read_offset() are based on the
19253      document entitled "DWARF Debugging Information Format", revision
19254      3, draft 8, dated November 19, 2001.  This document was obtained
19255      from:
19256
19257         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19258
19259      This document is only a draft and is subject to change.  (So beware.)
19260
19261      Details regarding the older, non-standard 64-bit format were
19262      determined empirically by examining 64-bit ELF files produced by
19263      the SGI toolchain on an IRIX 6.5 machine.
19264
19265      - Kevin, July 16, 2002
19266    ] */
19267
19268 static LONGEST
19269 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19270 {
19271   LONGEST length = bfd_get_32 (abfd, buf);
19272
19273   if (length == 0xffffffff)
19274     {
19275       length = bfd_get_64 (abfd, buf + 4);
19276       *bytes_read = 12;
19277     }
19278   else if (length == 0)
19279     {
19280       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19281       length = bfd_get_64 (abfd, buf);
19282       *bytes_read = 8;
19283     }
19284   else
19285     {
19286       *bytes_read = 4;
19287     }
19288
19289   return length;
19290 }
19291
19292 /* Cover function for read_initial_length.
19293    Returns the length of the object at BUF, and stores the size of the
19294    initial length in *BYTES_READ and stores the size that offsets will be in
19295    *OFFSET_SIZE.
19296    If the initial length size is not equivalent to that specified in
19297    CU_HEADER then issue a complaint.
19298    This is useful when reading non-comp-unit headers.  */
19299
19300 static LONGEST
19301 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19302                                         const struct comp_unit_head *cu_header,
19303                                         unsigned int *bytes_read,
19304                                         unsigned int *offset_size)
19305 {
19306   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19307
19308   gdb_assert (cu_header->initial_length_size == 4
19309               || cu_header->initial_length_size == 8
19310               || cu_header->initial_length_size == 12);
19311
19312   if (cu_header->initial_length_size != *bytes_read)
19313     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19314
19315   *offset_size = (*bytes_read == 4) ? 4 : 8;
19316   return length;
19317 }
19318
19319 /* Read an offset from the data stream.  The size of the offset is
19320    given by cu_header->offset_size.  */
19321
19322 static LONGEST
19323 read_offset (bfd *abfd, const gdb_byte *buf,
19324              const struct comp_unit_head *cu_header,
19325              unsigned int *bytes_read)
19326 {
19327   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19328
19329   *bytes_read = cu_header->offset_size;
19330   return offset;
19331 }
19332
19333 /* Read an offset from the data stream.  */
19334
19335 static LONGEST
19336 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19337 {
19338   LONGEST retval = 0;
19339
19340   switch (offset_size)
19341     {
19342     case 4:
19343       retval = bfd_get_32 (abfd, buf);
19344       break;
19345     case 8:
19346       retval = bfd_get_64 (abfd, buf);
19347       break;
19348     default:
19349       internal_error (__FILE__, __LINE__,
19350                       _("read_offset_1: bad switch [in module %s]"),
19351                       bfd_get_filename (abfd));
19352     }
19353
19354   return retval;
19355 }
19356
19357 static const gdb_byte *
19358 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19359 {
19360   /* If the size of a host char is 8 bits, we can return a pointer
19361      to the buffer, otherwise we have to copy the data to a buffer
19362      allocated on the temporary obstack.  */
19363   gdb_assert (HOST_CHAR_BIT == 8);
19364   return buf;
19365 }
19366
19367 static const char *
19368 read_direct_string (bfd *abfd, const gdb_byte *buf,
19369                     unsigned int *bytes_read_ptr)
19370 {
19371   /* If the size of a host char is 8 bits, we can return a pointer
19372      to the string, otherwise we have to copy the string to a buffer
19373      allocated on the temporary obstack.  */
19374   gdb_assert (HOST_CHAR_BIT == 8);
19375   if (*buf == '\0')
19376     {
19377       *bytes_read_ptr = 1;
19378       return NULL;
19379     }
19380   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19381   return (const char *) buf;
19382 }
19383
19384 /* Return pointer to string at section SECT offset STR_OFFSET with error
19385    reporting strings FORM_NAME and SECT_NAME.  */
19386
19387 static const char *
19388 read_indirect_string_at_offset_from (struct objfile *objfile,
19389                                      bfd *abfd, LONGEST str_offset,
19390                                      struct dwarf2_section_info *sect,
19391                                      const char *form_name,
19392                                      const char *sect_name)
19393 {
19394   dwarf2_read_section (objfile, sect);
19395   if (sect->buffer == NULL)
19396     error (_("%s used without %s section [in module %s]"),
19397            form_name, sect_name, bfd_get_filename (abfd));
19398   if (str_offset >= sect->size)
19399     error (_("%s pointing outside of %s section [in module %s]"),
19400            form_name, sect_name, bfd_get_filename (abfd));
19401   gdb_assert (HOST_CHAR_BIT == 8);
19402   if (sect->buffer[str_offset] == '\0')
19403     return NULL;
19404   return (const char *) (sect->buffer + str_offset);
19405 }
19406
19407 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19408
19409 static const char *
19410 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19411                                 bfd *abfd, LONGEST str_offset)
19412 {
19413   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19414                                               abfd, str_offset,
19415                                               &dwarf2_per_objfile->str,
19416                                               "DW_FORM_strp", ".debug_str");
19417 }
19418
19419 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19420
19421 static const char *
19422 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19423                                      bfd *abfd, LONGEST str_offset)
19424 {
19425   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19426                                               abfd, str_offset,
19427                                               &dwarf2_per_objfile->line_str,
19428                                               "DW_FORM_line_strp",
19429                                               ".debug_line_str");
19430 }
19431
19432 /* Read a string at offset STR_OFFSET in the .debug_str section from
19433    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19434    the string consists of a single NUL byte, return NULL; otherwise
19435    return a pointer to the string.  */
19436
19437 static const char *
19438 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19439                                LONGEST str_offset)
19440 {
19441   dwarf2_read_section (objfile, &dwz->str);
19442
19443   if (dwz->str.buffer == NULL)
19444     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19445              "section [in module %s]"),
19446            bfd_get_filename (dwz->dwz_bfd));
19447   if (str_offset >= dwz->str.size)
19448     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19449              ".debug_str section [in module %s]"),
19450            bfd_get_filename (dwz->dwz_bfd));
19451   gdb_assert (HOST_CHAR_BIT == 8);
19452   if (dwz->str.buffer[str_offset] == '\0')
19453     return NULL;
19454   return (const char *) (dwz->str.buffer + str_offset);
19455 }
19456
19457 /* Return pointer to string at .debug_str offset as read from BUF.
19458    BUF is assumed to be in a compilation unit described by CU_HEADER.
19459    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19460
19461 static const char *
19462 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19463                       const gdb_byte *buf,
19464                       const struct comp_unit_head *cu_header,
19465                       unsigned int *bytes_read_ptr)
19466 {
19467   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19468
19469   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19470 }
19471
19472 /* Return pointer to string at .debug_line_str offset as read from BUF.
19473    BUF is assumed to be in a compilation unit described by CU_HEADER.
19474    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19475
19476 static const char *
19477 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19478                            bfd *abfd, const gdb_byte *buf,
19479                            const struct comp_unit_head *cu_header,
19480                            unsigned int *bytes_read_ptr)
19481 {
19482   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19483
19484   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19485                                               str_offset);
19486 }
19487
19488 ULONGEST
19489 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19490                           unsigned int *bytes_read_ptr)
19491 {
19492   ULONGEST result;
19493   unsigned int num_read;
19494   int shift;
19495   unsigned char byte;
19496
19497   result = 0;
19498   shift = 0;
19499   num_read = 0;
19500   while (1)
19501     {
19502       byte = bfd_get_8 (abfd, buf);
19503       buf++;
19504       num_read++;
19505       result |= ((ULONGEST) (byte & 127) << shift);
19506       if ((byte & 128) == 0)
19507         {
19508           break;
19509         }
19510       shift += 7;
19511     }
19512   *bytes_read_ptr = num_read;
19513   return result;
19514 }
19515
19516 static LONGEST
19517 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19518                     unsigned int *bytes_read_ptr)
19519 {
19520   LONGEST result;
19521   int shift, num_read;
19522   unsigned char byte;
19523
19524   result = 0;
19525   shift = 0;
19526   num_read = 0;
19527   while (1)
19528     {
19529       byte = bfd_get_8 (abfd, buf);
19530       buf++;
19531       num_read++;
19532       result |= ((LONGEST) (byte & 127) << shift);
19533       shift += 7;
19534       if ((byte & 128) == 0)
19535         {
19536           break;
19537         }
19538     }
19539   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19540     result |= -(((LONGEST) 1) << shift);
19541   *bytes_read_ptr = num_read;
19542   return result;
19543 }
19544
19545 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19546    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19547    ADDR_SIZE is the size of addresses from the CU header.  */
19548
19549 static CORE_ADDR
19550 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19551                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19552 {
19553   struct objfile *objfile = dwarf2_per_objfile->objfile;
19554   bfd *abfd = objfile->obfd;
19555   const gdb_byte *info_ptr;
19556
19557   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19558   if (dwarf2_per_objfile->addr.buffer == NULL)
19559     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19560            objfile_name (objfile));
19561   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19562     error (_("DW_FORM_addr_index pointing outside of "
19563              ".debug_addr section [in module %s]"),
19564            objfile_name (objfile));
19565   info_ptr = (dwarf2_per_objfile->addr.buffer
19566               + addr_base + addr_index * addr_size);
19567   if (addr_size == 4)
19568     return bfd_get_32 (abfd, info_ptr);
19569   else
19570     return bfd_get_64 (abfd, info_ptr);
19571 }
19572
19573 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19574
19575 static CORE_ADDR
19576 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19577 {
19578   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19579                             cu->addr_base, cu->header.addr_size);
19580 }
19581
19582 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19583
19584 static CORE_ADDR
19585 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19586                              unsigned int *bytes_read)
19587 {
19588   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19589   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19590
19591   return read_addr_index (cu, addr_index);
19592 }
19593
19594 /* Data structure to pass results from dwarf2_read_addr_index_reader
19595    back to dwarf2_read_addr_index.  */
19596
19597 struct dwarf2_read_addr_index_data
19598 {
19599   ULONGEST addr_base;
19600   int addr_size;
19601 };
19602
19603 /* die_reader_func for dwarf2_read_addr_index.  */
19604
19605 static void
19606 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19607                                const gdb_byte *info_ptr,
19608                                struct die_info *comp_unit_die,
19609                                int has_children,
19610                                void *data)
19611 {
19612   struct dwarf2_cu *cu = reader->cu;
19613   struct dwarf2_read_addr_index_data *aidata =
19614     (struct dwarf2_read_addr_index_data *) data;
19615
19616   aidata->addr_base = cu->addr_base;
19617   aidata->addr_size = cu->header.addr_size;
19618 }
19619
19620 /* Given an index in .debug_addr, fetch the value.
19621    NOTE: This can be called during dwarf expression evaluation,
19622    long after the debug information has been read, and thus per_cu->cu
19623    may no longer exist.  */
19624
19625 CORE_ADDR
19626 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19627                         unsigned int addr_index)
19628 {
19629   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19630   struct dwarf2_cu *cu = per_cu->cu;
19631   ULONGEST addr_base;
19632   int addr_size;
19633
19634   /* We need addr_base and addr_size.
19635      If we don't have PER_CU->cu, we have to get it.
19636      Nasty, but the alternative is storing the needed info in PER_CU,
19637      which at this point doesn't seem justified: it's not clear how frequently
19638      it would get used and it would increase the size of every PER_CU.
19639      Entry points like dwarf2_per_cu_addr_size do a similar thing
19640      so we're not in uncharted territory here.
19641      Alas we need to be a bit more complicated as addr_base is contained
19642      in the DIE.
19643
19644      We don't need to read the entire CU(/TU).
19645      We just need the header and top level die.
19646
19647      IWBN to use the aging mechanism to let us lazily later discard the CU.
19648      For now we skip this optimization.  */
19649
19650   if (cu != NULL)
19651     {
19652       addr_base = cu->addr_base;
19653       addr_size = cu->header.addr_size;
19654     }
19655   else
19656     {
19657       struct dwarf2_read_addr_index_data aidata;
19658
19659       /* Note: We can't use init_cutu_and_read_dies_simple here,
19660          we need addr_base.  */
19661       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19662                                dwarf2_read_addr_index_reader, &aidata);
19663       addr_base = aidata.addr_base;
19664       addr_size = aidata.addr_size;
19665     }
19666
19667   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19668                             addr_size);
19669 }
19670
19671 /* Given a DW_FORM_GNU_str_index, fetch the string.
19672    This is only used by the Fission support.  */
19673
19674 static const char *
19675 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19676 {
19677   struct dwarf2_cu *cu = reader->cu;
19678   struct dwarf2_per_objfile *dwarf2_per_objfile
19679     = cu->per_cu->dwarf2_per_objfile;
19680   struct objfile *objfile = dwarf2_per_objfile->objfile;
19681   const char *objf_name = objfile_name (objfile);
19682   bfd *abfd = objfile->obfd;
19683   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19684   struct dwarf2_section_info *str_offsets_section =
19685     &reader->dwo_file->sections.str_offsets;
19686   const gdb_byte *info_ptr;
19687   ULONGEST str_offset;
19688   static const char form_name[] = "DW_FORM_GNU_str_index";
19689
19690   dwarf2_read_section (objfile, str_section);
19691   dwarf2_read_section (objfile, str_offsets_section);
19692   if (str_section->buffer == NULL)
19693     error (_("%s used without .debug_str.dwo section"
19694              " in CU at offset %s [in module %s]"),
19695            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19696   if (str_offsets_section->buffer == NULL)
19697     error (_("%s used without .debug_str_offsets.dwo section"
19698              " in CU at offset %s [in module %s]"),
19699            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19700   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19701     error (_("%s pointing outside of .debug_str_offsets.dwo"
19702              " section in CU at offset %s [in module %s]"),
19703            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19704   info_ptr = (str_offsets_section->buffer
19705               + str_index * cu->header.offset_size);
19706   if (cu->header.offset_size == 4)
19707     str_offset = bfd_get_32 (abfd, info_ptr);
19708   else
19709     str_offset = bfd_get_64 (abfd, info_ptr);
19710   if (str_offset >= str_section->size)
19711     error (_("Offset from %s pointing outside of"
19712              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19713            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19714   return (const char *) (str_section->buffer + str_offset);
19715 }
19716
19717 /* Return the length of an LEB128 number in BUF.  */
19718
19719 static int
19720 leb128_size (const gdb_byte *buf)
19721 {
19722   const gdb_byte *begin = buf;
19723   gdb_byte byte;
19724
19725   while (1)
19726     {
19727       byte = *buf++;
19728       if ((byte & 128) == 0)
19729         return buf - begin;
19730     }
19731 }
19732
19733 static void
19734 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19735 {
19736   switch (lang)
19737     {
19738     case DW_LANG_C89:
19739     case DW_LANG_C99:
19740     case DW_LANG_C11:
19741     case DW_LANG_C:
19742     case DW_LANG_UPC:
19743       cu->language = language_c;
19744       break;
19745     case DW_LANG_Java:
19746     case DW_LANG_C_plus_plus:
19747     case DW_LANG_C_plus_plus_11:
19748     case DW_LANG_C_plus_plus_14:
19749       cu->language = language_cplus;
19750       break;
19751     case DW_LANG_D:
19752       cu->language = language_d;
19753       break;
19754     case DW_LANG_Fortran77:
19755     case DW_LANG_Fortran90:
19756     case DW_LANG_Fortran95:
19757     case DW_LANG_Fortran03:
19758     case DW_LANG_Fortran08:
19759       cu->language = language_fortran;
19760       break;
19761     case DW_LANG_Go:
19762       cu->language = language_go;
19763       break;
19764     case DW_LANG_Mips_Assembler:
19765       cu->language = language_asm;
19766       break;
19767     case DW_LANG_Ada83:
19768     case DW_LANG_Ada95:
19769       cu->language = language_ada;
19770       break;
19771     case DW_LANG_Modula2:
19772       cu->language = language_m2;
19773       break;
19774     case DW_LANG_Pascal83:
19775       cu->language = language_pascal;
19776       break;
19777     case DW_LANG_ObjC:
19778       cu->language = language_objc;
19779       break;
19780     case DW_LANG_Rust:
19781     case DW_LANG_Rust_old:
19782       cu->language = language_rust;
19783       break;
19784     case DW_LANG_Cobol74:
19785     case DW_LANG_Cobol85:
19786     default:
19787       cu->language = language_minimal;
19788       break;
19789     }
19790   cu->language_defn = language_def (cu->language);
19791 }
19792
19793 /* Return the named attribute or NULL if not there.  */
19794
19795 static struct attribute *
19796 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19797 {
19798   for (;;)
19799     {
19800       unsigned int i;
19801       struct attribute *spec = NULL;
19802
19803       for (i = 0; i < die->num_attrs; ++i)
19804         {
19805           if (die->attrs[i].name == name)
19806             return &die->attrs[i];
19807           if (die->attrs[i].name == DW_AT_specification
19808               || die->attrs[i].name == DW_AT_abstract_origin)
19809             spec = &die->attrs[i];
19810         }
19811
19812       if (!spec)
19813         break;
19814
19815       die = follow_die_ref (die, spec, &cu);
19816     }
19817
19818   return NULL;
19819 }
19820
19821 /* Return the named attribute or NULL if not there,
19822    but do not follow DW_AT_specification, etc.
19823    This is for use in contexts where we're reading .debug_types dies.
19824    Following DW_AT_specification, DW_AT_abstract_origin will take us
19825    back up the chain, and we want to go down.  */
19826
19827 static struct attribute *
19828 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19829 {
19830   unsigned int i;
19831
19832   for (i = 0; i < die->num_attrs; ++i)
19833     if (die->attrs[i].name == name)
19834       return &die->attrs[i];
19835
19836   return NULL;
19837 }
19838
19839 /* Return the string associated with a string-typed attribute, or NULL if it
19840    is either not found or is of an incorrect type.  */
19841
19842 static const char *
19843 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19844 {
19845   struct attribute *attr;
19846   const char *str = NULL;
19847
19848   attr = dwarf2_attr (die, name, cu);
19849
19850   if (attr != NULL)
19851     {
19852       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19853           || attr->form == DW_FORM_string
19854           || attr->form == DW_FORM_GNU_str_index
19855           || attr->form == DW_FORM_GNU_strp_alt)
19856         str = DW_STRING (attr);
19857       else
19858         complaint (_("string type expected for attribute %s for "
19859                      "DIE at %s in module %s"),
19860                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19861                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19862     }
19863
19864   return str;
19865 }
19866
19867 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19868    and holds a non-zero value.  This function should only be used for
19869    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19870
19871 static int
19872 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19873 {
19874   struct attribute *attr = dwarf2_attr (die, name, cu);
19875
19876   return (attr && DW_UNSND (attr));
19877 }
19878
19879 static int
19880 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19881 {
19882   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19883      which value is non-zero.  However, we have to be careful with
19884      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19885      (via dwarf2_flag_true_p) follows this attribute.  So we may
19886      end up accidently finding a declaration attribute that belongs
19887      to a different DIE referenced by the specification attribute,
19888      even though the given DIE does not have a declaration attribute.  */
19889   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19890           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19891 }
19892
19893 /* Return the die giving the specification for DIE, if there is
19894    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19895    containing the return value on output.  If there is no
19896    specification, but there is an abstract origin, that is
19897    returned.  */
19898
19899 static struct die_info *
19900 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19901 {
19902   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19903                                              *spec_cu);
19904
19905   if (spec_attr == NULL)
19906     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19907
19908   if (spec_attr == NULL)
19909     return NULL;
19910   else
19911     return follow_die_ref (die, spec_attr, spec_cu);
19912 }
19913
19914 /* Stub for free_line_header to match void * callback types.  */
19915
19916 static void
19917 free_line_header_voidp (void *arg)
19918 {
19919   struct line_header *lh = (struct line_header *) arg;
19920
19921   delete lh;
19922 }
19923
19924 void
19925 line_header::add_include_dir (const char *include_dir)
19926 {
19927   if (dwarf_line_debug >= 2)
19928     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19929                         include_dirs.size () + 1, include_dir);
19930
19931   include_dirs.push_back (include_dir);
19932 }
19933
19934 void
19935 line_header::add_file_name (const char *name,
19936                             dir_index d_index,
19937                             unsigned int mod_time,
19938                             unsigned int length)
19939 {
19940   if (dwarf_line_debug >= 2)
19941     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19942                         (unsigned) file_names.size () + 1, name);
19943
19944   file_names.emplace_back (name, d_index, mod_time, length);
19945 }
19946
19947 /* A convenience function to find the proper .debug_line section for a CU.  */
19948
19949 static struct dwarf2_section_info *
19950 get_debug_line_section (struct dwarf2_cu *cu)
19951 {
19952   struct dwarf2_section_info *section;
19953   struct dwarf2_per_objfile *dwarf2_per_objfile
19954     = cu->per_cu->dwarf2_per_objfile;
19955
19956   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19957      DWO file.  */
19958   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19959     section = &cu->dwo_unit->dwo_file->sections.line;
19960   else if (cu->per_cu->is_dwz)
19961     {
19962       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19963
19964       section = &dwz->line;
19965     }
19966   else
19967     section = &dwarf2_per_objfile->line;
19968
19969   return section;
19970 }
19971
19972 /* Read directory or file name entry format, starting with byte of
19973    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19974    entries count and the entries themselves in the described entry
19975    format.  */
19976
19977 static void
19978 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
19979                         bfd *abfd, const gdb_byte **bufp,
19980                         struct line_header *lh,
19981                         const struct comp_unit_head *cu_header,
19982                         void (*callback) (struct line_header *lh,
19983                                           const char *name,
19984                                           dir_index d_index,
19985                                           unsigned int mod_time,
19986                                           unsigned int length))
19987 {
19988   gdb_byte format_count, formati;
19989   ULONGEST data_count, datai;
19990   const gdb_byte *buf = *bufp;
19991   const gdb_byte *format_header_data;
19992   unsigned int bytes_read;
19993
19994   format_count = read_1_byte (abfd, buf);
19995   buf += 1;
19996   format_header_data = buf;
19997   for (formati = 0; formati < format_count; formati++)
19998     {
19999       read_unsigned_leb128 (abfd, buf, &bytes_read);
20000       buf += bytes_read;
20001       read_unsigned_leb128 (abfd, buf, &bytes_read);
20002       buf += bytes_read;
20003     }
20004
20005   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20006   buf += bytes_read;
20007   for (datai = 0; datai < data_count; datai++)
20008     {
20009       const gdb_byte *format = format_header_data;
20010       struct file_entry fe;
20011
20012       for (formati = 0; formati < format_count; formati++)
20013         {
20014           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20015           format += bytes_read;
20016
20017           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20018           format += bytes_read;
20019
20020           gdb::optional<const char *> string;
20021           gdb::optional<unsigned int> uint;
20022
20023           switch (form)
20024             {
20025             case DW_FORM_string:
20026               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20027               buf += bytes_read;
20028               break;
20029
20030             case DW_FORM_line_strp:
20031               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20032                                                          abfd, buf,
20033                                                          cu_header,
20034                                                          &bytes_read));
20035               buf += bytes_read;
20036               break;
20037
20038             case DW_FORM_data1:
20039               uint.emplace (read_1_byte (abfd, buf));
20040               buf += 1;
20041               break;
20042
20043             case DW_FORM_data2:
20044               uint.emplace (read_2_bytes (abfd, buf));
20045               buf += 2;
20046               break;
20047
20048             case DW_FORM_data4:
20049               uint.emplace (read_4_bytes (abfd, buf));
20050               buf += 4;
20051               break;
20052
20053             case DW_FORM_data8:
20054               uint.emplace (read_8_bytes (abfd, buf));
20055               buf += 8;
20056               break;
20057
20058             case DW_FORM_udata:
20059               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20060               buf += bytes_read;
20061               break;
20062
20063             case DW_FORM_block:
20064               /* It is valid only for DW_LNCT_timestamp which is ignored by
20065                  current GDB.  */
20066               break;
20067             }
20068
20069           switch (content_type)
20070             {
20071             case DW_LNCT_path:
20072               if (string.has_value ())
20073                 fe.name = *string;
20074               break;
20075             case DW_LNCT_directory_index:
20076               if (uint.has_value ())
20077                 fe.d_index = (dir_index) *uint;
20078               break;
20079             case DW_LNCT_timestamp:
20080               if (uint.has_value ())
20081                 fe.mod_time = *uint;
20082               break;
20083             case DW_LNCT_size:
20084               if (uint.has_value ())
20085                 fe.length = *uint;
20086               break;
20087             case DW_LNCT_MD5:
20088               break;
20089             default:
20090               complaint (_("Unknown format content type %s"),
20091                          pulongest (content_type));
20092             }
20093         }
20094
20095       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20096     }
20097
20098   *bufp = buf;
20099 }
20100
20101 /* Read the statement program header starting at OFFSET in
20102    .debug_line, or .debug_line.dwo.  Return a pointer
20103    to a struct line_header, allocated using xmalloc.
20104    Returns NULL if there is a problem reading the header, e.g., if it
20105    has a version we don't understand.
20106
20107    NOTE: the strings in the include directory and file name tables of
20108    the returned object point into the dwarf line section buffer,
20109    and must not be freed.  */
20110
20111 static line_header_up
20112 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20113 {
20114   const gdb_byte *line_ptr;
20115   unsigned int bytes_read, offset_size;
20116   int i;
20117   const char *cur_dir, *cur_file;
20118   struct dwarf2_section_info *section;
20119   bfd *abfd;
20120   struct dwarf2_per_objfile *dwarf2_per_objfile
20121     = cu->per_cu->dwarf2_per_objfile;
20122
20123   section = get_debug_line_section (cu);
20124   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20125   if (section->buffer == NULL)
20126     {
20127       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20128         complaint (_("missing .debug_line.dwo section"));
20129       else
20130         complaint (_("missing .debug_line section"));
20131       return 0;
20132     }
20133
20134   /* We can't do this until we know the section is non-empty.
20135      Only then do we know we have such a section.  */
20136   abfd = get_section_bfd_owner (section);
20137
20138   /* Make sure that at least there's room for the total_length field.
20139      That could be 12 bytes long, but we're just going to fudge that.  */
20140   if (to_underlying (sect_off) + 4 >= section->size)
20141     {
20142       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20143       return 0;
20144     }
20145
20146   line_header_up lh (new line_header ());
20147
20148   lh->sect_off = sect_off;
20149   lh->offset_in_dwz = cu->per_cu->is_dwz;
20150
20151   line_ptr = section->buffer + to_underlying (sect_off);
20152
20153   /* Read in the header.  */
20154   lh->total_length =
20155     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20156                                             &bytes_read, &offset_size);
20157   line_ptr += bytes_read;
20158   if (line_ptr + lh->total_length > (section->buffer + section->size))
20159     {
20160       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20161       return 0;
20162     }
20163   lh->statement_program_end = line_ptr + lh->total_length;
20164   lh->version = read_2_bytes (abfd, line_ptr);
20165   line_ptr += 2;
20166   if (lh->version > 5)
20167     {
20168       /* This is a version we don't understand.  The format could have
20169          changed in ways we don't handle properly so just punt.  */
20170       complaint (_("unsupported version in .debug_line section"));
20171       return NULL;
20172     }
20173   if (lh->version >= 5)
20174     {
20175       gdb_byte segment_selector_size;
20176
20177       /* Skip address size.  */
20178       read_1_byte (abfd, line_ptr);
20179       line_ptr += 1;
20180
20181       segment_selector_size = read_1_byte (abfd, line_ptr);
20182       line_ptr += 1;
20183       if (segment_selector_size != 0)
20184         {
20185           complaint (_("unsupported segment selector size %u "
20186                        "in .debug_line section"),
20187                      segment_selector_size);
20188           return NULL;
20189         }
20190     }
20191   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20192   line_ptr += offset_size;
20193   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20194   line_ptr += 1;
20195   if (lh->version >= 4)
20196     {
20197       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20198       line_ptr += 1;
20199     }
20200   else
20201     lh->maximum_ops_per_instruction = 1;
20202
20203   if (lh->maximum_ops_per_instruction == 0)
20204     {
20205       lh->maximum_ops_per_instruction = 1;
20206       complaint (_("invalid maximum_ops_per_instruction "
20207                    "in `.debug_line' section"));
20208     }
20209
20210   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20211   line_ptr += 1;
20212   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20213   line_ptr += 1;
20214   lh->line_range = read_1_byte (abfd, line_ptr);
20215   line_ptr += 1;
20216   lh->opcode_base = read_1_byte (abfd, line_ptr);
20217   line_ptr += 1;
20218   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20219
20220   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20221   for (i = 1; i < lh->opcode_base; ++i)
20222     {
20223       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20224       line_ptr += 1;
20225     }
20226
20227   if (lh->version >= 5)
20228     {
20229       /* Read directory table.  */
20230       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20231                               &cu->header,
20232                               [] (struct line_header *lh, const char *name,
20233                                   dir_index d_index, unsigned int mod_time,
20234                                   unsigned int length)
20235         {
20236           lh->add_include_dir (name);
20237         });
20238
20239       /* Read file name table.  */
20240       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20241                               &cu->header,
20242                               [] (struct line_header *lh, const char *name,
20243                                   dir_index d_index, unsigned int mod_time,
20244                                   unsigned int length)
20245         {
20246           lh->add_file_name (name, d_index, mod_time, length);
20247         });
20248     }
20249   else
20250     {
20251       /* Read directory table.  */
20252       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20253         {
20254           line_ptr += bytes_read;
20255           lh->add_include_dir (cur_dir);
20256         }
20257       line_ptr += bytes_read;
20258
20259       /* Read file name table.  */
20260       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20261         {
20262           unsigned int mod_time, length;
20263           dir_index d_index;
20264
20265           line_ptr += bytes_read;
20266           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20267           line_ptr += bytes_read;
20268           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20269           line_ptr += bytes_read;
20270           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20271           line_ptr += bytes_read;
20272
20273           lh->add_file_name (cur_file, d_index, mod_time, length);
20274         }
20275       line_ptr += bytes_read;
20276     }
20277   lh->statement_program_start = line_ptr;
20278
20279   if (line_ptr > (section->buffer + section->size))
20280     complaint (_("line number info header doesn't "
20281                  "fit in `.debug_line' section"));
20282
20283   return lh;
20284 }
20285
20286 /* Subroutine of dwarf_decode_lines to simplify it.
20287    Return the file name of the psymtab for included file FILE_INDEX
20288    in line header LH of PST.
20289    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20290    If space for the result is malloc'd, *NAME_HOLDER will be set.
20291    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20292
20293 static const char *
20294 psymtab_include_file_name (const struct line_header *lh, int file_index,
20295                            const struct partial_symtab *pst,
20296                            const char *comp_dir,
20297                            gdb::unique_xmalloc_ptr<char> *name_holder)
20298 {
20299   const file_entry &fe = lh->file_names[file_index];
20300   const char *include_name = fe.name;
20301   const char *include_name_to_compare = include_name;
20302   const char *pst_filename;
20303   int file_is_pst;
20304
20305   const char *dir_name = fe.include_dir (lh);
20306
20307   gdb::unique_xmalloc_ptr<char> hold_compare;
20308   if (!IS_ABSOLUTE_PATH (include_name)
20309       && (dir_name != NULL || comp_dir != NULL))
20310     {
20311       /* Avoid creating a duplicate psymtab for PST.
20312          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20313          Before we do the comparison, however, we need to account
20314          for DIR_NAME and COMP_DIR.
20315          First prepend dir_name (if non-NULL).  If we still don't
20316          have an absolute path prepend comp_dir (if non-NULL).
20317          However, the directory we record in the include-file's
20318          psymtab does not contain COMP_DIR (to match the
20319          corresponding symtab(s)).
20320
20321          Example:
20322
20323          bash$ cd /tmp
20324          bash$ gcc -g ./hello.c
20325          include_name = "hello.c"
20326          dir_name = "."
20327          DW_AT_comp_dir = comp_dir = "/tmp"
20328          DW_AT_name = "./hello.c"
20329
20330       */
20331
20332       if (dir_name != NULL)
20333         {
20334           name_holder->reset (concat (dir_name, SLASH_STRING,
20335                                       include_name, (char *) NULL));
20336           include_name = name_holder->get ();
20337           include_name_to_compare = include_name;
20338         }
20339       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20340         {
20341           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20342                                       include_name, (char *) NULL));
20343           include_name_to_compare = hold_compare.get ();
20344         }
20345     }
20346
20347   pst_filename = pst->filename;
20348   gdb::unique_xmalloc_ptr<char> copied_name;
20349   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20350     {
20351       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20352                                  pst_filename, (char *) NULL));
20353       pst_filename = copied_name.get ();
20354     }
20355
20356   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20357
20358   if (file_is_pst)
20359     return NULL;
20360   return include_name;
20361 }
20362
20363 /* State machine to track the state of the line number program.  */
20364
20365 class lnp_state_machine
20366 {
20367 public:
20368   /* Initialize a machine state for the start of a line number
20369      program.  */
20370   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20371                      bool record_lines_p);
20372
20373   file_entry *current_file ()
20374   {
20375     /* lh->file_names is 0-based, but the file name numbers in the
20376        statement program are 1-based.  */
20377     return m_line_header->file_name_at (m_file);
20378   }
20379
20380   /* Record the line in the state machine.  END_SEQUENCE is true if
20381      we're processing the end of a sequence.  */
20382   void record_line (bool end_sequence);
20383
20384   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20385      nop-out rest of the lines in this sequence.  */
20386   void check_line_address (struct dwarf2_cu *cu,
20387                            const gdb_byte *line_ptr,
20388                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20389
20390   void handle_set_discriminator (unsigned int discriminator)
20391   {
20392     m_discriminator = discriminator;
20393     m_line_has_non_zero_discriminator |= discriminator != 0;
20394   }
20395
20396   /* Handle DW_LNE_set_address.  */
20397   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20398   {
20399     m_op_index = 0;
20400     address += baseaddr;
20401     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20402   }
20403
20404   /* Handle DW_LNS_advance_pc.  */
20405   void handle_advance_pc (CORE_ADDR adjust);
20406
20407   /* Handle a special opcode.  */
20408   void handle_special_opcode (unsigned char op_code);
20409
20410   /* Handle DW_LNS_advance_line.  */
20411   void handle_advance_line (int line_delta)
20412   {
20413     advance_line (line_delta);
20414   }
20415
20416   /* Handle DW_LNS_set_file.  */
20417   void handle_set_file (file_name_index file);
20418
20419   /* Handle DW_LNS_negate_stmt.  */
20420   void handle_negate_stmt ()
20421   {
20422     m_is_stmt = !m_is_stmt;
20423   }
20424
20425   /* Handle DW_LNS_const_add_pc.  */
20426   void handle_const_add_pc ();
20427
20428   /* Handle DW_LNS_fixed_advance_pc.  */
20429   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20430   {
20431     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20432     m_op_index = 0;
20433   }
20434
20435   /* Handle DW_LNS_copy.  */
20436   void handle_copy ()
20437   {
20438     record_line (false);
20439     m_discriminator = 0;
20440   }
20441
20442   /* Handle DW_LNE_end_sequence.  */
20443   void handle_end_sequence ()
20444   {
20445     m_currently_recording_lines = true;
20446   }
20447
20448 private:
20449   /* Advance the line by LINE_DELTA.  */
20450   void advance_line (int line_delta)
20451   {
20452     m_line += line_delta;
20453
20454     if (line_delta != 0)
20455       m_line_has_non_zero_discriminator = m_discriminator != 0;
20456   }
20457
20458   struct dwarf2_cu *m_cu;
20459
20460   gdbarch *m_gdbarch;
20461
20462   /* True if we're recording lines.
20463      Otherwise we're building partial symtabs and are just interested in
20464      finding include files mentioned by the line number program.  */
20465   bool m_record_lines_p;
20466
20467   /* The line number header.  */
20468   line_header *m_line_header;
20469
20470   /* These are part of the standard DWARF line number state machine,
20471      and initialized according to the DWARF spec.  */
20472
20473   unsigned char m_op_index = 0;
20474   /* The line table index (1-based) of the current file.  */
20475   file_name_index m_file = (file_name_index) 1;
20476   unsigned int m_line = 1;
20477
20478   /* These are initialized in the constructor.  */
20479
20480   CORE_ADDR m_address;
20481   bool m_is_stmt;
20482   unsigned int m_discriminator;
20483
20484   /* Additional bits of state we need to track.  */
20485
20486   /* The last file that we called dwarf2_start_subfile for.
20487      This is only used for TLLs.  */
20488   unsigned int m_last_file = 0;
20489   /* The last file a line number was recorded for.  */
20490   struct subfile *m_last_subfile = NULL;
20491
20492   /* When true, record the lines we decode.  */
20493   bool m_currently_recording_lines = false;
20494
20495   /* The last line number that was recorded, used to coalesce
20496      consecutive entries for the same line.  This can happen, for
20497      example, when discriminators are present.  PR 17276.  */
20498   unsigned int m_last_line = 0;
20499   bool m_line_has_non_zero_discriminator = false;
20500 };
20501
20502 void
20503 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20504 {
20505   CORE_ADDR addr_adj = (((m_op_index + adjust)
20506                          / m_line_header->maximum_ops_per_instruction)
20507                         * m_line_header->minimum_instruction_length);
20508   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20509   m_op_index = ((m_op_index + adjust)
20510                 % m_line_header->maximum_ops_per_instruction);
20511 }
20512
20513 void
20514 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20515 {
20516   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20517   CORE_ADDR addr_adj = (((m_op_index
20518                           + (adj_opcode / m_line_header->line_range))
20519                          / m_line_header->maximum_ops_per_instruction)
20520                         * m_line_header->minimum_instruction_length);
20521   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20522   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20523                 % m_line_header->maximum_ops_per_instruction);
20524
20525   int line_delta = (m_line_header->line_base
20526                     + (adj_opcode % m_line_header->line_range));
20527   advance_line (line_delta);
20528   record_line (false);
20529   m_discriminator = 0;
20530 }
20531
20532 void
20533 lnp_state_machine::handle_set_file (file_name_index file)
20534 {
20535   m_file = file;
20536
20537   const file_entry *fe = current_file ();
20538   if (fe == NULL)
20539     dwarf2_debug_line_missing_file_complaint ();
20540   else if (m_record_lines_p)
20541     {
20542       const char *dir = fe->include_dir (m_line_header);
20543
20544       m_last_subfile = m_cu->builder->get_current_subfile ();
20545       m_line_has_non_zero_discriminator = m_discriminator != 0;
20546       dwarf2_start_subfile (m_cu, fe->name, dir);
20547     }
20548 }
20549
20550 void
20551 lnp_state_machine::handle_const_add_pc ()
20552 {
20553   CORE_ADDR adjust
20554     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20555
20556   CORE_ADDR addr_adj
20557     = (((m_op_index + adjust)
20558         / m_line_header->maximum_ops_per_instruction)
20559        * m_line_header->minimum_instruction_length);
20560
20561   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20562   m_op_index = ((m_op_index + adjust)
20563                 % m_line_header->maximum_ops_per_instruction);
20564 }
20565
20566 /* Return non-zero if we should add LINE to the line number table.
20567    LINE is the line to add, LAST_LINE is the last line that was added,
20568    LAST_SUBFILE is the subfile for LAST_LINE.
20569    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20570    had a non-zero discriminator.
20571
20572    We have to be careful in the presence of discriminators.
20573    E.g., for this line:
20574
20575      for (i = 0; i < 100000; i++);
20576
20577    clang can emit four line number entries for that one line,
20578    each with a different discriminator.
20579    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20580
20581    However, we want gdb to coalesce all four entries into one.
20582    Otherwise the user could stepi into the middle of the line and
20583    gdb would get confused about whether the pc really was in the
20584    middle of the line.
20585
20586    Things are further complicated by the fact that two consecutive
20587    line number entries for the same line is a heuristic used by gcc
20588    to denote the end of the prologue.  So we can't just discard duplicate
20589    entries, we have to be selective about it.  The heuristic we use is
20590    that we only collapse consecutive entries for the same line if at least
20591    one of those entries has a non-zero discriminator.  PR 17276.
20592
20593    Note: Addresses in the line number state machine can never go backwards
20594    within one sequence, thus this coalescing is ok.  */
20595
20596 static int
20597 dwarf_record_line_p (struct dwarf2_cu *cu,
20598                      unsigned int line, unsigned int last_line,
20599                      int line_has_non_zero_discriminator,
20600                      struct subfile *last_subfile)
20601 {
20602   if (cu->builder->get_current_subfile () != last_subfile)
20603     return 1;
20604   if (line != last_line)
20605     return 1;
20606   /* Same line for the same file that we've seen already.
20607      As a last check, for pr 17276, only record the line if the line
20608      has never had a non-zero discriminator.  */
20609   if (!line_has_non_zero_discriminator)
20610     return 1;
20611   return 0;
20612 }
20613
20614 /* Use the CU's builder to record line number LINE beginning at
20615    address ADDRESS in the line table of subfile SUBFILE.  */
20616
20617 static void
20618 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20619                      unsigned int line, CORE_ADDR address,
20620                      struct dwarf2_cu *cu)
20621 {
20622   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20623
20624   if (dwarf_line_debug)
20625     {
20626       fprintf_unfiltered (gdb_stdlog,
20627                           "Recording line %u, file %s, address %s\n",
20628                           line, lbasename (subfile->name),
20629                           paddress (gdbarch, address));
20630     }
20631
20632   if (cu != nullptr)
20633     cu->builder->record_line (subfile, line, addr);
20634 }
20635
20636 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20637    Mark the end of a set of line number records.
20638    The arguments are the same as for dwarf_record_line_1.
20639    If SUBFILE is NULL the request is ignored.  */
20640
20641 static void
20642 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20643                    CORE_ADDR address, struct dwarf2_cu *cu)
20644 {
20645   if (subfile == NULL)
20646     return;
20647
20648   if (dwarf_line_debug)
20649     {
20650       fprintf_unfiltered (gdb_stdlog,
20651                           "Finishing current line, file %s, address %s\n",
20652                           lbasename (subfile->name),
20653                           paddress (gdbarch, address));
20654     }
20655
20656   dwarf_record_line_1 (gdbarch, subfile, 0, address, cu);
20657 }
20658
20659 void
20660 lnp_state_machine::record_line (bool end_sequence)
20661 {
20662   if (dwarf_line_debug)
20663     {
20664       fprintf_unfiltered (gdb_stdlog,
20665                           "Processing actual line %u: file %u,"
20666                           " address %s, is_stmt %u, discrim %u\n",
20667                           m_line, to_underlying (m_file),
20668                           paddress (m_gdbarch, m_address),
20669                           m_is_stmt, m_discriminator);
20670     }
20671
20672   file_entry *fe = current_file ();
20673
20674   if (fe == NULL)
20675     dwarf2_debug_line_missing_file_complaint ();
20676   /* For now we ignore lines not starting on an instruction boundary.
20677      But not when processing end_sequence for compatibility with the
20678      previous version of the code.  */
20679   else if (m_op_index == 0 || end_sequence)
20680     {
20681       fe->included_p = 1;
20682       if (m_record_lines_p && m_is_stmt)
20683         {
20684           if (m_last_subfile != m_cu->builder->get_current_subfile ()
20685               || end_sequence)
20686             {
20687               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
20688                                  m_currently_recording_lines ? m_cu : nullptr);
20689             }
20690
20691           if (!end_sequence)
20692             {
20693               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
20694                                        m_line_has_non_zero_discriminator,
20695                                        m_last_subfile))
20696                 {
20697                   dwarf_record_line_1 (m_gdbarch,
20698                                        m_cu->builder->get_current_subfile (),
20699                                        m_line, m_address,
20700                                        m_currently_recording_lines ? m_cu : nullptr);
20701                 }
20702               m_last_subfile = m_cu->builder->get_current_subfile ();
20703               m_last_line = m_line;
20704             }
20705         }
20706     }
20707 }
20708
20709 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
20710                                       line_header *lh, bool record_lines_p)
20711 {
20712   m_cu = cu;
20713   m_gdbarch = arch;
20714   m_record_lines_p = record_lines_p;
20715   m_line_header = lh;
20716
20717   m_currently_recording_lines = true;
20718
20719   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20720      was a line entry for it so that the backend has a chance to adjust it
20721      and also record it in case it needs it.  This is currently used by MIPS
20722      code, cf. `mips_adjust_dwarf2_line'.  */
20723   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20724   m_is_stmt = lh->default_is_stmt;
20725   m_discriminator = 0;
20726 }
20727
20728 void
20729 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20730                                        const gdb_byte *line_ptr,
20731                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20732 {
20733   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20734      the pc range of the CU.  However, we restrict the test to only ADDRESS
20735      values of zero to preserve GDB's previous behaviour which is to handle
20736      the specific case of a function being GC'd by the linker.  */
20737
20738   if (address == 0 && address < unrelocated_lowpc)
20739     {
20740       /* This line table is for a function which has been
20741          GCd by the linker.  Ignore it.  PR gdb/12528 */
20742
20743       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20744       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20745
20746       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20747                  line_offset, objfile_name (objfile));
20748       m_currently_recording_lines = false;
20749       /* Note: m_currently_recording_lines is left as false until we see
20750          DW_LNE_end_sequence.  */
20751     }
20752 }
20753
20754 /* Subroutine of dwarf_decode_lines to simplify it.
20755    Process the line number information in LH.
20756    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20757    program in order to set included_p for every referenced header.  */
20758
20759 static void
20760 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20761                       const int decode_for_pst_p, CORE_ADDR lowpc)
20762 {
20763   const gdb_byte *line_ptr, *extended_end;
20764   const gdb_byte *line_end;
20765   unsigned int bytes_read, extended_len;
20766   unsigned char op_code, extended_op;
20767   CORE_ADDR baseaddr;
20768   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20769   bfd *abfd = objfile->obfd;
20770   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20771   /* True if we're recording line info (as opposed to building partial
20772      symtabs and just interested in finding include files mentioned by
20773      the line number program).  */
20774   bool record_lines_p = !decode_for_pst_p;
20775
20776   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20777
20778   line_ptr = lh->statement_program_start;
20779   line_end = lh->statement_program_end;
20780
20781   /* Read the statement sequences until there's nothing left.  */
20782   while (line_ptr < line_end)
20783     {
20784       /* The DWARF line number program state machine.  Reset the state
20785          machine at the start of each sequence.  */
20786       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
20787       bool end_sequence = false;
20788
20789       if (record_lines_p)
20790         {
20791           /* Start a subfile for the current file of the state
20792              machine.  */
20793           const file_entry *fe = state_machine.current_file ();
20794
20795           if (fe != NULL)
20796             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
20797         }
20798
20799       /* Decode the table.  */
20800       while (line_ptr < line_end && !end_sequence)
20801         {
20802           op_code = read_1_byte (abfd, line_ptr);
20803           line_ptr += 1;
20804
20805           if (op_code >= lh->opcode_base)
20806             {
20807               /* Special opcode.  */
20808               state_machine.handle_special_opcode (op_code);
20809             }
20810           else switch (op_code)
20811             {
20812             case DW_LNS_extended_op:
20813               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20814                                                    &bytes_read);
20815               line_ptr += bytes_read;
20816               extended_end = line_ptr + extended_len;
20817               extended_op = read_1_byte (abfd, line_ptr);
20818               line_ptr += 1;
20819               switch (extended_op)
20820                 {
20821                 case DW_LNE_end_sequence:
20822                   state_machine.handle_end_sequence ();
20823                   end_sequence = true;
20824                   break;
20825                 case DW_LNE_set_address:
20826                   {
20827                     CORE_ADDR address
20828                       = read_address (abfd, line_ptr, cu, &bytes_read);
20829                     line_ptr += bytes_read;
20830
20831                     state_machine.check_line_address (cu, line_ptr,
20832                                                       lowpc - baseaddr, address);
20833                     state_machine.handle_set_address (baseaddr, address);
20834                   }
20835                   break;
20836                 case DW_LNE_define_file:
20837                   {
20838                     const char *cur_file;
20839                     unsigned int mod_time, length;
20840                     dir_index dindex;
20841
20842                     cur_file = read_direct_string (abfd, line_ptr,
20843                                                    &bytes_read);
20844                     line_ptr += bytes_read;
20845                     dindex = (dir_index)
20846                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20847                     line_ptr += bytes_read;
20848                     mod_time =
20849                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20850                     line_ptr += bytes_read;
20851                     length =
20852                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20853                     line_ptr += bytes_read;
20854                     lh->add_file_name (cur_file, dindex, mod_time, length);
20855                   }
20856                   break;
20857                 case DW_LNE_set_discriminator:
20858                   {
20859                     /* The discriminator is not interesting to the
20860                        debugger; just ignore it.  We still need to
20861                        check its value though:
20862                        if there are consecutive entries for the same
20863                        (non-prologue) line we want to coalesce them.
20864                        PR 17276.  */
20865                     unsigned int discr
20866                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20867                     line_ptr += bytes_read;
20868
20869                     state_machine.handle_set_discriminator (discr);
20870                   }
20871                   break;
20872                 default:
20873                   complaint (_("mangled .debug_line section"));
20874                   return;
20875                 }
20876               /* Make sure that we parsed the extended op correctly.  If e.g.
20877                  we expected a different address size than the producer used,
20878                  we may have read the wrong number of bytes.  */
20879               if (line_ptr != extended_end)
20880                 {
20881                   complaint (_("mangled .debug_line section"));
20882                   return;
20883                 }
20884               break;
20885             case DW_LNS_copy:
20886               state_machine.handle_copy ();
20887               break;
20888             case DW_LNS_advance_pc:
20889               {
20890                 CORE_ADDR adjust
20891                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20892                 line_ptr += bytes_read;
20893
20894                 state_machine.handle_advance_pc (adjust);
20895               }
20896               break;
20897             case DW_LNS_advance_line:
20898               {
20899                 int line_delta
20900                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20901                 line_ptr += bytes_read;
20902
20903                 state_machine.handle_advance_line (line_delta);
20904               }
20905               break;
20906             case DW_LNS_set_file:
20907               {
20908                 file_name_index file
20909                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20910                                                             &bytes_read);
20911                 line_ptr += bytes_read;
20912
20913                 state_machine.handle_set_file (file);
20914               }
20915               break;
20916             case DW_LNS_set_column:
20917               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20918               line_ptr += bytes_read;
20919               break;
20920             case DW_LNS_negate_stmt:
20921               state_machine.handle_negate_stmt ();
20922               break;
20923             case DW_LNS_set_basic_block:
20924               break;
20925             /* Add to the address register of the state machine the
20926                address increment value corresponding to special opcode
20927                255.  I.e., this value is scaled by the minimum
20928                instruction length since special opcode 255 would have
20929                scaled the increment.  */
20930             case DW_LNS_const_add_pc:
20931               state_machine.handle_const_add_pc ();
20932               break;
20933             case DW_LNS_fixed_advance_pc:
20934               {
20935                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20936                 line_ptr += 2;
20937
20938                 state_machine.handle_fixed_advance_pc (addr_adj);
20939               }
20940               break;
20941             default:
20942               {
20943                 /* Unknown standard opcode, ignore it.  */
20944                 int i;
20945
20946                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20947                   {
20948                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20949                     line_ptr += bytes_read;
20950                   }
20951               }
20952             }
20953         }
20954
20955       if (!end_sequence)
20956         dwarf2_debug_line_missing_end_sequence_complaint ();
20957
20958       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20959          in which case we still finish recording the last line).  */
20960       state_machine.record_line (true);
20961     }
20962 }
20963
20964 /* Decode the Line Number Program (LNP) for the given line_header
20965    structure and CU.  The actual information extracted and the type
20966    of structures created from the LNP depends on the value of PST.
20967
20968    1. If PST is NULL, then this procedure uses the data from the program
20969       to create all necessary symbol tables, and their linetables.
20970
20971    2. If PST is not NULL, this procedure reads the program to determine
20972       the list of files included by the unit represented by PST, and
20973       builds all the associated partial symbol tables.
20974
20975    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20976    It is used for relative paths in the line table.
20977    NOTE: When processing partial symtabs (pst != NULL),
20978    comp_dir == pst->dirname.
20979
20980    NOTE: It is important that psymtabs have the same file name (via strcmp)
20981    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20982    symtab we don't use it in the name of the psymtabs we create.
20983    E.g. expand_line_sal requires this when finding psymtabs to expand.
20984    A good testcase for this is mb-inline.exp.
20985
20986    LOWPC is the lowest address in CU (or 0 if not known).
20987
20988    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20989    for its PC<->lines mapping information.  Otherwise only the filename
20990    table is read in.  */
20991
20992 static void
20993 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20994                     struct dwarf2_cu *cu, struct partial_symtab *pst,
20995                     CORE_ADDR lowpc, int decode_mapping)
20996 {
20997   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20998   const int decode_for_pst_p = (pst != NULL);
20999
21000   if (decode_mapping)
21001     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21002
21003   if (decode_for_pst_p)
21004     {
21005       int file_index;
21006
21007       /* Now that we're done scanning the Line Header Program, we can
21008          create the psymtab of each included file.  */
21009       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21010         if (lh->file_names[file_index].included_p == 1)
21011           {
21012             gdb::unique_xmalloc_ptr<char> name_holder;
21013             const char *include_name =
21014               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21015                                          &name_holder);
21016             if (include_name != NULL)
21017               dwarf2_create_include_psymtab (include_name, pst, objfile);
21018           }
21019     }
21020   else
21021     {
21022       /* Make sure a symtab is created for every file, even files
21023          which contain only variables (i.e. no code with associated
21024          line numbers).  */
21025       struct compunit_symtab *cust = cu->builder->get_compunit_symtab ();
21026       int i;
21027
21028       for (i = 0; i < lh->file_names.size (); i++)
21029         {
21030           file_entry &fe = lh->file_names[i];
21031
21032           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
21033
21034           if (cu->builder->get_current_subfile ()->symtab == NULL)
21035             {
21036               cu->builder->get_current_subfile ()->symtab
21037                 = allocate_symtab (cust,
21038                                    cu->builder->get_current_subfile ()->name);
21039             }
21040           fe.symtab = cu->builder->get_current_subfile ()->symtab;
21041         }
21042     }
21043 }
21044
21045 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21046    DIRNAME the name of the source directory which contains FILENAME
21047    or NULL if not known.
21048    This routine tries to keep line numbers from identical absolute and
21049    relative file names in a common subfile.
21050
21051    Using the `list' example from the GDB testsuite, which resides in
21052    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21053    of /srcdir/list0.c yields the following debugging information for list0.c:
21054
21055    DW_AT_name:          /srcdir/list0.c
21056    DW_AT_comp_dir:      /compdir
21057    files.files[0].name: list0.h
21058    files.files[0].dir:  /srcdir
21059    files.files[1].name: list0.c
21060    files.files[1].dir:  /srcdir
21061
21062    The line number information for list0.c has to end up in a single
21063    subfile, so that `break /srcdir/list0.c:1' works as expected.
21064    start_subfile will ensure that this happens provided that we pass the
21065    concatenation of files.files[1].dir and files.files[1].name as the
21066    subfile's name.  */
21067
21068 static void
21069 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21070                       const char *dirname)
21071 {
21072   char *copy = NULL;
21073
21074   /* In order not to lose the line information directory,
21075      we concatenate it to the filename when it makes sense.
21076      Note that the Dwarf3 standard says (speaking of filenames in line
21077      information): ``The directory index is ignored for file names
21078      that represent full path names''.  Thus ignoring dirname in the
21079      `else' branch below isn't an issue.  */
21080
21081   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21082     {
21083       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21084       filename = copy;
21085     }
21086
21087   cu->builder->start_subfile (filename);
21088
21089   if (copy != NULL)
21090     xfree (copy);
21091 }
21092
21093 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
21094    buildsym_compunit constructor.  */
21095
21096 static struct compunit_symtab *
21097 dwarf2_start_symtab (struct dwarf2_cu *cu,
21098                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21099 {
21100   gdb_assert (cu->builder == nullptr);
21101
21102   cu->builder.reset (new struct buildsym_compunit
21103                      (cu->per_cu->dwarf2_per_objfile->objfile,
21104                       name, comp_dir, cu->language, low_pc));
21105
21106   cu->list_in_scope = cu->builder->get_file_symbols ();
21107
21108   cu->builder->record_debugformat ("DWARF 2");
21109   cu->builder->record_producer (cu->producer);
21110
21111   cu->processing_has_namespace_info = 0;
21112
21113   return cu->builder->get_compunit_symtab ();
21114 }
21115
21116 static void
21117 var_decode_location (struct attribute *attr, struct symbol *sym,
21118                      struct dwarf2_cu *cu)
21119 {
21120   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21121   struct comp_unit_head *cu_header = &cu->header;
21122
21123   /* NOTE drow/2003-01-30: There used to be a comment and some special
21124      code here to turn a symbol with DW_AT_external and a
21125      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21126      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21127      with some versions of binutils) where shared libraries could have
21128      relocations against symbols in their debug information - the
21129      minimal symbol would have the right address, but the debug info
21130      would not.  It's no longer necessary, because we will explicitly
21131      apply relocations when we read in the debug information now.  */
21132
21133   /* A DW_AT_location attribute with no contents indicates that a
21134      variable has been optimized away.  */
21135   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21136     {
21137       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21138       return;
21139     }
21140
21141   /* Handle one degenerate form of location expression specially, to
21142      preserve GDB's previous behavior when section offsets are
21143      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21144      then mark this symbol as LOC_STATIC.  */
21145
21146   if (attr_form_is_block (attr)
21147       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21148            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21149           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21150               && (DW_BLOCK (attr)->size
21151                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21152     {
21153       unsigned int dummy;
21154
21155       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21156         SYMBOL_VALUE_ADDRESS (sym) =
21157           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21158       else
21159         SYMBOL_VALUE_ADDRESS (sym) =
21160           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21161       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21162       fixup_symbol_section (sym, objfile);
21163       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21164                                               SYMBOL_SECTION (sym));
21165       return;
21166     }
21167
21168   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21169      expression evaluator, and use LOC_COMPUTED only when necessary
21170      (i.e. when the value of a register or memory location is
21171      referenced, or a thread-local block, etc.).  Then again, it might
21172      not be worthwhile.  I'm assuming that it isn't unless performance
21173      or memory numbers show me otherwise.  */
21174
21175   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21176
21177   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21178     cu->has_loclist = 1;
21179 }
21180
21181 /* Given a pointer to a DWARF information entry, figure out if we need
21182    to make a symbol table entry for it, and if so, create a new entry
21183    and return a pointer to it.
21184    If TYPE is NULL, determine symbol type from the die, otherwise
21185    used the passed type.
21186    If SPACE is not NULL, use it to hold the new symbol.  If it is
21187    NULL, allocate a new symbol on the objfile's obstack.  */
21188
21189 static struct symbol *
21190 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21191             struct symbol *space)
21192 {
21193   struct dwarf2_per_objfile *dwarf2_per_objfile
21194     = cu->per_cu->dwarf2_per_objfile;
21195   struct objfile *objfile = dwarf2_per_objfile->objfile;
21196   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21197   struct symbol *sym = NULL;
21198   const char *name;
21199   struct attribute *attr = NULL;
21200   struct attribute *attr2 = NULL;
21201   CORE_ADDR baseaddr;
21202   struct pending **list_to_add = NULL;
21203
21204   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21205
21206   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21207
21208   name = dwarf2_name (die, cu);
21209   if (name)
21210     {
21211       const char *linkagename;
21212       int suppress_add = 0;
21213
21214       if (space)
21215         sym = space;
21216       else
21217         sym = allocate_symbol (objfile);
21218       OBJSTAT (objfile, n_syms++);
21219
21220       /* Cache this symbol's name and the name's demangled form (if any).  */
21221       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21222       linkagename = dwarf2_physname (name, die, cu);
21223       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21224
21225       /* Fortran does not have mangling standard and the mangling does differ
21226          between gfortran, iFort etc.  */
21227       if (cu->language == language_fortran
21228           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21229         symbol_set_demangled_name (&(sym->ginfo),
21230                                    dwarf2_full_name (name, die, cu),
21231                                    NULL);
21232
21233       /* Default assumptions.
21234          Use the passed type or decode it from the die.  */
21235       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21236       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21237       if (type != NULL)
21238         SYMBOL_TYPE (sym) = type;
21239       else
21240         SYMBOL_TYPE (sym) = die_type (die, cu);
21241       attr = dwarf2_attr (die,
21242                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21243                           cu);
21244       if (attr)
21245         {
21246           SYMBOL_LINE (sym) = DW_UNSND (attr);
21247         }
21248
21249       attr = dwarf2_attr (die,
21250                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21251                           cu);
21252       if (attr)
21253         {
21254           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21255           struct file_entry *fe;
21256
21257           if (cu->line_header != NULL)
21258             fe = cu->line_header->file_name_at (file_index);
21259           else
21260             fe = NULL;
21261
21262           if (fe == NULL)
21263             complaint (_("file index out of range"));
21264           else
21265             symbol_set_symtab (sym, fe->symtab);
21266         }
21267
21268       switch (die->tag)
21269         {
21270         case DW_TAG_label:
21271           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21272           if (attr)
21273             {
21274               CORE_ADDR addr;
21275
21276               addr = attr_value_as_address (attr);
21277               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21278               SYMBOL_VALUE_ADDRESS (sym) = addr;
21279             }
21280           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21281           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21282           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21283           dw2_add_symbol_to_list (sym, cu->list_in_scope);
21284           break;
21285         case DW_TAG_subprogram:
21286           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21287              finish_block.  */
21288           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21289           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21290           if ((attr2 && (DW_UNSND (attr2) != 0))
21291               || cu->language == language_ada)
21292             {
21293               /* Subprograms marked external are stored as a global symbol.
21294                  Ada subprograms, whether marked external or not, are always
21295                  stored as a global symbol, because we want to be able to
21296                  access them globally.  For instance, we want to be able
21297                  to break on a nested subprogram without having to
21298                  specify the context.  */
21299               list_to_add = cu->builder->get_global_symbols ();
21300             }
21301           else
21302             {
21303               list_to_add = cu->list_in_scope;
21304             }
21305           break;
21306         case DW_TAG_inlined_subroutine:
21307           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21308              finish_block.  */
21309           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21310           SYMBOL_INLINED (sym) = 1;
21311           list_to_add = cu->list_in_scope;
21312           break;
21313         case DW_TAG_template_value_param:
21314           suppress_add = 1;
21315           /* Fall through.  */
21316         case DW_TAG_constant:
21317         case DW_TAG_variable:
21318         case DW_TAG_member:
21319           /* Compilation with minimal debug info may result in
21320              variables with missing type entries.  Change the
21321              misleading `void' type to something sensible.  */
21322           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21323             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21324
21325           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21326           /* In the case of DW_TAG_member, we should only be called for
21327              static const members.  */
21328           if (die->tag == DW_TAG_member)
21329             {
21330               /* dwarf2_add_field uses die_is_declaration,
21331                  so we do the same.  */
21332               gdb_assert (die_is_declaration (die, cu));
21333               gdb_assert (attr);
21334             }
21335           if (attr)
21336             {
21337               dwarf2_const_value (attr, sym, cu);
21338               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21339               if (!suppress_add)
21340                 {
21341                   if (attr2 && (DW_UNSND (attr2) != 0))
21342                     list_to_add = cu->builder->get_global_symbols ();
21343                   else
21344                     list_to_add = cu->list_in_scope;
21345                 }
21346               break;
21347             }
21348           attr = dwarf2_attr (die, DW_AT_location, cu);
21349           if (attr)
21350             {
21351               var_decode_location (attr, sym, cu);
21352               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21353
21354               /* Fortran explicitly imports any global symbols to the local
21355                  scope by DW_TAG_common_block.  */
21356               if (cu->language == language_fortran && die->parent
21357                   && die->parent->tag == DW_TAG_common_block)
21358                 attr2 = NULL;
21359
21360               if (SYMBOL_CLASS (sym) == LOC_STATIC
21361                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21362                   && !dwarf2_per_objfile->has_section_at_zero)
21363                 {
21364                   /* When a static variable is eliminated by the linker,
21365                      the corresponding debug information is not stripped
21366                      out, but the variable address is set to null;
21367                      do not add such variables into symbol table.  */
21368                 }
21369               else if (attr2 && (DW_UNSND (attr2) != 0))
21370                 {
21371                   /* Workaround gfortran PR debug/40040 - it uses
21372                      DW_AT_location for variables in -fPIC libraries which may
21373                      get overriden by other libraries/executable and get
21374                      a different address.  Resolve it by the minimal symbol
21375                      which may come from inferior's executable using copy
21376                      relocation.  Make this workaround only for gfortran as for
21377                      other compilers GDB cannot guess the minimal symbol
21378                      Fortran mangling kind.  */
21379                   if (cu->language == language_fortran && die->parent
21380                       && die->parent->tag == DW_TAG_module
21381                       && cu->producer
21382                       && startswith (cu->producer, "GNU Fortran"))
21383                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21384
21385                   /* A variable with DW_AT_external is never static,
21386                      but it may be block-scoped.  */
21387                   list_to_add
21388                     = (cu->list_in_scope == cu->builder->get_file_symbols ()
21389                        ? cu->builder->get_global_symbols ()
21390                        : cu->list_in_scope);
21391                 }
21392               else
21393                 list_to_add = cu->list_in_scope;
21394             }
21395           else
21396             {
21397               /* We do not know the address of this symbol.
21398                  If it is an external symbol and we have type information
21399                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21400                  The address of the variable will then be determined from
21401                  the minimal symbol table whenever the variable is
21402                  referenced.  */
21403               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21404
21405               /* Fortran explicitly imports any global symbols to the local
21406                  scope by DW_TAG_common_block.  */
21407               if (cu->language == language_fortran && die->parent
21408                   && die->parent->tag == DW_TAG_common_block)
21409                 {
21410                   /* SYMBOL_CLASS doesn't matter here because
21411                      read_common_block is going to reset it.  */
21412                   if (!suppress_add)
21413                     list_to_add = cu->list_in_scope;
21414                 }
21415               else if (attr2 && (DW_UNSND (attr2) != 0)
21416                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21417                 {
21418                   /* A variable with DW_AT_external is never static, but it
21419                      may be block-scoped.  */
21420                   list_to_add
21421                     = (cu->list_in_scope == cu->builder->get_file_symbols ()
21422                        ? cu->builder->get_global_symbols ()
21423                        : cu->list_in_scope);
21424
21425                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21426                 }
21427               else if (!die_is_declaration (die, cu))
21428                 {
21429                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21430                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21431                   if (!suppress_add)
21432                     list_to_add = cu->list_in_scope;
21433                 }
21434             }
21435           break;
21436         case DW_TAG_formal_parameter:
21437           {
21438             /* If we are inside a function, mark this as an argument.  If
21439                not, we might be looking at an argument to an inlined function
21440                when we do not have enough information to show inlined frames;
21441                pretend it's a local variable in that case so that the user can
21442                still see it.  */
21443             struct context_stack *curr
21444               = cu->builder->get_current_context_stack ();
21445             if (curr != nullptr && curr->name != nullptr)
21446               SYMBOL_IS_ARGUMENT (sym) = 1;
21447             attr = dwarf2_attr (die, DW_AT_location, cu);
21448             if (attr)
21449               {
21450                 var_decode_location (attr, sym, cu);
21451               }
21452             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21453             if (attr)
21454               {
21455                 dwarf2_const_value (attr, sym, cu);
21456               }
21457
21458             list_to_add = cu->list_in_scope;
21459           }
21460           break;
21461         case DW_TAG_unspecified_parameters:
21462           /* From varargs functions; gdb doesn't seem to have any
21463              interest in this information, so just ignore it for now.
21464              (FIXME?) */
21465           break;
21466         case DW_TAG_template_type_param:
21467           suppress_add = 1;
21468           /* Fall through.  */
21469         case DW_TAG_class_type:
21470         case DW_TAG_interface_type:
21471         case DW_TAG_structure_type:
21472         case DW_TAG_union_type:
21473         case DW_TAG_set_type:
21474         case DW_TAG_enumeration_type:
21475           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21476           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21477
21478           {
21479             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21480                really ever be static objects: otherwise, if you try
21481                to, say, break of a class's method and you're in a file
21482                which doesn't mention that class, it won't work unless
21483                the check for all static symbols in lookup_symbol_aux
21484                saves you.  See the OtherFileClass tests in
21485                gdb.c++/namespace.exp.  */
21486
21487             if (!suppress_add)
21488               {
21489                 list_to_add
21490                   = (cu->list_in_scope == cu->builder->get_file_symbols ()
21491                      && cu->language == language_cplus
21492                      ? cu->builder->get_global_symbols ()
21493                      : cu->list_in_scope);
21494
21495                 /* The semantics of C++ state that "struct foo {
21496                    ... }" also defines a typedef for "foo".  */
21497                 if (cu->language == language_cplus
21498                     || cu->language == language_ada
21499                     || cu->language == language_d
21500                     || cu->language == language_rust)
21501                   {
21502                     /* The symbol's name is already allocated along
21503                        with this objfile, so we don't need to
21504                        duplicate it for the type.  */
21505                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21506                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21507                   }
21508               }
21509           }
21510           break;
21511         case DW_TAG_typedef:
21512           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21513           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21514           list_to_add = cu->list_in_scope;
21515           break;
21516         case DW_TAG_base_type:
21517         case DW_TAG_subrange_type:
21518           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21519           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21520           list_to_add = cu->list_in_scope;
21521           break;
21522         case DW_TAG_enumerator:
21523           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21524           if (attr)
21525             {
21526               dwarf2_const_value (attr, sym, cu);
21527             }
21528           {
21529             /* NOTE: carlton/2003-11-10: See comment above in the
21530                DW_TAG_class_type, etc. block.  */
21531
21532             list_to_add
21533               = (cu->list_in_scope == cu->builder->get_file_symbols ()
21534                  && cu->language == language_cplus
21535                  ? cu->builder->get_global_symbols ()
21536                  : cu->list_in_scope);
21537           }
21538           break;
21539         case DW_TAG_imported_declaration:
21540         case DW_TAG_namespace:
21541           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21542           list_to_add = cu->builder->get_global_symbols ();
21543           break;
21544         case DW_TAG_module:
21545           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21546           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21547           list_to_add = cu->builder->get_global_symbols ();
21548           break;
21549         case DW_TAG_common_block:
21550           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21551           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21552           dw2_add_symbol_to_list (sym, cu->list_in_scope);
21553           break;
21554         default:
21555           /* Not a tag we recognize.  Hopefully we aren't processing
21556              trash data, but since we must specifically ignore things
21557              we don't recognize, there is nothing else we should do at
21558              this point.  */
21559           complaint (_("unsupported tag: '%s'"),
21560                      dwarf_tag_name (die->tag));
21561           break;
21562         }
21563
21564       if (suppress_add)
21565         {
21566           sym->hash_next = objfile->template_symbols;
21567           objfile->template_symbols = sym;
21568           list_to_add = NULL;
21569         }
21570
21571       if (list_to_add != NULL)
21572         dw2_add_symbol_to_list (sym, list_to_add);
21573
21574       /* For the benefit of old versions of GCC, check for anonymous
21575          namespaces based on the demangled name.  */
21576       if (!cu->processing_has_namespace_info
21577           && cu->language == language_cplus)
21578         cp_scan_for_anonymous_namespaces (cu->builder.get (), sym, objfile);
21579     }
21580   return (sym);
21581 }
21582
21583 /* Given an attr with a DW_FORM_dataN value in host byte order,
21584    zero-extend it as appropriate for the symbol's type.  The DWARF
21585    standard (v4) is not entirely clear about the meaning of using
21586    DW_FORM_dataN for a constant with a signed type, where the type is
21587    wider than the data.  The conclusion of a discussion on the DWARF
21588    list was that this is unspecified.  We choose to always zero-extend
21589    because that is the interpretation long in use by GCC.  */
21590
21591 static gdb_byte *
21592 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21593                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21594 {
21595   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21596   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21597                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21598   LONGEST l = DW_UNSND (attr);
21599
21600   if (bits < sizeof (*value) * 8)
21601     {
21602       l &= ((LONGEST) 1 << bits) - 1;
21603       *value = l;
21604     }
21605   else if (bits == sizeof (*value) * 8)
21606     *value = l;
21607   else
21608     {
21609       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21610       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21611       return bytes;
21612     }
21613
21614   return NULL;
21615 }
21616
21617 /* Read a constant value from an attribute.  Either set *VALUE, or if
21618    the value does not fit in *VALUE, set *BYTES - either already
21619    allocated on the objfile obstack, or newly allocated on OBSTACK,
21620    or, set *BATON, if we translated the constant to a location
21621    expression.  */
21622
21623 static void
21624 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21625                          const char *name, struct obstack *obstack,
21626                          struct dwarf2_cu *cu,
21627                          LONGEST *value, const gdb_byte **bytes,
21628                          struct dwarf2_locexpr_baton **baton)
21629 {
21630   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21631   struct comp_unit_head *cu_header = &cu->header;
21632   struct dwarf_block *blk;
21633   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21634                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21635
21636   *value = 0;
21637   *bytes = NULL;
21638   *baton = NULL;
21639
21640   switch (attr->form)
21641     {
21642     case DW_FORM_addr:
21643     case DW_FORM_GNU_addr_index:
21644       {
21645         gdb_byte *data;
21646
21647         if (TYPE_LENGTH (type) != cu_header->addr_size)
21648           dwarf2_const_value_length_mismatch_complaint (name,
21649                                                         cu_header->addr_size,
21650                                                         TYPE_LENGTH (type));
21651         /* Symbols of this form are reasonably rare, so we just
21652            piggyback on the existing location code rather than writing
21653            a new implementation of symbol_computed_ops.  */
21654         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21655         (*baton)->per_cu = cu->per_cu;
21656         gdb_assert ((*baton)->per_cu);
21657
21658         (*baton)->size = 2 + cu_header->addr_size;
21659         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21660         (*baton)->data = data;
21661
21662         data[0] = DW_OP_addr;
21663         store_unsigned_integer (&data[1], cu_header->addr_size,
21664                                 byte_order, DW_ADDR (attr));
21665         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21666       }
21667       break;
21668     case DW_FORM_string:
21669     case DW_FORM_strp:
21670     case DW_FORM_GNU_str_index:
21671     case DW_FORM_GNU_strp_alt:
21672       /* DW_STRING is already allocated on the objfile obstack, point
21673          directly to it.  */
21674       *bytes = (const gdb_byte *) DW_STRING (attr);
21675       break;
21676     case DW_FORM_block1:
21677     case DW_FORM_block2:
21678     case DW_FORM_block4:
21679     case DW_FORM_block:
21680     case DW_FORM_exprloc:
21681     case DW_FORM_data16:
21682       blk = DW_BLOCK (attr);
21683       if (TYPE_LENGTH (type) != blk->size)
21684         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21685                                                       TYPE_LENGTH (type));
21686       *bytes = blk->data;
21687       break;
21688
21689       /* The DW_AT_const_value attributes are supposed to carry the
21690          symbol's value "represented as it would be on the target
21691          architecture."  By the time we get here, it's already been
21692          converted to host endianness, so we just need to sign- or
21693          zero-extend it as appropriate.  */
21694     case DW_FORM_data1:
21695       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21696       break;
21697     case DW_FORM_data2:
21698       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21699       break;
21700     case DW_FORM_data4:
21701       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21702       break;
21703     case DW_FORM_data8:
21704       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21705       break;
21706
21707     case DW_FORM_sdata:
21708     case DW_FORM_implicit_const:
21709       *value = DW_SND (attr);
21710       break;
21711
21712     case DW_FORM_udata:
21713       *value = DW_UNSND (attr);
21714       break;
21715
21716     default:
21717       complaint (_("unsupported const value attribute form: '%s'"),
21718                  dwarf_form_name (attr->form));
21719       *value = 0;
21720       break;
21721     }
21722 }
21723
21724
21725 /* Copy constant value from an attribute to a symbol.  */
21726
21727 static void
21728 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21729                     struct dwarf2_cu *cu)
21730 {
21731   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21732   LONGEST value;
21733   const gdb_byte *bytes;
21734   struct dwarf2_locexpr_baton *baton;
21735
21736   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21737                            SYMBOL_PRINT_NAME (sym),
21738                            &objfile->objfile_obstack, cu,
21739                            &value, &bytes, &baton);
21740
21741   if (baton != NULL)
21742     {
21743       SYMBOL_LOCATION_BATON (sym) = baton;
21744       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21745     }
21746   else if (bytes != NULL)
21747      {
21748       SYMBOL_VALUE_BYTES (sym) = bytes;
21749       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21750     }
21751   else
21752     {
21753       SYMBOL_VALUE (sym) = value;
21754       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21755     }
21756 }
21757
21758 /* Return the type of the die in question using its DW_AT_type attribute.  */
21759
21760 static struct type *
21761 die_type (struct die_info *die, struct dwarf2_cu *cu)
21762 {
21763   struct attribute *type_attr;
21764
21765   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21766   if (!type_attr)
21767     {
21768       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21769       /* A missing DW_AT_type represents a void type.  */
21770       return objfile_type (objfile)->builtin_void;
21771     }
21772
21773   return lookup_die_type (die, type_attr, cu);
21774 }
21775
21776 /* True iff CU's producer generates GNAT Ada auxiliary information
21777    that allows to find parallel types through that information instead
21778    of having to do expensive parallel lookups by type name.  */
21779
21780 static int
21781 need_gnat_info (struct dwarf2_cu *cu)
21782 {
21783   /* Assume that the Ada compiler was GNAT, which always produces
21784      the auxiliary information.  */
21785   return (cu->language == language_ada);
21786 }
21787
21788 /* Return the auxiliary type of the die in question using its
21789    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21790    attribute is not present.  */
21791
21792 static struct type *
21793 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21794 {
21795   struct attribute *type_attr;
21796
21797   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21798   if (!type_attr)
21799     return NULL;
21800
21801   return lookup_die_type (die, type_attr, cu);
21802 }
21803
21804 /* If DIE has a descriptive_type attribute, then set the TYPE's
21805    descriptive type accordingly.  */
21806
21807 static void
21808 set_descriptive_type (struct type *type, struct die_info *die,
21809                       struct dwarf2_cu *cu)
21810 {
21811   struct type *descriptive_type = die_descriptive_type (die, cu);
21812
21813   if (descriptive_type)
21814     {
21815       ALLOCATE_GNAT_AUX_TYPE (type);
21816       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21817     }
21818 }
21819
21820 /* Return the containing type of the die in question using its
21821    DW_AT_containing_type attribute.  */
21822
21823 static struct type *
21824 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21825 {
21826   struct attribute *type_attr;
21827   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21828
21829   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21830   if (!type_attr)
21831     error (_("Dwarf Error: Problem turning containing type into gdb type "
21832              "[in module %s]"), objfile_name (objfile));
21833
21834   return lookup_die_type (die, type_attr, cu);
21835 }
21836
21837 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21838
21839 static struct type *
21840 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21841 {
21842   struct dwarf2_per_objfile *dwarf2_per_objfile
21843     = cu->per_cu->dwarf2_per_objfile;
21844   struct objfile *objfile = dwarf2_per_objfile->objfile;
21845   char *saved;
21846
21847   std::string message
21848     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
21849                      objfile_name (objfile),
21850                      sect_offset_str (cu->header.sect_off),
21851                      sect_offset_str (die->sect_off));
21852   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21853                                   message.c_str (), message.length ());
21854
21855   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21856 }
21857
21858 /* Look up the type of DIE in CU using its type attribute ATTR.
21859    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21860    DW_AT_containing_type.
21861    If there is no type substitute an error marker.  */
21862
21863 static struct type *
21864 lookup_die_type (struct die_info *die, const struct attribute *attr,
21865                  struct dwarf2_cu *cu)
21866 {
21867   struct dwarf2_per_objfile *dwarf2_per_objfile
21868     = cu->per_cu->dwarf2_per_objfile;
21869   struct objfile *objfile = dwarf2_per_objfile->objfile;
21870   struct type *this_type;
21871
21872   gdb_assert (attr->name == DW_AT_type
21873               || attr->name == DW_AT_GNAT_descriptive_type
21874               || attr->name == DW_AT_containing_type);
21875
21876   /* First see if we have it cached.  */
21877
21878   if (attr->form == DW_FORM_GNU_ref_alt)
21879     {
21880       struct dwarf2_per_cu_data *per_cu;
21881       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21882
21883       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21884                                                  dwarf2_per_objfile);
21885       this_type = get_die_type_at_offset (sect_off, per_cu);
21886     }
21887   else if (attr_form_is_ref (attr))
21888     {
21889       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21890
21891       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21892     }
21893   else if (attr->form == DW_FORM_ref_sig8)
21894     {
21895       ULONGEST signature = DW_SIGNATURE (attr);
21896
21897       return get_signatured_type (die, signature, cu);
21898     }
21899   else
21900     {
21901       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
21902                    " at %s [in module %s]"),
21903                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21904                  objfile_name (objfile));
21905       return build_error_marker_type (cu, die);
21906     }
21907
21908   /* If not cached we need to read it in.  */
21909
21910   if (this_type == NULL)
21911     {
21912       struct die_info *type_die = NULL;
21913       struct dwarf2_cu *type_cu = cu;
21914
21915       if (attr_form_is_ref (attr))
21916         type_die = follow_die_ref (die, attr, &type_cu);
21917       if (type_die == NULL)
21918         return build_error_marker_type (cu, die);
21919       /* If we find the type now, it's probably because the type came
21920          from an inter-CU reference and the type's CU got expanded before
21921          ours.  */
21922       this_type = read_type_die (type_die, type_cu);
21923     }
21924
21925   /* If we still don't have a type use an error marker.  */
21926
21927   if (this_type == NULL)
21928     return build_error_marker_type (cu, die);
21929
21930   return this_type;
21931 }
21932
21933 /* Return the type in DIE, CU.
21934    Returns NULL for invalid types.
21935
21936    This first does a lookup in die_type_hash,
21937    and only reads the die in if necessary.
21938
21939    NOTE: This can be called when reading in partial or full symbols.  */
21940
21941 static struct type *
21942 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21943 {
21944   struct type *this_type;
21945
21946   this_type = get_die_type (die, cu);
21947   if (this_type)
21948     return this_type;
21949
21950   return read_type_die_1 (die, cu);
21951 }
21952
21953 /* Read the type in DIE, CU.
21954    Returns NULL for invalid types.  */
21955
21956 static struct type *
21957 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21958 {
21959   struct type *this_type = NULL;
21960
21961   switch (die->tag)
21962     {
21963     case DW_TAG_class_type:
21964     case DW_TAG_interface_type:
21965     case DW_TAG_structure_type:
21966     case DW_TAG_union_type:
21967       this_type = read_structure_type (die, cu);
21968       break;
21969     case DW_TAG_enumeration_type:
21970       this_type = read_enumeration_type (die, cu);
21971       break;
21972     case DW_TAG_subprogram:
21973     case DW_TAG_subroutine_type:
21974     case DW_TAG_inlined_subroutine:
21975       this_type = read_subroutine_type (die, cu);
21976       break;
21977     case DW_TAG_array_type:
21978       this_type = read_array_type (die, cu);
21979       break;
21980     case DW_TAG_set_type:
21981       this_type = read_set_type (die, cu);
21982       break;
21983     case DW_TAG_pointer_type:
21984       this_type = read_tag_pointer_type (die, cu);
21985       break;
21986     case DW_TAG_ptr_to_member_type:
21987       this_type = read_tag_ptr_to_member_type (die, cu);
21988       break;
21989     case DW_TAG_reference_type:
21990       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21991       break;
21992     case DW_TAG_rvalue_reference_type:
21993       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21994       break;
21995     case DW_TAG_const_type:
21996       this_type = read_tag_const_type (die, cu);
21997       break;
21998     case DW_TAG_volatile_type:
21999       this_type = read_tag_volatile_type (die, cu);
22000       break;
22001     case DW_TAG_restrict_type:
22002       this_type = read_tag_restrict_type (die, cu);
22003       break;
22004     case DW_TAG_string_type:
22005       this_type = read_tag_string_type (die, cu);
22006       break;
22007     case DW_TAG_typedef:
22008       this_type = read_typedef (die, cu);
22009       break;
22010     case DW_TAG_subrange_type:
22011       this_type = read_subrange_type (die, cu);
22012       break;
22013     case DW_TAG_base_type:
22014       this_type = read_base_type (die, cu);
22015       break;
22016     case DW_TAG_unspecified_type:
22017       this_type = read_unspecified_type (die, cu);
22018       break;
22019     case DW_TAG_namespace:
22020       this_type = read_namespace_type (die, cu);
22021       break;
22022     case DW_TAG_module:
22023       this_type = read_module_type (die, cu);
22024       break;
22025     case DW_TAG_atomic_type:
22026       this_type = read_tag_atomic_type (die, cu);
22027       break;
22028     default:
22029       complaint (_("unexpected tag in read_type_die: '%s'"),
22030                  dwarf_tag_name (die->tag));
22031       break;
22032     }
22033
22034   return this_type;
22035 }
22036
22037 /* See if we can figure out if the class lives in a namespace.  We do
22038    this by looking for a member function; its demangled name will
22039    contain namespace info, if there is any.
22040    Return the computed name or NULL.
22041    Space for the result is allocated on the objfile's obstack.
22042    This is the full-die version of guess_partial_die_structure_name.
22043    In this case we know DIE has no useful parent.  */
22044
22045 static char *
22046 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22047 {
22048   struct die_info *spec_die;
22049   struct dwarf2_cu *spec_cu;
22050   struct die_info *child;
22051   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22052
22053   spec_cu = cu;
22054   spec_die = die_specification (die, &spec_cu);
22055   if (spec_die != NULL)
22056     {
22057       die = spec_die;
22058       cu = spec_cu;
22059     }
22060
22061   for (child = die->child;
22062        child != NULL;
22063        child = child->sibling)
22064     {
22065       if (child->tag == DW_TAG_subprogram)
22066         {
22067           const char *linkage_name = dw2_linkage_name (child, cu);
22068
22069           if (linkage_name != NULL)
22070             {
22071               char *actual_name
22072                 = language_class_name_from_physname (cu->language_defn,
22073                                                      linkage_name);
22074               char *name = NULL;
22075
22076               if (actual_name != NULL)
22077                 {
22078                   const char *die_name = dwarf2_name (die, cu);
22079
22080                   if (die_name != NULL
22081                       && strcmp (die_name, actual_name) != 0)
22082                     {
22083                       /* Strip off the class name from the full name.
22084                          We want the prefix.  */
22085                       int die_name_len = strlen (die_name);
22086                       int actual_name_len = strlen (actual_name);
22087
22088                       /* Test for '::' as a sanity check.  */
22089                       if (actual_name_len > die_name_len + 2
22090                           && actual_name[actual_name_len
22091                                          - die_name_len - 1] == ':')
22092                         name = (char *) obstack_copy0 (
22093                           &objfile->per_bfd->storage_obstack,
22094                           actual_name, actual_name_len - die_name_len - 2);
22095                     }
22096                 }
22097               xfree (actual_name);
22098               return name;
22099             }
22100         }
22101     }
22102
22103   return NULL;
22104 }
22105
22106 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22107    prefix part in such case.  See
22108    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22109
22110 static const char *
22111 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22112 {
22113   struct attribute *attr;
22114   const char *base;
22115
22116   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22117       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22118     return NULL;
22119
22120   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22121     return NULL;
22122
22123   attr = dw2_linkage_name_attr (die, cu);
22124   if (attr == NULL || DW_STRING (attr) == NULL)
22125     return NULL;
22126
22127   /* dwarf2_name had to be already called.  */
22128   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22129
22130   /* Strip the base name, keep any leading namespaces/classes.  */
22131   base = strrchr (DW_STRING (attr), ':');
22132   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22133     return "";
22134
22135   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22136   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22137                                  DW_STRING (attr),
22138                                  &base[-1] - DW_STRING (attr));
22139 }
22140
22141 /* Return the name of the namespace/class that DIE is defined within,
22142    or "" if we can't tell.  The caller should not xfree the result.
22143
22144    For example, if we're within the method foo() in the following
22145    code:
22146
22147    namespace N {
22148      class C {
22149        void foo () {
22150        }
22151      };
22152    }
22153
22154    then determine_prefix on foo's die will return "N::C".  */
22155
22156 static const char *
22157 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22158 {
22159   struct dwarf2_per_objfile *dwarf2_per_objfile
22160     = cu->per_cu->dwarf2_per_objfile;
22161   struct die_info *parent, *spec_die;
22162   struct dwarf2_cu *spec_cu;
22163   struct type *parent_type;
22164   const char *retval;
22165
22166   if (cu->language != language_cplus
22167       && cu->language != language_fortran && cu->language != language_d
22168       && cu->language != language_rust)
22169     return "";
22170
22171   retval = anonymous_struct_prefix (die, cu);
22172   if (retval)
22173     return retval;
22174
22175   /* We have to be careful in the presence of DW_AT_specification.
22176      For example, with GCC 3.4, given the code
22177
22178      namespace N {
22179        void foo() {
22180          // Definition of N::foo.
22181        }
22182      }
22183
22184      then we'll have a tree of DIEs like this:
22185
22186      1: DW_TAG_compile_unit
22187        2: DW_TAG_namespace        // N
22188          3: DW_TAG_subprogram     // declaration of N::foo
22189        4: DW_TAG_subprogram       // definition of N::foo
22190             DW_AT_specification   // refers to die #3
22191
22192      Thus, when processing die #4, we have to pretend that we're in
22193      the context of its DW_AT_specification, namely the contex of die
22194      #3.  */
22195   spec_cu = cu;
22196   spec_die = die_specification (die, &spec_cu);
22197   if (spec_die == NULL)
22198     parent = die->parent;
22199   else
22200     {
22201       parent = spec_die->parent;
22202       cu = spec_cu;
22203     }
22204
22205   if (parent == NULL)
22206     return "";
22207   else if (parent->building_fullname)
22208     {
22209       const char *name;
22210       const char *parent_name;
22211
22212       /* It has been seen on RealView 2.2 built binaries,
22213          DW_TAG_template_type_param types actually _defined_ as
22214          children of the parent class:
22215
22216          enum E {};
22217          template class <class Enum> Class{};
22218          Class<enum E> class_e;
22219
22220          1: DW_TAG_class_type (Class)
22221            2: DW_TAG_enumeration_type (E)
22222              3: DW_TAG_enumerator (enum1:0)
22223              3: DW_TAG_enumerator (enum2:1)
22224              ...
22225            2: DW_TAG_template_type_param
22226               DW_AT_type  DW_FORM_ref_udata (E)
22227
22228          Besides being broken debug info, it can put GDB into an
22229          infinite loop.  Consider:
22230
22231          When we're building the full name for Class<E>, we'll start
22232          at Class, and go look over its template type parameters,
22233          finding E.  We'll then try to build the full name of E, and
22234          reach here.  We're now trying to build the full name of E,
22235          and look over the parent DIE for containing scope.  In the
22236          broken case, if we followed the parent DIE of E, we'd again
22237          find Class, and once again go look at its template type
22238          arguments, etc., etc.  Simply don't consider such parent die
22239          as source-level parent of this die (it can't be, the language
22240          doesn't allow it), and break the loop here.  */
22241       name = dwarf2_name (die, cu);
22242       parent_name = dwarf2_name (parent, cu);
22243       complaint (_("template param type '%s' defined within parent '%s'"),
22244                  name ? name : "<unknown>",
22245                  parent_name ? parent_name : "<unknown>");
22246       return "";
22247     }
22248   else
22249     switch (parent->tag)
22250       {
22251       case DW_TAG_namespace:
22252         parent_type = read_type_die (parent, cu);
22253         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22254            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22255            Work around this problem here.  */
22256         if (cu->language == language_cplus
22257             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22258           return "";
22259         /* We give a name to even anonymous namespaces.  */
22260         return TYPE_NAME (parent_type);
22261       case DW_TAG_class_type:
22262       case DW_TAG_interface_type:
22263       case DW_TAG_structure_type:
22264       case DW_TAG_union_type:
22265       case DW_TAG_module:
22266         parent_type = read_type_die (parent, cu);
22267         if (TYPE_NAME (parent_type) != NULL)
22268           return TYPE_NAME (parent_type);
22269         else
22270           /* An anonymous structure is only allowed non-static data
22271              members; no typedefs, no member functions, et cetera.
22272              So it does not need a prefix.  */
22273           return "";
22274       case DW_TAG_compile_unit:
22275       case DW_TAG_partial_unit:
22276         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22277         if (cu->language == language_cplus
22278             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22279             && die->child != NULL
22280             && (die->tag == DW_TAG_class_type
22281                 || die->tag == DW_TAG_structure_type
22282                 || die->tag == DW_TAG_union_type))
22283           {
22284             char *name = guess_full_die_structure_name (die, cu);
22285             if (name != NULL)
22286               return name;
22287           }
22288         return "";
22289       case DW_TAG_enumeration_type:
22290         parent_type = read_type_die (parent, cu);
22291         if (TYPE_DECLARED_CLASS (parent_type))
22292           {
22293             if (TYPE_NAME (parent_type) != NULL)
22294               return TYPE_NAME (parent_type);
22295             return "";
22296           }
22297         /* Fall through.  */
22298       default:
22299         return determine_prefix (parent, cu);
22300       }
22301 }
22302
22303 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22304    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22305    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22306    an obconcat, otherwise allocate storage for the result.  The CU argument is
22307    used to determine the language and hence, the appropriate separator.  */
22308
22309 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22310
22311 static char *
22312 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22313                  int physname, struct dwarf2_cu *cu)
22314 {
22315   const char *lead = "";
22316   const char *sep;
22317
22318   if (suffix == NULL || suffix[0] == '\0'
22319       || prefix == NULL || prefix[0] == '\0')
22320     sep = "";
22321   else if (cu->language == language_d)
22322     {
22323       /* For D, the 'main' function could be defined in any module, but it
22324          should never be prefixed.  */
22325       if (strcmp (suffix, "D main") == 0)
22326         {
22327           prefix = "";
22328           sep = "";
22329         }
22330       else
22331         sep = ".";
22332     }
22333   else if (cu->language == language_fortran && physname)
22334     {
22335       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22336          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22337
22338       lead = "__";
22339       sep = "_MOD_";
22340     }
22341   else
22342     sep = "::";
22343
22344   if (prefix == NULL)
22345     prefix = "";
22346   if (suffix == NULL)
22347     suffix = "";
22348
22349   if (obs == NULL)
22350     {
22351       char *retval
22352         = ((char *)
22353            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22354
22355       strcpy (retval, lead);
22356       strcat (retval, prefix);
22357       strcat (retval, sep);
22358       strcat (retval, suffix);
22359       return retval;
22360     }
22361   else
22362     {
22363       /* We have an obstack.  */
22364       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22365     }
22366 }
22367
22368 /* Return sibling of die, NULL if no sibling.  */
22369
22370 static struct die_info *
22371 sibling_die (struct die_info *die)
22372 {
22373   return die->sibling;
22374 }
22375
22376 /* Get name of a die, return NULL if not found.  */
22377
22378 static const char *
22379 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22380                           struct obstack *obstack)
22381 {
22382   if (name && cu->language == language_cplus)
22383     {
22384       std::string canon_name = cp_canonicalize_string (name);
22385
22386       if (!canon_name.empty ())
22387         {
22388           if (canon_name != name)
22389             name = (const char *) obstack_copy0 (obstack,
22390                                                  canon_name.c_str (),
22391                                                  canon_name.length ());
22392         }
22393     }
22394
22395   return name;
22396 }
22397
22398 /* Get name of a die, return NULL if not found.
22399    Anonymous namespaces are converted to their magic string.  */
22400
22401 static const char *
22402 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22403 {
22404   struct attribute *attr;
22405   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22406
22407   attr = dwarf2_attr (die, DW_AT_name, cu);
22408   if ((!attr || !DW_STRING (attr))
22409       && die->tag != DW_TAG_namespace
22410       && die->tag != DW_TAG_class_type
22411       && die->tag != DW_TAG_interface_type
22412       && die->tag != DW_TAG_structure_type
22413       && die->tag != DW_TAG_union_type)
22414     return NULL;
22415
22416   switch (die->tag)
22417     {
22418     case DW_TAG_compile_unit:
22419     case DW_TAG_partial_unit:
22420       /* Compilation units have a DW_AT_name that is a filename, not
22421          a source language identifier.  */
22422     case DW_TAG_enumeration_type:
22423     case DW_TAG_enumerator:
22424       /* These tags always have simple identifiers already; no need
22425          to canonicalize them.  */
22426       return DW_STRING (attr);
22427
22428     case DW_TAG_namespace:
22429       if (attr != NULL && DW_STRING (attr) != NULL)
22430         return DW_STRING (attr);
22431       return CP_ANONYMOUS_NAMESPACE_STR;
22432
22433     case DW_TAG_class_type:
22434     case DW_TAG_interface_type:
22435     case DW_TAG_structure_type:
22436     case DW_TAG_union_type:
22437       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22438          structures or unions.  These were of the form "._%d" in GCC 4.1,
22439          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22440          and GCC 4.4.  We work around this problem by ignoring these.  */
22441       if (attr && DW_STRING (attr)
22442           && (startswith (DW_STRING (attr), "._")
22443               || startswith (DW_STRING (attr), "<anonymous")))
22444         return NULL;
22445
22446       /* GCC might emit a nameless typedef that has a linkage name.  See
22447          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22448       if (!attr || DW_STRING (attr) == NULL)
22449         {
22450           char *demangled = NULL;
22451
22452           attr = dw2_linkage_name_attr (die, cu);
22453           if (attr == NULL || DW_STRING (attr) == NULL)
22454             return NULL;
22455
22456           /* Avoid demangling DW_STRING (attr) the second time on a second
22457              call for the same DIE.  */
22458           if (!DW_STRING_IS_CANONICAL (attr))
22459             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22460
22461           if (demangled)
22462             {
22463               const char *base;
22464
22465               /* FIXME: we already did this for the partial symbol... */
22466               DW_STRING (attr)
22467                 = ((const char *)
22468                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22469                                   demangled, strlen (demangled)));
22470               DW_STRING_IS_CANONICAL (attr) = 1;
22471               xfree (demangled);
22472
22473               /* Strip any leading namespaces/classes, keep only the base name.
22474                  DW_AT_name for named DIEs does not contain the prefixes.  */
22475               base = strrchr (DW_STRING (attr), ':');
22476               if (base && base > DW_STRING (attr) && base[-1] == ':')
22477                 return &base[1];
22478               else
22479                 return DW_STRING (attr);
22480             }
22481         }
22482       break;
22483
22484     default:
22485       break;
22486     }
22487
22488   if (!DW_STRING_IS_CANONICAL (attr))
22489     {
22490       DW_STRING (attr)
22491         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22492                                     &objfile->per_bfd->storage_obstack);
22493       DW_STRING_IS_CANONICAL (attr) = 1;
22494     }
22495   return DW_STRING (attr);
22496 }
22497
22498 /* Return the die that this die in an extension of, or NULL if there
22499    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22500    containing the return value on output.  */
22501
22502 static struct die_info *
22503 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22504 {
22505   struct attribute *attr;
22506
22507   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22508   if (attr == NULL)
22509     return NULL;
22510
22511   return follow_die_ref (die, attr, ext_cu);
22512 }
22513
22514 /* Convert a DIE tag into its string name.  */
22515
22516 static const char *
22517 dwarf_tag_name (unsigned tag)
22518 {
22519   const char *name = get_DW_TAG_name (tag);
22520
22521   if (name == NULL)
22522     return "DW_TAG_<unknown>";
22523
22524   return name;
22525 }
22526
22527 /* Convert a DWARF attribute code into its string name.  */
22528
22529 static const char *
22530 dwarf_attr_name (unsigned attr)
22531 {
22532   const char *name;
22533
22534 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22535   if (attr == DW_AT_MIPS_fde)
22536     return "DW_AT_MIPS_fde";
22537 #else
22538   if (attr == DW_AT_HP_block_index)
22539     return "DW_AT_HP_block_index";
22540 #endif
22541
22542   name = get_DW_AT_name (attr);
22543
22544   if (name == NULL)
22545     return "DW_AT_<unknown>";
22546
22547   return name;
22548 }
22549
22550 /* Convert a DWARF value form code into its string name.  */
22551
22552 static const char *
22553 dwarf_form_name (unsigned form)
22554 {
22555   const char *name = get_DW_FORM_name (form);
22556
22557   if (name == NULL)
22558     return "DW_FORM_<unknown>";
22559
22560   return name;
22561 }
22562
22563 static const char *
22564 dwarf_bool_name (unsigned mybool)
22565 {
22566   if (mybool)
22567     return "TRUE";
22568   else
22569     return "FALSE";
22570 }
22571
22572 /* Convert a DWARF type code into its string name.  */
22573
22574 static const char *
22575 dwarf_type_encoding_name (unsigned enc)
22576 {
22577   const char *name = get_DW_ATE_name (enc);
22578
22579   if (name == NULL)
22580     return "DW_ATE_<unknown>";
22581
22582   return name;
22583 }
22584
22585 static void
22586 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22587 {
22588   unsigned int i;
22589
22590   print_spaces (indent, f);
22591   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22592                       dwarf_tag_name (die->tag), die->abbrev,
22593                       sect_offset_str (die->sect_off));
22594
22595   if (die->parent != NULL)
22596     {
22597       print_spaces (indent, f);
22598       fprintf_unfiltered (f, "  parent at offset: %s\n",
22599                           sect_offset_str (die->parent->sect_off));
22600     }
22601
22602   print_spaces (indent, f);
22603   fprintf_unfiltered (f, "  has children: %s\n",
22604            dwarf_bool_name (die->child != NULL));
22605
22606   print_spaces (indent, f);
22607   fprintf_unfiltered (f, "  attributes:\n");
22608
22609   for (i = 0; i < die->num_attrs; ++i)
22610     {
22611       print_spaces (indent, f);
22612       fprintf_unfiltered (f, "    %s (%s) ",
22613                dwarf_attr_name (die->attrs[i].name),
22614                dwarf_form_name (die->attrs[i].form));
22615
22616       switch (die->attrs[i].form)
22617         {
22618         case DW_FORM_addr:
22619         case DW_FORM_GNU_addr_index:
22620           fprintf_unfiltered (f, "address: ");
22621           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22622           break;
22623         case DW_FORM_block2:
22624         case DW_FORM_block4:
22625         case DW_FORM_block:
22626         case DW_FORM_block1:
22627           fprintf_unfiltered (f, "block: size %s",
22628                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22629           break;
22630         case DW_FORM_exprloc:
22631           fprintf_unfiltered (f, "expression: size %s",
22632                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22633           break;
22634         case DW_FORM_data16:
22635           fprintf_unfiltered (f, "constant of 16 bytes");
22636           break;
22637         case DW_FORM_ref_addr:
22638           fprintf_unfiltered (f, "ref address: ");
22639           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22640           break;
22641         case DW_FORM_GNU_ref_alt:
22642           fprintf_unfiltered (f, "alt ref address: ");
22643           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22644           break;
22645         case DW_FORM_ref1:
22646         case DW_FORM_ref2:
22647         case DW_FORM_ref4:
22648         case DW_FORM_ref8:
22649         case DW_FORM_ref_udata:
22650           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22651                               (long) (DW_UNSND (&die->attrs[i])));
22652           break;
22653         case DW_FORM_data1:
22654         case DW_FORM_data2:
22655         case DW_FORM_data4:
22656         case DW_FORM_data8:
22657         case DW_FORM_udata:
22658         case DW_FORM_sdata:
22659           fprintf_unfiltered (f, "constant: %s",
22660                               pulongest (DW_UNSND (&die->attrs[i])));
22661           break;
22662         case DW_FORM_sec_offset:
22663           fprintf_unfiltered (f, "section offset: %s",
22664                               pulongest (DW_UNSND (&die->attrs[i])));
22665           break;
22666         case DW_FORM_ref_sig8:
22667           fprintf_unfiltered (f, "signature: %s",
22668                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22669           break;
22670         case DW_FORM_string:
22671         case DW_FORM_strp:
22672         case DW_FORM_line_strp:
22673         case DW_FORM_GNU_str_index:
22674         case DW_FORM_GNU_strp_alt:
22675           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22676                    DW_STRING (&die->attrs[i])
22677                    ? DW_STRING (&die->attrs[i]) : "",
22678                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22679           break;
22680         case DW_FORM_flag:
22681           if (DW_UNSND (&die->attrs[i]))
22682             fprintf_unfiltered (f, "flag: TRUE");
22683           else
22684             fprintf_unfiltered (f, "flag: FALSE");
22685           break;
22686         case DW_FORM_flag_present:
22687           fprintf_unfiltered (f, "flag: TRUE");
22688           break;
22689         case DW_FORM_indirect:
22690           /* The reader will have reduced the indirect form to
22691              the "base form" so this form should not occur.  */
22692           fprintf_unfiltered (f, 
22693                               "unexpected attribute form: DW_FORM_indirect");
22694           break;
22695         case DW_FORM_implicit_const:
22696           fprintf_unfiltered (f, "constant: %s",
22697                               plongest (DW_SND (&die->attrs[i])));
22698           break;
22699         default:
22700           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22701                    die->attrs[i].form);
22702           break;
22703         }
22704       fprintf_unfiltered (f, "\n");
22705     }
22706 }
22707
22708 static void
22709 dump_die_for_error (struct die_info *die)
22710 {
22711   dump_die_shallow (gdb_stderr, 0, die);
22712 }
22713
22714 static void
22715 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22716 {
22717   int indent = level * 4;
22718
22719   gdb_assert (die != NULL);
22720
22721   if (level >= max_level)
22722     return;
22723
22724   dump_die_shallow (f, indent, die);
22725
22726   if (die->child != NULL)
22727     {
22728       print_spaces (indent, f);
22729       fprintf_unfiltered (f, "  Children:");
22730       if (level + 1 < max_level)
22731         {
22732           fprintf_unfiltered (f, "\n");
22733           dump_die_1 (f, level + 1, max_level, die->child);
22734         }
22735       else
22736         {
22737           fprintf_unfiltered (f,
22738                               " [not printed, max nesting level reached]\n");
22739         }
22740     }
22741
22742   if (die->sibling != NULL && level > 0)
22743     {
22744       dump_die_1 (f, level, max_level, die->sibling);
22745     }
22746 }
22747
22748 /* This is called from the pdie macro in gdbinit.in.
22749    It's not static so gcc will keep a copy callable from gdb.  */
22750
22751 void
22752 dump_die (struct die_info *die, int max_level)
22753 {
22754   dump_die_1 (gdb_stdlog, 0, max_level, die);
22755 }
22756
22757 static void
22758 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22759 {
22760   void **slot;
22761
22762   slot = htab_find_slot_with_hash (cu->die_hash, die,
22763                                    to_underlying (die->sect_off),
22764                                    INSERT);
22765
22766   *slot = die;
22767 }
22768
22769 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22770    required kind.  */
22771
22772 static sect_offset
22773 dwarf2_get_ref_die_offset (const struct attribute *attr)
22774 {
22775   if (attr_form_is_ref (attr))
22776     return (sect_offset) DW_UNSND (attr);
22777
22778   complaint (_("unsupported die ref attribute form: '%s'"),
22779              dwarf_form_name (attr->form));
22780   return {};
22781 }
22782
22783 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22784  * the value held by the attribute is not constant.  */
22785
22786 static LONGEST
22787 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22788 {
22789   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22790     return DW_SND (attr);
22791   else if (attr->form == DW_FORM_udata
22792            || attr->form == DW_FORM_data1
22793            || attr->form == DW_FORM_data2
22794            || attr->form == DW_FORM_data4
22795            || attr->form == DW_FORM_data8)
22796     return DW_UNSND (attr);
22797   else
22798     {
22799       /* For DW_FORM_data16 see attr_form_is_constant.  */
22800       complaint (_("Attribute value is not a constant (%s)"),
22801                  dwarf_form_name (attr->form));
22802       return default_value;
22803     }
22804 }
22805
22806 /* Follow reference or signature attribute ATTR of SRC_DIE.
22807    On entry *REF_CU is the CU of SRC_DIE.
22808    On exit *REF_CU is the CU of the result.  */
22809
22810 static struct die_info *
22811 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22812                        struct dwarf2_cu **ref_cu)
22813 {
22814   struct die_info *die;
22815
22816   if (attr_form_is_ref (attr))
22817     die = follow_die_ref (src_die, attr, ref_cu);
22818   else if (attr->form == DW_FORM_ref_sig8)
22819     die = follow_die_sig (src_die, attr, ref_cu);
22820   else
22821     {
22822       dump_die_for_error (src_die);
22823       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22824              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22825     }
22826
22827   return die;
22828 }
22829
22830 /* Follow reference OFFSET.
22831    On entry *REF_CU is the CU of the source die referencing OFFSET.
22832    On exit *REF_CU is the CU of the result.
22833    Returns NULL if OFFSET is invalid.  */
22834
22835 static struct die_info *
22836 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22837                    struct dwarf2_cu **ref_cu)
22838 {
22839   struct die_info temp_die;
22840   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22841   struct dwarf2_per_objfile *dwarf2_per_objfile
22842     = cu->per_cu->dwarf2_per_objfile;
22843
22844   gdb_assert (cu->per_cu != NULL);
22845
22846   target_cu = cu;
22847
22848   if (cu->per_cu->is_debug_types)
22849     {
22850       /* .debug_types CUs cannot reference anything outside their CU.
22851          If they need to, they have to reference a signatured type via
22852          DW_FORM_ref_sig8.  */
22853       if (!offset_in_cu_p (&cu->header, sect_off))
22854         return NULL;
22855     }
22856   else if (offset_in_dwz != cu->per_cu->is_dwz
22857            || !offset_in_cu_p (&cu->header, sect_off))
22858     {
22859       struct dwarf2_per_cu_data *per_cu;
22860
22861       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22862                                                  dwarf2_per_objfile);
22863
22864       /* If necessary, add it to the queue and load its DIEs.  */
22865       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22866         load_full_comp_unit (per_cu, false, cu->language);
22867
22868       target_cu = per_cu->cu;
22869     }
22870   else if (cu->dies == NULL)
22871     {
22872       /* We're loading full DIEs during partial symbol reading.  */
22873       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22874       load_full_comp_unit (cu->per_cu, false, language_minimal);
22875     }
22876
22877   *ref_cu = target_cu;
22878   temp_die.sect_off = sect_off;
22879   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22880                                                   &temp_die,
22881                                                   to_underlying (sect_off));
22882 }
22883
22884 /* Follow reference attribute ATTR of SRC_DIE.
22885    On entry *REF_CU is the CU of SRC_DIE.
22886    On exit *REF_CU is the CU of the result.  */
22887
22888 static struct die_info *
22889 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22890                 struct dwarf2_cu **ref_cu)
22891 {
22892   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22893   struct dwarf2_cu *cu = *ref_cu;
22894   struct die_info *die;
22895
22896   die = follow_die_offset (sect_off,
22897                            (attr->form == DW_FORM_GNU_ref_alt
22898                             || cu->per_cu->is_dwz),
22899                            ref_cu);
22900   if (!die)
22901     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22902            "at %s [in module %s]"),
22903            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22904            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22905
22906   return die;
22907 }
22908
22909 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22910    Returned value is intended for DW_OP_call*.  Returned
22911    dwarf2_locexpr_baton->data has lifetime of
22912    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22913
22914 struct dwarf2_locexpr_baton
22915 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22916                                struct dwarf2_per_cu_data *per_cu,
22917                                CORE_ADDR (*get_frame_pc) (void *baton),
22918                                void *baton)
22919 {
22920   struct dwarf2_cu *cu;
22921   struct die_info *die;
22922   struct attribute *attr;
22923   struct dwarf2_locexpr_baton retval;
22924   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22925   struct objfile *objfile = dwarf2_per_objfile->objfile;
22926
22927   if (per_cu->cu == NULL)
22928     load_cu (per_cu, false);
22929   cu = per_cu->cu;
22930   if (cu == NULL)
22931     {
22932       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22933          Instead just throw an error, not much else we can do.  */
22934       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22935              sect_offset_str (sect_off), objfile_name (objfile));
22936     }
22937
22938   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22939   if (!die)
22940     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22941            sect_offset_str (sect_off), objfile_name (objfile));
22942
22943   attr = dwarf2_attr (die, DW_AT_location, cu);
22944   if (!attr)
22945     {
22946       /* DWARF: "If there is no such attribute, then there is no effect.".
22947          DATA is ignored if SIZE is 0.  */
22948
22949       retval.data = NULL;
22950       retval.size = 0;
22951     }
22952   else if (attr_form_is_section_offset (attr))
22953     {
22954       struct dwarf2_loclist_baton loclist_baton;
22955       CORE_ADDR pc = (*get_frame_pc) (baton);
22956       size_t size;
22957
22958       fill_in_loclist_baton (cu, &loclist_baton, attr);
22959
22960       retval.data = dwarf2_find_location_expression (&loclist_baton,
22961                                                      &size, pc);
22962       retval.size = size;
22963     }
22964   else
22965     {
22966       if (!attr_form_is_block (attr))
22967         error (_("Dwarf Error: DIE at %s referenced in module %s "
22968                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22969                sect_offset_str (sect_off), objfile_name (objfile));
22970
22971       retval.data = DW_BLOCK (attr)->data;
22972       retval.size = DW_BLOCK (attr)->size;
22973     }
22974   retval.per_cu = cu->per_cu;
22975
22976   age_cached_comp_units (dwarf2_per_objfile);
22977
22978   return retval;
22979 }
22980
22981 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
22982    offset.  */
22983
22984 struct dwarf2_locexpr_baton
22985 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
22986                              struct dwarf2_per_cu_data *per_cu,
22987                              CORE_ADDR (*get_frame_pc) (void *baton),
22988                              void *baton)
22989 {
22990   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
22991
22992   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
22993 }
22994
22995 /* Write a constant of a given type as target-ordered bytes into
22996    OBSTACK.  */
22997
22998 static const gdb_byte *
22999 write_constant_as_bytes (struct obstack *obstack,
23000                          enum bfd_endian byte_order,
23001                          struct type *type,
23002                          ULONGEST value,
23003                          LONGEST *len)
23004 {
23005   gdb_byte *result;
23006
23007   *len = TYPE_LENGTH (type);
23008   result = (gdb_byte *) obstack_alloc (obstack, *len);
23009   store_unsigned_integer (result, *len, byte_order, value);
23010
23011   return result;
23012 }
23013
23014 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23015    pointer to the constant bytes and set LEN to the length of the
23016    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23017    does not have a DW_AT_const_value, return NULL.  */
23018
23019 const gdb_byte *
23020 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23021                              struct dwarf2_per_cu_data *per_cu,
23022                              struct obstack *obstack,
23023                              LONGEST *len)
23024 {
23025   struct dwarf2_cu *cu;
23026   struct die_info *die;
23027   struct attribute *attr;
23028   const gdb_byte *result = NULL;
23029   struct type *type;
23030   LONGEST value;
23031   enum bfd_endian byte_order;
23032   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23033
23034   if (per_cu->cu == NULL)
23035     load_cu (per_cu, false);
23036   cu = per_cu->cu;
23037   if (cu == NULL)
23038     {
23039       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23040          Instead just throw an error, not much else we can do.  */
23041       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23042              sect_offset_str (sect_off), objfile_name (objfile));
23043     }
23044
23045   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23046   if (!die)
23047     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23048            sect_offset_str (sect_off), objfile_name (objfile));
23049
23050   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23051   if (attr == NULL)
23052     return NULL;
23053
23054   byte_order = (bfd_big_endian (objfile->obfd)
23055                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23056
23057   switch (attr->form)
23058     {
23059     case DW_FORM_addr:
23060     case DW_FORM_GNU_addr_index:
23061       {
23062         gdb_byte *tem;
23063
23064         *len = cu->header.addr_size;
23065         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23066         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23067         result = tem;
23068       }
23069       break;
23070     case DW_FORM_string:
23071     case DW_FORM_strp:
23072     case DW_FORM_GNU_str_index:
23073     case DW_FORM_GNU_strp_alt:
23074       /* DW_STRING is already allocated on the objfile obstack, point
23075          directly to it.  */
23076       result = (const gdb_byte *) DW_STRING (attr);
23077       *len = strlen (DW_STRING (attr));
23078       break;
23079     case DW_FORM_block1:
23080     case DW_FORM_block2:
23081     case DW_FORM_block4:
23082     case DW_FORM_block:
23083     case DW_FORM_exprloc:
23084     case DW_FORM_data16:
23085       result = DW_BLOCK (attr)->data;
23086       *len = DW_BLOCK (attr)->size;
23087       break;
23088
23089       /* The DW_AT_const_value attributes are supposed to carry the
23090          symbol's value "represented as it would be on the target
23091          architecture."  By the time we get here, it's already been
23092          converted to host endianness, so we just need to sign- or
23093          zero-extend it as appropriate.  */
23094     case DW_FORM_data1:
23095       type = die_type (die, cu);
23096       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23097       if (result == NULL)
23098         result = write_constant_as_bytes (obstack, byte_order,
23099                                           type, value, len);
23100       break;
23101     case DW_FORM_data2:
23102       type = die_type (die, cu);
23103       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23104       if (result == NULL)
23105         result = write_constant_as_bytes (obstack, byte_order,
23106                                           type, value, len);
23107       break;
23108     case DW_FORM_data4:
23109       type = die_type (die, cu);
23110       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23111       if (result == NULL)
23112         result = write_constant_as_bytes (obstack, byte_order,
23113                                           type, value, len);
23114       break;
23115     case DW_FORM_data8:
23116       type = die_type (die, cu);
23117       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23118       if (result == NULL)
23119         result = write_constant_as_bytes (obstack, byte_order,
23120                                           type, value, len);
23121       break;
23122
23123     case DW_FORM_sdata:
23124     case DW_FORM_implicit_const:
23125       type = die_type (die, cu);
23126       result = write_constant_as_bytes (obstack, byte_order,
23127                                         type, DW_SND (attr), len);
23128       break;
23129
23130     case DW_FORM_udata:
23131       type = die_type (die, cu);
23132       result = write_constant_as_bytes (obstack, byte_order,
23133                                         type, DW_UNSND (attr), len);
23134       break;
23135
23136     default:
23137       complaint (_("unsupported const value attribute form: '%s'"),
23138                  dwarf_form_name (attr->form));
23139       break;
23140     }
23141
23142   return result;
23143 }
23144
23145 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23146    valid type for this die is found.  */
23147
23148 struct type *
23149 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23150                                 struct dwarf2_per_cu_data *per_cu)
23151 {
23152   struct dwarf2_cu *cu;
23153   struct die_info *die;
23154
23155   if (per_cu->cu == NULL)
23156     load_cu (per_cu, false);
23157   cu = per_cu->cu;
23158   if (!cu)
23159     return NULL;
23160
23161   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23162   if (!die)
23163     return NULL;
23164
23165   return die_type (die, cu);
23166 }
23167
23168 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23169    PER_CU.  */
23170
23171 struct type *
23172 dwarf2_get_die_type (cu_offset die_offset,
23173                      struct dwarf2_per_cu_data *per_cu)
23174 {
23175   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23176   return get_die_type_at_offset (die_offset_sect, per_cu);
23177 }
23178
23179 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23180    On entry *REF_CU is the CU of SRC_DIE.
23181    On exit *REF_CU is the CU of the result.
23182    Returns NULL if the referenced DIE isn't found.  */
23183
23184 static struct die_info *
23185 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23186                   struct dwarf2_cu **ref_cu)
23187 {
23188   struct die_info temp_die;
23189   struct dwarf2_cu *sig_cu;
23190   struct die_info *die;
23191
23192   /* While it might be nice to assert sig_type->type == NULL here,
23193      we can get here for DW_AT_imported_declaration where we need
23194      the DIE not the type.  */
23195
23196   /* If necessary, add it to the queue and load its DIEs.  */
23197
23198   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23199     read_signatured_type (sig_type);
23200
23201   sig_cu = sig_type->per_cu.cu;
23202   gdb_assert (sig_cu != NULL);
23203   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23204   temp_die.sect_off = sig_type->type_offset_in_section;
23205   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23206                                                  to_underlying (temp_die.sect_off));
23207   if (die)
23208     {
23209       struct dwarf2_per_objfile *dwarf2_per_objfile
23210         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23211
23212       /* For .gdb_index version 7 keep track of included TUs.
23213          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23214       if (dwarf2_per_objfile->index_table != NULL
23215           && dwarf2_per_objfile->index_table->version <= 7)
23216         {
23217           VEC_safe_push (dwarf2_per_cu_ptr,
23218                          (*ref_cu)->per_cu->imported_symtabs,
23219                          sig_cu->per_cu);
23220         }
23221
23222       *ref_cu = sig_cu;
23223       return die;
23224     }
23225
23226   return NULL;
23227 }
23228
23229 /* Follow signatured type referenced by ATTR in SRC_DIE.
23230    On entry *REF_CU is the CU of SRC_DIE.
23231    On exit *REF_CU is the CU of the result.
23232    The result is the DIE of the type.
23233    If the referenced type cannot be found an error is thrown.  */
23234
23235 static struct die_info *
23236 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23237                 struct dwarf2_cu **ref_cu)
23238 {
23239   ULONGEST signature = DW_SIGNATURE (attr);
23240   struct signatured_type *sig_type;
23241   struct die_info *die;
23242
23243   gdb_assert (attr->form == DW_FORM_ref_sig8);
23244
23245   sig_type = lookup_signatured_type (*ref_cu, signature);
23246   /* sig_type will be NULL if the signatured type is missing from
23247      the debug info.  */
23248   if (sig_type == NULL)
23249     {
23250       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23251                " from DIE at %s [in module %s]"),
23252              hex_string (signature), sect_offset_str (src_die->sect_off),
23253              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23254     }
23255
23256   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23257   if (die == NULL)
23258     {
23259       dump_die_for_error (src_die);
23260       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23261                " from DIE at %s [in module %s]"),
23262              hex_string (signature), sect_offset_str (src_die->sect_off),
23263              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23264     }
23265
23266   return die;
23267 }
23268
23269 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23270    reading in and processing the type unit if necessary.  */
23271
23272 static struct type *
23273 get_signatured_type (struct die_info *die, ULONGEST signature,
23274                      struct dwarf2_cu *cu)
23275 {
23276   struct dwarf2_per_objfile *dwarf2_per_objfile
23277     = cu->per_cu->dwarf2_per_objfile;
23278   struct signatured_type *sig_type;
23279   struct dwarf2_cu *type_cu;
23280   struct die_info *type_die;
23281   struct type *type;
23282
23283   sig_type = lookup_signatured_type (cu, signature);
23284   /* sig_type will be NULL if the signatured type is missing from
23285      the debug info.  */
23286   if (sig_type == NULL)
23287     {
23288       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23289                    " from DIE at %s [in module %s]"),
23290                  hex_string (signature), sect_offset_str (die->sect_off),
23291                  objfile_name (dwarf2_per_objfile->objfile));
23292       return build_error_marker_type (cu, die);
23293     }
23294
23295   /* If we already know the type we're done.  */
23296   if (sig_type->type != NULL)
23297     return sig_type->type;
23298
23299   type_cu = cu;
23300   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23301   if (type_die != NULL)
23302     {
23303       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23304          is created.  This is important, for example, because for c++ classes
23305          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23306       type = read_type_die (type_die, type_cu);
23307       if (type == NULL)
23308         {
23309           complaint (_("Dwarf Error: Cannot build signatured type %s"
23310                        " referenced from DIE at %s [in module %s]"),
23311                      hex_string (signature), sect_offset_str (die->sect_off),
23312                      objfile_name (dwarf2_per_objfile->objfile));
23313           type = build_error_marker_type (cu, die);
23314         }
23315     }
23316   else
23317     {
23318       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23319                    " from DIE at %s [in module %s]"),
23320                  hex_string (signature), sect_offset_str (die->sect_off),
23321                  objfile_name (dwarf2_per_objfile->objfile));
23322       type = build_error_marker_type (cu, die);
23323     }
23324   sig_type->type = type;
23325
23326   return type;
23327 }
23328
23329 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23330    reading in and processing the type unit if necessary.  */
23331
23332 static struct type *
23333 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23334                           struct dwarf2_cu *cu) /* ARI: editCase function */
23335 {
23336   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23337   if (attr_form_is_ref (attr))
23338     {
23339       struct dwarf2_cu *type_cu = cu;
23340       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23341
23342       return read_type_die (type_die, type_cu);
23343     }
23344   else if (attr->form == DW_FORM_ref_sig8)
23345     {
23346       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23347     }
23348   else
23349     {
23350       struct dwarf2_per_objfile *dwarf2_per_objfile
23351         = cu->per_cu->dwarf2_per_objfile;
23352
23353       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23354                    " at %s [in module %s]"),
23355                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23356                  objfile_name (dwarf2_per_objfile->objfile));
23357       return build_error_marker_type (cu, die);
23358     }
23359 }
23360
23361 /* Load the DIEs associated with type unit PER_CU into memory.  */
23362
23363 static void
23364 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23365 {
23366   struct signatured_type *sig_type;
23367
23368   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23369   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23370
23371   /* We have the per_cu, but we need the signatured_type.
23372      Fortunately this is an easy translation.  */
23373   gdb_assert (per_cu->is_debug_types);
23374   sig_type = (struct signatured_type *) per_cu;
23375
23376   gdb_assert (per_cu->cu == NULL);
23377
23378   read_signatured_type (sig_type);
23379
23380   gdb_assert (per_cu->cu != NULL);
23381 }
23382
23383 /* die_reader_func for read_signatured_type.
23384    This is identical to load_full_comp_unit_reader,
23385    but is kept separate for now.  */
23386
23387 static void
23388 read_signatured_type_reader (const struct die_reader_specs *reader,
23389                              const gdb_byte *info_ptr,
23390                              struct die_info *comp_unit_die,
23391                              int has_children,
23392                              void *data)
23393 {
23394   struct dwarf2_cu *cu = reader->cu;
23395
23396   gdb_assert (cu->die_hash == NULL);
23397   cu->die_hash =
23398     htab_create_alloc_ex (cu->header.length / 12,
23399                           die_hash,
23400                           die_eq,
23401                           NULL,
23402                           &cu->comp_unit_obstack,
23403                           hashtab_obstack_allocate,
23404                           dummy_obstack_deallocate);
23405
23406   if (has_children)
23407     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23408                                                   &info_ptr, comp_unit_die);
23409   cu->dies = comp_unit_die;
23410   /* comp_unit_die is not stored in die_hash, no need.  */
23411
23412   /* We try not to read any attributes in this function, because not
23413      all CUs needed for references have been loaded yet, and symbol
23414      table processing isn't initialized.  But we have to set the CU language,
23415      or we won't be able to build types correctly.
23416      Similarly, if we do not read the producer, we can not apply
23417      producer-specific interpretation.  */
23418   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23419 }
23420
23421 /* Read in a signatured type and build its CU and DIEs.
23422    If the type is a stub for the real type in a DWO file,
23423    read in the real type from the DWO file as well.  */
23424
23425 static void
23426 read_signatured_type (struct signatured_type *sig_type)
23427 {
23428   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23429
23430   gdb_assert (per_cu->is_debug_types);
23431   gdb_assert (per_cu->cu == NULL);
23432
23433   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23434                            read_signatured_type_reader, NULL);
23435   sig_type->per_cu.tu_read = 1;
23436 }
23437
23438 /* Decode simple location descriptions.
23439    Given a pointer to a dwarf block that defines a location, compute
23440    the location and return the value.
23441
23442    NOTE drow/2003-11-18: This function is called in two situations
23443    now: for the address of static or global variables (partial symbols
23444    only) and for offsets into structures which are expected to be
23445    (more or less) constant.  The partial symbol case should go away,
23446    and only the constant case should remain.  That will let this
23447    function complain more accurately.  A few special modes are allowed
23448    without complaint for global variables (for instance, global
23449    register values and thread-local values).
23450
23451    A location description containing no operations indicates that the
23452    object is optimized out.  The return value is 0 for that case.
23453    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23454    callers will only want a very basic result and this can become a
23455    complaint.
23456
23457    Note that stack[0] is unused except as a default error return.  */
23458
23459 static CORE_ADDR
23460 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23461 {
23462   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23463   size_t i;
23464   size_t size = blk->size;
23465   const gdb_byte *data = blk->data;
23466   CORE_ADDR stack[64];
23467   int stacki;
23468   unsigned int bytes_read, unsnd;
23469   gdb_byte op;
23470
23471   i = 0;
23472   stacki = 0;
23473   stack[stacki] = 0;
23474   stack[++stacki] = 0;
23475
23476   while (i < size)
23477     {
23478       op = data[i++];
23479       switch (op)
23480         {
23481         case DW_OP_lit0:
23482         case DW_OP_lit1:
23483         case DW_OP_lit2:
23484         case DW_OP_lit3:
23485         case DW_OP_lit4:
23486         case DW_OP_lit5:
23487         case DW_OP_lit6:
23488         case DW_OP_lit7:
23489         case DW_OP_lit8:
23490         case DW_OP_lit9:
23491         case DW_OP_lit10:
23492         case DW_OP_lit11:
23493         case DW_OP_lit12:
23494         case DW_OP_lit13:
23495         case DW_OP_lit14:
23496         case DW_OP_lit15:
23497         case DW_OP_lit16:
23498         case DW_OP_lit17:
23499         case DW_OP_lit18:
23500         case DW_OP_lit19:
23501         case DW_OP_lit20:
23502         case DW_OP_lit21:
23503         case DW_OP_lit22:
23504         case DW_OP_lit23:
23505         case DW_OP_lit24:
23506         case DW_OP_lit25:
23507         case DW_OP_lit26:
23508         case DW_OP_lit27:
23509         case DW_OP_lit28:
23510         case DW_OP_lit29:
23511         case DW_OP_lit30:
23512         case DW_OP_lit31:
23513           stack[++stacki] = op - DW_OP_lit0;
23514           break;
23515
23516         case DW_OP_reg0:
23517         case DW_OP_reg1:
23518         case DW_OP_reg2:
23519         case DW_OP_reg3:
23520         case DW_OP_reg4:
23521         case DW_OP_reg5:
23522         case DW_OP_reg6:
23523         case DW_OP_reg7:
23524         case DW_OP_reg8:
23525         case DW_OP_reg9:
23526         case DW_OP_reg10:
23527         case DW_OP_reg11:
23528         case DW_OP_reg12:
23529         case DW_OP_reg13:
23530         case DW_OP_reg14:
23531         case DW_OP_reg15:
23532         case DW_OP_reg16:
23533         case DW_OP_reg17:
23534         case DW_OP_reg18:
23535         case DW_OP_reg19:
23536         case DW_OP_reg20:
23537         case DW_OP_reg21:
23538         case DW_OP_reg22:
23539         case DW_OP_reg23:
23540         case DW_OP_reg24:
23541         case DW_OP_reg25:
23542         case DW_OP_reg26:
23543         case DW_OP_reg27:
23544         case DW_OP_reg28:
23545         case DW_OP_reg29:
23546         case DW_OP_reg30:
23547         case DW_OP_reg31:
23548           stack[++stacki] = op - DW_OP_reg0;
23549           if (i < size)
23550             dwarf2_complex_location_expr_complaint ();
23551           break;
23552
23553         case DW_OP_regx:
23554           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23555           i += bytes_read;
23556           stack[++stacki] = unsnd;
23557           if (i < size)
23558             dwarf2_complex_location_expr_complaint ();
23559           break;
23560
23561         case DW_OP_addr:
23562           stack[++stacki] = read_address (objfile->obfd, &data[i],
23563                                           cu, &bytes_read);
23564           i += bytes_read;
23565           break;
23566
23567         case DW_OP_const1u:
23568           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23569           i += 1;
23570           break;
23571
23572         case DW_OP_const1s:
23573           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23574           i += 1;
23575           break;
23576
23577         case DW_OP_const2u:
23578           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23579           i += 2;
23580           break;
23581
23582         case DW_OP_const2s:
23583           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23584           i += 2;
23585           break;
23586
23587         case DW_OP_const4u:
23588           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23589           i += 4;
23590           break;
23591
23592         case DW_OP_const4s:
23593           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23594           i += 4;
23595           break;
23596
23597         case DW_OP_const8u:
23598           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23599           i += 8;
23600           break;
23601
23602         case DW_OP_constu:
23603           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23604                                                   &bytes_read);
23605           i += bytes_read;
23606           break;
23607
23608         case DW_OP_consts:
23609           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23610           i += bytes_read;
23611           break;
23612
23613         case DW_OP_dup:
23614           stack[stacki + 1] = stack[stacki];
23615           stacki++;
23616           break;
23617
23618         case DW_OP_plus:
23619           stack[stacki - 1] += stack[stacki];
23620           stacki--;
23621           break;
23622
23623         case DW_OP_plus_uconst:
23624           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23625                                                  &bytes_read);
23626           i += bytes_read;
23627           break;
23628
23629         case DW_OP_minus:
23630           stack[stacki - 1] -= stack[stacki];
23631           stacki--;
23632           break;
23633
23634         case DW_OP_deref:
23635           /* If we're not the last op, then we definitely can't encode
23636              this using GDB's address_class enum.  This is valid for partial
23637              global symbols, although the variable's address will be bogus
23638              in the psymtab.  */
23639           if (i < size)
23640             dwarf2_complex_location_expr_complaint ();
23641           break;
23642
23643         case DW_OP_GNU_push_tls_address:
23644         case DW_OP_form_tls_address:
23645           /* The top of the stack has the offset from the beginning
23646              of the thread control block at which the variable is located.  */
23647           /* Nothing should follow this operator, so the top of stack would
23648              be returned.  */
23649           /* This is valid for partial global symbols, but the variable's
23650              address will be bogus in the psymtab.  Make it always at least
23651              non-zero to not look as a variable garbage collected by linker
23652              which have DW_OP_addr 0.  */
23653           if (i < size)
23654             dwarf2_complex_location_expr_complaint ();
23655           stack[stacki]++;
23656           break;
23657
23658         case DW_OP_GNU_uninit:
23659           break;
23660
23661         case DW_OP_GNU_addr_index:
23662         case DW_OP_GNU_const_index:
23663           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23664                                                          &bytes_read);
23665           i += bytes_read;
23666           break;
23667
23668         default:
23669           {
23670             const char *name = get_DW_OP_name (op);
23671
23672             if (name)
23673               complaint (_("unsupported stack op: '%s'"),
23674                          name);
23675             else
23676               complaint (_("unsupported stack op: '%02x'"),
23677                          op);
23678           }
23679
23680           return (stack[stacki]);
23681         }
23682
23683       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23684          outside of the allocated space.  Also enforce minimum>0.  */
23685       if (stacki >= ARRAY_SIZE (stack) - 1)
23686         {
23687           complaint (_("location description stack overflow"));
23688           return 0;
23689         }
23690
23691       if (stacki <= 0)
23692         {
23693           complaint (_("location description stack underflow"));
23694           return 0;
23695         }
23696     }
23697   return (stack[stacki]);
23698 }
23699
23700 /* memory allocation interface */
23701
23702 static struct dwarf_block *
23703 dwarf_alloc_block (struct dwarf2_cu *cu)
23704 {
23705   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23706 }
23707
23708 static struct die_info *
23709 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23710 {
23711   struct die_info *die;
23712   size_t size = sizeof (struct die_info);
23713
23714   if (num_attrs > 1)
23715     size += (num_attrs - 1) * sizeof (struct attribute);
23716
23717   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23718   memset (die, 0, sizeof (struct die_info));
23719   return (die);
23720 }
23721
23722 \f
23723 /* Macro support.  */
23724
23725 /* Return file name relative to the compilation directory of file number I in
23726    *LH's file name table.  The result is allocated using xmalloc; the caller is
23727    responsible for freeing it.  */
23728
23729 static char *
23730 file_file_name (int file, struct line_header *lh)
23731 {
23732   /* Is the file number a valid index into the line header's file name
23733      table?  Remember that file numbers start with one, not zero.  */
23734   if (1 <= file && file <= lh->file_names.size ())
23735     {
23736       const file_entry &fe = lh->file_names[file - 1];
23737
23738       if (!IS_ABSOLUTE_PATH (fe.name))
23739         {
23740           const char *dir = fe.include_dir (lh);
23741           if (dir != NULL)
23742             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23743         }
23744       return xstrdup (fe.name);
23745     }
23746   else
23747     {
23748       /* The compiler produced a bogus file number.  We can at least
23749          record the macro definitions made in the file, even if we
23750          won't be able to find the file by name.  */
23751       char fake_name[80];
23752
23753       xsnprintf (fake_name, sizeof (fake_name),
23754                  "<bad macro file number %d>", file);
23755
23756       complaint (_("bad file number in macro information (%d)"),
23757                  file);
23758
23759       return xstrdup (fake_name);
23760     }
23761 }
23762
23763 /* Return the full name of file number I in *LH's file name table.
23764    Use COMP_DIR as the name of the current directory of the
23765    compilation.  The result is allocated using xmalloc; the caller is
23766    responsible for freeing it.  */
23767 static char *
23768 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23769 {
23770   /* Is the file number a valid index into the line header's file name
23771      table?  Remember that file numbers start with one, not zero.  */
23772   if (1 <= file && file <= lh->file_names.size ())
23773     {
23774       char *relative = file_file_name (file, lh);
23775
23776       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23777         return relative;
23778       return reconcat (relative, comp_dir, SLASH_STRING,
23779                        relative, (char *) NULL);
23780     }
23781   else
23782     return file_file_name (file, lh);
23783 }
23784
23785
23786 static struct macro_source_file *
23787 macro_start_file (struct dwarf2_cu *cu,
23788                   int file, int line,
23789                   struct macro_source_file *current_file,
23790                   struct line_header *lh)
23791 {
23792   /* File name relative to the compilation directory of this source file.  */
23793   char *file_name = file_file_name (file, lh);
23794
23795   if (! current_file)
23796     {
23797       /* Note: We don't create a macro table for this compilation unit
23798          at all until we actually get a filename.  */
23799       struct macro_table *macro_table = cu->builder->get_macro_table ();
23800
23801       /* If we have no current file, then this must be the start_file
23802          directive for the compilation unit's main source file.  */
23803       current_file = macro_set_main (macro_table, file_name);
23804       macro_define_special (macro_table);
23805     }
23806   else
23807     current_file = macro_include (current_file, line, file_name);
23808
23809   xfree (file_name);
23810
23811   return current_file;
23812 }
23813
23814 static const char *
23815 consume_improper_spaces (const char *p, const char *body)
23816 {
23817   if (*p == ' ')
23818     {
23819       complaint (_("macro definition contains spaces "
23820                    "in formal argument list:\n`%s'"),
23821                  body);
23822
23823       while (*p == ' ')
23824         p++;
23825     }
23826
23827   return p;
23828 }
23829
23830
23831 static void
23832 parse_macro_definition (struct macro_source_file *file, int line,
23833                         const char *body)
23834 {
23835   const char *p;
23836
23837   /* The body string takes one of two forms.  For object-like macro
23838      definitions, it should be:
23839
23840         <macro name> " " <definition>
23841
23842      For function-like macro definitions, it should be:
23843
23844         <macro name> "() " <definition>
23845      or
23846         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23847
23848      Spaces may appear only where explicitly indicated, and in the
23849      <definition>.
23850
23851      The Dwarf 2 spec says that an object-like macro's name is always
23852      followed by a space, but versions of GCC around March 2002 omit
23853      the space when the macro's definition is the empty string.
23854
23855      The Dwarf 2 spec says that there should be no spaces between the
23856      formal arguments in a function-like macro's formal argument list,
23857      but versions of GCC around March 2002 include spaces after the
23858      commas.  */
23859
23860
23861   /* Find the extent of the macro name.  The macro name is terminated
23862      by either a space or null character (for an object-like macro) or
23863      an opening paren (for a function-like macro).  */
23864   for (p = body; *p; p++)
23865     if (*p == ' ' || *p == '(')
23866       break;
23867
23868   if (*p == ' ' || *p == '\0')
23869     {
23870       /* It's an object-like macro.  */
23871       int name_len = p - body;
23872       char *name = savestring (body, name_len);
23873       const char *replacement;
23874
23875       if (*p == ' ')
23876         replacement = body + name_len + 1;
23877       else
23878         {
23879           dwarf2_macro_malformed_definition_complaint (body);
23880           replacement = body + name_len;
23881         }
23882
23883       macro_define_object (file, line, name, replacement);
23884
23885       xfree (name);
23886     }
23887   else if (*p == '(')
23888     {
23889       /* It's a function-like macro.  */
23890       char *name = savestring (body, p - body);
23891       int argc = 0;
23892       int argv_size = 1;
23893       char **argv = XNEWVEC (char *, argv_size);
23894
23895       p++;
23896
23897       p = consume_improper_spaces (p, body);
23898
23899       /* Parse the formal argument list.  */
23900       while (*p && *p != ')')
23901         {
23902           /* Find the extent of the current argument name.  */
23903           const char *arg_start = p;
23904
23905           while (*p && *p != ',' && *p != ')' && *p != ' ')
23906             p++;
23907
23908           if (! *p || p == arg_start)
23909             dwarf2_macro_malformed_definition_complaint (body);
23910           else
23911             {
23912               /* Make sure argv has room for the new argument.  */
23913               if (argc >= argv_size)
23914                 {
23915                   argv_size *= 2;
23916                   argv = XRESIZEVEC (char *, argv, argv_size);
23917                 }
23918
23919               argv[argc++] = savestring (arg_start, p - arg_start);
23920             }
23921
23922           p = consume_improper_spaces (p, body);
23923
23924           /* Consume the comma, if present.  */
23925           if (*p == ',')
23926             {
23927               p++;
23928
23929               p = consume_improper_spaces (p, body);
23930             }
23931         }
23932
23933       if (*p == ')')
23934         {
23935           p++;
23936
23937           if (*p == ' ')
23938             /* Perfectly formed definition, no complaints.  */
23939             macro_define_function (file, line, name,
23940                                    argc, (const char **) argv,
23941                                    p + 1);
23942           else if (*p == '\0')
23943             {
23944               /* Complain, but do define it.  */
23945               dwarf2_macro_malformed_definition_complaint (body);
23946               macro_define_function (file, line, name,
23947                                      argc, (const char **) argv,
23948                                      p);
23949             }
23950           else
23951             /* Just complain.  */
23952             dwarf2_macro_malformed_definition_complaint (body);
23953         }
23954       else
23955         /* Just complain.  */
23956         dwarf2_macro_malformed_definition_complaint (body);
23957
23958       xfree (name);
23959       {
23960         int i;
23961
23962         for (i = 0; i < argc; i++)
23963           xfree (argv[i]);
23964       }
23965       xfree (argv);
23966     }
23967   else
23968     dwarf2_macro_malformed_definition_complaint (body);
23969 }
23970
23971 /* Skip some bytes from BYTES according to the form given in FORM.
23972    Returns the new pointer.  */
23973
23974 static const gdb_byte *
23975 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23976                  enum dwarf_form form,
23977                  unsigned int offset_size,
23978                  struct dwarf2_section_info *section)
23979 {
23980   unsigned int bytes_read;
23981
23982   switch (form)
23983     {
23984     case DW_FORM_data1:
23985     case DW_FORM_flag:
23986       ++bytes;
23987       break;
23988
23989     case DW_FORM_data2:
23990       bytes += 2;
23991       break;
23992
23993     case DW_FORM_data4:
23994       bytes += 4;
23995       break;
23996
23997     case DW_FORM_data8:
23998       bytes += 8;
23999       break;
24000
24001     case DW_FORM_data16:
24002       bytes += 16;
24003       break;
24004
24005     case DW_FORM_string:
24006       read_direct_string (abfd, bytes, &bytes_read);
24007       bytes += bytes_read;
24008       break;
24009
24010     case DW_FORM_sec_offset:
24011     case DW_FORM_strp:
24012     case DW_FORM_GNU_strp_alt:
24013       bytes += offset_size;
24014       break;
24015
24016     case DW_FORM_block:
24017       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24018       bytes += bytes_read;
24019       break;
24020
24021     case DW_FORM_block1:
24022       bytes += 1 + read_1_byte (abfd, bytes);
24023       break;
24024     case DW_FORM_block2:
24025       bytes += 2 + read_2_bytes (abfd, bytes);
24026       break;
24027     case DW_FORM_block4:
24028       bytes += 4 + read_4_bytes (abfd, bytes);
24029       break;
24030
24031     case DW_FORM_sdata:
24032     case DW_FORM_udata:
24033     case DW_FORM_GNU_addr_index:
24034     case DW_FORM_GNU_str_index:
24035       bytes = gdb_skip_leb128 (bytes, buffer_end);
24036       if (bytes == NULL)
24037         {
24038           dwarf2_section_buffer_overflow_complaint (section);
24039           return NULL;
24040         }
24041       break;
24042
24043     case DW_FORM_implicit_const:
24044       break;
24045
24046     default:
24047       {
24048         complaint (_("invalid form 0x%x in `%s'"),
24049                    form, get_section_name (section));
24050         return NULL;
24051       }
24052     }
24053
24054   return bytes;
24055 }
24056
24057 /* A helper for dwarf_decode_macros that handles skipping an unknown
24058    opcode.  Returns an updated pointer to the macro data buffer; or,
24059    on error, issues a complaint and returns NULL.  */
24060
24061 static const gdb_byte *
24062 skip_unknown_opcode (unsigned int opcode,
24063                      const gdb_byte **opcode_definitions,
24064                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24065                      bfd *abfd,
24066                      unsigned int offset_size,
24067                      struct dwarf2_section_info *section)
24068 {
24069   unsigned int bytes_read, i;
24070   unsigned long arg;
24071   const gdb_byte *defn;
24072
24073   if (opcode_definitions[opcode] == NULL)
24074     {
24075       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
24076                  opcode);
24077       return NULL;
24078     }
24079
24080   defn = opcode_definitions[opcode];
24081   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24082   defn += bytes_read;
24083
24084   for (i = 0; i < arg; ++i)
24085     {
24086       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24087                                  (enum dwarf_form) defn[i], offset_size,
24088                                  section);
24089       if (mac_ptr == NULL)
24090         {
24091           /* skip_form_bytes already issued the complaint.  */
24092           return NULL;
24093         }
24094     }
24095
24096   return mac_ptr;
24097 }
24098
24099 /* A helper function which parses the header of a macro section.
24100    If the macro section is the extended (for now called "GNU") type,
24101    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24102    the header, or issues a complaint and returns NULL on error.  */
24103
24104 static const gdb_byte *
24105 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24106                           bfd *abfd,
24107                           const gdb_byte *mac_ptr,
24108                           unsigned int *offset_size,
24109                           int section_is_gnu)
24110 {
24111   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24112
24113   if (section_is_gnu)
24114     {
24115       unsigned int version, flags;
24116
24117       version = read_2_bytes (abfd, mac_ptr);
24118       if (version != 4 && version != 5)
24119         {
24120           complaint (_("unrecognized version `%d' in .debug_macro section"),
24121                      version);
24122           return NULL;
24123         }
24124       mac_ptr += 2;
24125
24126       flags = read_1_byte (abfd, mac_ptr);
24127       ++mac_ptr;
24128       *offset_size = (flags & 1) ? 8 : 4;
24129
24130       if ((flags & 2) != 0)
24131         /* We don't need the line table offset.  */
24132         mac_ptr += *offset_size;
24133
24134       /* Vendor opcode descriptions.  */
24135       if ((flags & 4) != 0)
24136         {
24137           unsigned int i, count;
24138
24139           count = read_1_byte (abfd, mac_ptr);
24140           ++mac_ptr;
24141           for (i = 0; i < count; ++i)
24142             {
24143               unsigned int opcode, bytes_read;
24144               unsigned long arg;
24145
24146               opcode = read_1_byte (abfd, mac_ptr);
24147               ++mac_ptr;
24148               opcode_definitions[opcode] = mac_ptr;
24149               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24150               mac_ptr += bytes_read;
24151               mac_ptr += arg;
24152             }
24153         }
24154     }
24155
24156   return mac_ptr;
24157 }
24158
24159 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24160    including DW_MACRO_import.  */
24161
24162 static void
24163 dwarf_decode_macro_bytes (struct dwarf2_cu *cu,
24164                           bfd *abfd,
24165                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24166                           struct macro_source_file *current_file,
24167                           struct line_header *lh,
24168                           struct dwarf2_section_info *section,
24169                           int section_is_gnu, int section_is_dwz,
24170                           unsigned int offset_size,
24171                           htab_t include_hash)
24172 {
24173   struct dwarf2_per_objfile *dwarf2_per_objfile
24174     = cu->per_cu->dwarf2_per_objfile;
24175   struct objfile *objfile = dwarf2_per_objfile->objfile;
24176   enum dwarf_macro_record_type macinfo_type;
24177   int at_commandline;
24178   const gdb_byte *opcode_definitions[256];
24179
24180   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24181                                       &offset_size, section_is_gnu);
24182   if (mac_ptr == NULL)
24183     {
24184       /* We already issued a complaint.  */
24185       return;
24186     }
24187
24188   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24189      GDB is still reading the definitions from command line.  First
24190      DW_MACINFO_start_file will need to be ignored as it was already executed
24191      to create CURRENT_FILE for the main source holding also the command line
24192      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24193      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24194
24195   at_commandline = 1;
24196
24197   do
24198     {
24199       /* Do we at least have room for a macinfo type byte?  */
24200       if (mac_ptr >= mac_end)
24201         {
24202           dwarf2_section_buffer_overflow_complaint (section);
24203           break;
24204         }
24205
24206       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24207       mac_ptr++;
24208
24209       /* Note that we rely on the fact that the corresponding GNU and
24210          DWARF constants are the same.  */
24211       DIAGNOSTIC_PUSH
24212       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24213       switch (macinfo_type)
24214         {
24215           /* A zero macinfo type indicates the end of the macro
24216              information.  */
24217         case 0:
24218           break;
24219
24220         case DW_MACRO_define:
24221         case DW_MACRO_undef:
24222         case DW_MACRO_define_strp:
24223         case DW_MACRO_undef_strp:
24224         case DW_MACRO_define_sup:
24225         case DW_MACRO_undef_sup:
24226           {
24227             unsigned int bytes_read;
24228             int line;
24229             const char *body;
24230             int is_define;
24231
24232             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24233             mac_ptr += bytes_read;
24234
24235             if (macinfo_type == DW_MACRO_define
24236                 || macinfo_type == DW_MACRO_undef)
24237               {
24238                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24239                 mac_ptr += bytes_read;
24240               }
24241             else
24242               {
24243                 LONGEST str_offset;
24244
24245                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24246                 mac_ptr += offset_size;
24247
24248                 if (macinfo_type == DW_MACRO_define_sup
24249                     || macinfo_type == DW_MACRO_undef_sup
24250                     || section_is_dwz)
24251                   {
24252                     struct dwz_file *dwz
24253                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24254
24255                     body = read_indirect_string_from_dwz (objfile,
24256                                                           dwz, str_offset);
24257                   }
24258                 else
24259                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24260                                                          abfd, str_offset);
24261               }
24262
24263             is_define = (macinfo_type == DW_MACRO_define
24264                          || macinfo_type == DW_MACRO_define_strp
24265                          || macinfo_type == DW_MACRO_define_sup);
24266             if (! current_file)
24267               {
24268                 /* DWARF violation as no main source is present.  */
24269                 complaint (_("debug info with no main source gives macro %s "
24270                              "on line %d: %s"),
24271                            is_define ? _("definition") : _("undefinition"),
24272                            line, body);
24273                 break;
24274               }
24275             if ((line == 0 && !at_commandline)
24276                 || (line != 0 && at_commandline))
24277               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24278                          at_commandline ? _("command-line") : _("in-file"),
24279                          is_define ? _("definition") : _("undefinition"),
24280                          line == 0 ? _("zero") : _("non-zero"), line, body);
24281
24282             if (is_define)
24283               parse_macro_definition (current_file, line, body);
24284             else
24285               {
24286                 gdb_assert (macinfo_type == DW_MACRO_undef
24287                             || macinfo_type == DW_MACRO_undef_strp
24288                             || macinfo_type == DW_MACRO_undef_sup);
24289                 macro_undef (current_file, line, body);
24290               }
24291           }
24292           break;
24293
24294         case DW_MACRO_start_file:
24295           {
24296             unsigned int bytes_read;
24297             int line, file;
24298
24299             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24300             mac_ptr += bytes_read;
24301             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24302             mac_ptr += bytes_read;
24303
24304             if ((line == 0 && !at_commandline)
24305                 || (line != 0 && at_commandline))
24306               complaint (_("debug info gives source %d included "
24307                            "from %s at %s line %d"),
24308                          file, at_commandline ? _("command-line") : _("file"),
24309                          line == 0 ? _("zero") : _("non-zero"), line);
24310
24311             if (at_commandline)
24312               {
24313                 /* This DW_MACRO_start_file was executed in the
24314                    pass one.  */
24315                 at_commandline = 0;
24316               }
24317             else
24318               current_file = macro_start_file (cu, file, line, current_file,
24319                                                lh);
24320           }
24321           break;
24322
24323         case DW_MACRO_end_file:
24324           if (! current_file)
24325             complaint (_("macro debug info has an unmatched "
24326                          "`close_file' directive"));
24327           else
24328             {
24329               current_file = current_file->included_by;
24330               if (! current_file)
24331                 {
24332                   enum dwarf_macro_record_type next_type;
24333
24334                   /* GCC circa March 2002 doesn't produce the zero
24335                      type byte marking the end of the compilation
24336                      unit.  Complain if it's not there, but exit no
24337                      matter what.  */
24338
24339                   /* Do we at least have room for a macinfo type byte?  */
24340                   if (mac_ptr >= mac_end)
24341                     {
24342                       dwarf2_section_buffer_overflow_complaint (section);
24343                       return;
24344                     }
24345
24346                   /* We don't increment mac_ptr here, so this is just
24347                      a look-ahead.  */
24348                   next_type
24349                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24350                                                                   mac_ptr);
24351                   if (next_type != 0)
24352                     complaint (_("no terminating 0-type entry for "
24353                                  "macros in `.debug_macinfo' section"));
24354
24355                   return;
24356                 }
24357             }
24358           break;
24359
24360         case DW_MACRO_import:
24361         case DW_MACRO_import_sup:
24362           {
24363             LONGEST offset;
24364             void **slot;
24365             bfd *include_bfd = abfd;
24366             struct dwarf2_section_info *include_section = section;
24367             const gdb_byte *include_mac_end = mac_end;
24368             int is_dwz = section_is_dwz;
24369             const gdb_byte *new_mac_ptr;
24370
24371             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24372             mac_ptr += offset_size;
24373
24374             if (macinfo_type == DW_MACRO_import_sup)
24375               {
24376                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24377
24378                 dwarf2_read_section (objfile, &dwz->macro);
24379
24380                 include_section = &dwz->macro;
24381                 include_bfd = get_section_bfd_owner (include_section);
24382                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24383                 is_dwz = 1;
24384               }
24385
24386             new_mac_ptr = include_section->buffer + offset;
24387             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24388
24389             if (*slot != NULL)
24390               {
24391                 /* This has actually happened; see
24392                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24393                 complaint (_("recursive DW_MACRO_import in "
24394                              ".debug_macro section"));
24395               }
24396             else
24397               {
24398                 *slot = (void *) new_mac_ptr;
24399
24400                 dwarf_decode_macro_bytes (cu, include_bfd, new_mac_ptr,
24401                                           include_mac_end, current_file, lh,
24402                                           section, section_is_gnu, is_dwz,
24403                                           offset_size, include_hash);
24404
24405                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24406               }
24407           }
24408           break;
24409
24410         case DW_MACINFO_vendor_ext:
24411           if (!section_is_gnu)
24412             {
24413               unsigned int bytes_read;
24414
24415               /* This reads the constant, but since we don't recognize
24416                  any vendor extensions, we ignore it.  */
24417               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24418               mac_ptr += bytes_read;
24419               read_direct_string (abfd, mac_ptr, &bytes_read);
24420               mac_ptr += bytes_read;
24421
24422               /* We don't recognize any vendor extensions.  */
24423               break;
24424             }
24425           /* FALLTHROUGH */
24426
24427         default:
24428           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24429                                          mac_ptr, mac_end, abfd, offset_size,
24430                                          section);
24431           if (mac_ptr == NULL)
24432             return;
24433           break;
24434         }
24435       DIAGNOSTIC_POP
24436     } while (macinfo_type != 0);
24437 }
24438
24439 static void
24440 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24441                      int section_is_gnu)
24442 {
24443   struct dwarf2_per_objfile *dwarf2_per_objfile
24444     = cu->per_cu->dwarf2_per_objfile;
24445   struct objfile *objfile = dwarf2_per_objfile->objfile;
24446   struct line_header *lh = cu->line_header;
24447   bfd *abfd;
24448   const gdb_byte *mac_ptr, *mac_end;
24449   struct macro_source_file *current_file = 0;
24450   enum dwarf_macro_record_type macinfo_type;
24451   unsigned int offset_size = cu->header.offset_size;
24452   const gdb_byte *opcode_definitions[256];
24453   void **slot;
24454   struct dwarf2_section_info *section;
24455   const char *section_name;
24456
24457   if (cu->dwo_unit != NULL)
24458     {
24459       if (section_is_gnu)
24460         {
24461           section = &cu->dwo_unit->dwo_file->sections.macro;
24462           section_name = ".debug_macro.dwo";
24463         }
24464       else
24465         {
24466           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24467           section_name = ".debug_macinfo.dwo";
24468         }
24469     }
24470   else
24471     {
24472       if (section_is_gnu)
24473         {
24474           section = &dwarf2_per_objfile->macro;
24475           section_name = ".debug_macro";
24476         }
24477       else
24478         {
24479           section = &dwarf2_per_objfile->macinfo;
24480           section_name = ".debug_macinfo";
24481         }
24482     }
24483
24484   dwarf2_read_section (objfile, section);
24485   if (section->buffer == NULL)
24486     {
24487       complaint (_("missing %s section"), section_name);
24488       return;
24489     }
24490   abfd = get_section_bfd_owner (section);
24491
24492   /* First pass: Find the name of the base filename.
24493      This filename is needed in order to process all macros whose definition
24494      (or undefinition) comes from the command line.  These macros are defined
24495      before the first DW_MACINFO_start_file entry, and yet still need to be
24496      associated to the base file.
24497
24498      To determine the base file name, we scan the macro definitions until we
24499      reach the first DW_MACINFO_start_file entry.  We then initialize
24500      CURRENT_FILE accordingly so that any macro definition found before the
24501      first DW_MACINFO_start_file can still be associated to the base file.  */
24502
24503   mac_ptr = section->buffer + offset;
24504   mac_end = section->buffer + section->size;
24505
24506   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24507                                       &offset_size, section_is_gnu);
24508   if (mac_ptr == NULL)
24509     {
24510       /* We already issued a complaint.  */
24511       return;
24512     }
24513
24514   do
24515     {
24516       /* Do we at least have room for a macinfo type byte?  */
24517       if (mac_ptr >= mac_end)
24518         {
24519           /* Complaint is printed during the second pass as GDB will probably
24520              stop the first pass earlier upon finding
24521              DW_MACINFO_start_file.  */
24522           break;
24523         }
24524
24525       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24526       mac_ptr++;
24527
24528       /* Note that we rely on the fact that the corresponding GNU and
24529          DWARF constants are the same.  */
24530       DIAGNOSTIC_PUSH
24531       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24532       switch (macinfo_type)
24533         {
24534           /* A zero macinfo type indicates the end of the macro
24535              information.  */
24536         case 0:
24537           break;
24538
24539         case DW_MACRO_define:
24540         case DW_MACRO_undef:
24541           /* Only skip the data by MAC_PTR.  */
24542           {
24543             unsigned int bytes_read;
24544
24545             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24546             mac_ptr += bytes_read;
24547             read_direct_string (abfd, mac_ptr, &bytes_read);
24548             mac_ptr += bytes_read;
24549           }
24550           break;
24551
24552         case DW_MACRO_start_file:
24553           {
24554             unsigned int bytes_read;
24555             int line, file;
24556
24557             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24558             mac_ptr += bytes_read;
24559             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24560             mac_ptr += bytes_read;
24561
24562             current_file = macro_start_file (cu, file, line, current_file, lh);
24563           }
24564           break;
24565
24566         case DW_MACRO_end_file:
24567           /* No data to skip by MAC_PTR.  */
24568           break;
24569
24570         case DW_MACRO_define_strp:
24571         case DW_MACRO_undef_strp:
24572         case DW_MACRO_define_sup:
24573         case DW_MACRO_undef_sup:
24574           {
24575             unsigned int bytes_read;
24576
24577             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24578             mac_ptr += bytes_read;
24579             mac_ptr += offset_size;
24580           }
24581           break;
24582
24583         case DW_MACRO_import:
24584         case DW_MACRO_import_sup:
24585           /* Note that, according to the spec, a transparent include
24586              chain cannot call DW_MACRO_start_file.  So, we can just
24587              skip this opcode.  */
24588           mac_ptr += offset_size;
24589           break;
24590
24591         case DW_MACINFO_vendor_ext:
24592           /* Only skip the data by MAC_PTR.  */
24593           if (!section_is_gnu)
24594             {
24595               unsigned int bytes_read;
24596
24597               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24598               mac_ptr += bytes_read;
24599               read_direct_string (abfd, mac_ptr, &bytes_read);
24600               mac_ptr += bytes_read;
24601             }
24602           /* FALLTHROUGH */
24603
24604         default:
24605           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24606                                          mac_ptr, mac_end, abfd, offset_size,
24607                                          section);
24608           if (mac_ptr == NULL)
24609             return;
24610           break;
24611         }
24612       DIAGNOSTIC_POP
24613     } while (macinfo_type != 0 && current_file == NULL);
24614
24615   /* Second pass: Process all entries.
24616
24617      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24618      command-line macro definitions/undefinitions.  This flag is unset when we
24619      reach the first DW_MACINFO_start_file entry.  */
24620
24621   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24622                                            htab_eq_pointer,
24623                                            NULL, xcalloc, xfree));
24624   mac_ptr = section->buffer + offset;
24625   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24626   *slot = (void *) mac_ptr;
24627   dwarf_decode_macro_bytes (cu, abfd, mac_ptr, mac_end,
24628                             current_file, lh, section,
24629                             section_is_gnu, 0, offset_size,
24630                             include_hash.get ());
24631 }
24632
24633 /* Check if the attribute's form is a DW_FORM_block*
24634    if so return true else false.  */
24635
24636 static int
24637 attr_form_is_block (const struct attribute *attr)
24638 {
24639   return (attr == NULL ? 0 :
24640       attr->form == DW_FORM_block1
24641       || attr->form == DW_FORM_block2
24642       || attr->form == DW_FORM_block4
24643       || attr->form == DW_FORM_block
24644       || attr->form == DW_FORM_exprloc);
24645 }
24646
24647 /* Return non-zero if ATTR's value is a section offset --- classes
24648    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24649    You may use DW_UNSND (attr) to retrieve such offsets.
24650
24651    Section 7.5.4, "Attribute Encodings", explains that no attribute
24652    may have a value that belongs to more than one of these classes; it
24653    would be ambiguous if we did, because we use the same forms for all
24654    of them.  */
24655
24656 static int
24657 attr_form_is_section_offset (const struct attribute *attr)
24658 {
24659   return (attr->form == DW_FORM_data4
24660           || attr->form == DW_FORM_data8
24661           || attr->form == DW_FORM_sec_offset);
24662 }
24663
24664 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24665    zero otherwise.  When this function returns true, you can apply
24666    dwarf2_get_attr_constant_value to it.
24667
24668    However, note that for some attributes you must check
24669    attr_form_is_section_offset before using this test.  DW_FORM_data4
24670    and DW_FORM_data8 are members of both the constant class, and of
24671    the classes that contain offsets into other debug sections
24672    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24673    that, if an attribute's can be either a constant or one of the
24674    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24675    taken as section offsets, not constants.
24676
24677    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24678    cannot handle that.  */
24679
24680 static int
24681 attr_form_is_constant (const struct attribute *attr)
24682 {
24683   switch (attr->form)
24684     {
24685     case DW_FORM_sdata:
24686     case DW_FORM_udata:
24687     case DW_FORM_data1:
24688     case DW_FORM_data2:
24689     case DW_FORM_data4:
24690     case DW_FORM_data8:
24691     case DW_FORM_implicit_const:
24692       return 1;
24693     default:
24694       return 0;
24695     }
24696 }
24697
24698
24699 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24700    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24701
24702 static int
24703 attr_form_is_ref (const struct attribute *attr)
24704 {
24705   switch (attr->form)
24706     {
24707     case DW_FORM_ref_addr:
24708     case DW_FORM_ref1:
24709     case DW_FORM_ref2:
24710     case DW_FORM_ref4:
24711     case DW_FORM_ref8:
24712     case DW_FORM_ref_udata:
24713     case DW_FORM_GNU_ref_alt:
24714       return 1;
24715     default:
24716       return 0;
24717     }
24718 }
24719
24720 /* Return the .debug_loc section to use for CU.
24721    For DWO files use .debug_loc.dwo.  */
24722
24723 static struct dwarf2_section_info *
24724 cu_debug_loc_section (struct dwarf2_cu *cu)
24725 {
24726   struct dwarf2_per_objfile *dwarf2_per_objfile
24727     = cu->per_cu->dwarf2_per_objfile;
24728
24729   if (cu->dwo_unit)
24730     {
24731       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24732       
24733       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24734     }
24735   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24736                                   : &dwarf2_per_objfile->loc);
24737 }
24738
24739 /* A helper function that fills in a dwarf2_loclist_baton.  */
24740
24741 static void
24742 fill_in_loclist_baton (struct dwarf2_cu *cu,
24743                        struct dwarf2_loclist_baton *baton,
24744                        const struct attribute *attr)
24745 {
24746   struct dwarf2_per_objfile *dwarf2_per_objfile
24747     = cu->per_cu->dwarf2_per_objfile;
24748   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24749
24750   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24751
24752   baton->per_cu = cu->per_cu;
24753   gdb_assert (baton->per_cu);
24754   /* We don't know how long the location list is, but make sure we
24755      don't run off the edge of the section.  */
24756   baton->size = section->size - DW_UNSND (attr);
24757   baton->data = section->buffer + DW_UNSND (attr);
24758   baton->base_address = cu->base_address;
24759   baton->from_dwo = cu->dwo_unit != NULL;
24760 }
24761
24762 static void
24763 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24764                              struct dwarf2_cu *cu, int is_block)
24765 {
24766   struct dwarf2_per_objfile *dwarf2_per_objfile
24767     = cu->per_cu->dwarf2_per_objfile;
24768   struct objfile *objfile = dwarf2_per_objfile->objfile;
24769   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24770
24771   if (attr_form_is_section_offset (attr)
24772       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24773          the section.  If so, fall through to the complaint in the
24774          other branch.  */
24775       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24776     {
24777       struct dwarf2_loclist_baton *baton;
24778
24779       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24780
24781       fill_in_loclist_baton (cu, baton, attr);
24782
24783       if (cu->base_known == 0)
24784         complaint (_("Location list used without "
24785                      "specifying the CU base address."));
24786
24787       SYMBOL_ACLASS_INDEX (sym) = (is_block
24788                                    ? dwarf2_loclist_block_index
24789                                    : dwarf2_loclist_index);
24790       SYMBOL_LOCATION_BATON (sym) = baton;
24791     }
24792   else
24793     {
24794       struct dwarf2_locexpr_baton *baton;
24795
24796       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24797       baton->per_cu = cu->per_cu;
24798       gdb_assert (baton->per_cu);
24799
24800       if (attr_form_is_block (attr))
24801         {
24802           /* Note that we're just copying the block's data pointer
24803              here, not the actual data.  We're still pointing into the
24804              info_buffer for SYM's objfile; right now we never release
24805              that buffer, but when we do clean up properly this may
24806              need to change.  */
24807           baton->size = DW_BLOCK (attr)->size;
24808           baton->data = DW_BLOCK (attr)->data;
24809         }
24810       else
24811         {
24812           dwarf2_invalid_attrib_class_complaint ("location description",
24813                                                  SYMBOL_NATURAL_NAME (sym));
24814           baton->size = 0;
24815         }
24816
24817       SYMBOL_ACLASS_INDEX (sym) = (is_block
24818                                    ? dwarf2_locexpr_block_index
24819                                    : dwarf2_locexpr_index);
24820       SYMBOL_LOCATION_BATON (sym) = baton;
24821     }
24822 }
24823
24824 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24825    came from a separate debuginfo file, then the master objfile is
24826    returned.  */
24827
24828 struct objfile *
24829 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24830 {
24831   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24832
24833   /* Return the master objfile, so that we can report and look up the
24834      correct file containing this variable.  */
24835   if (objfile->separate_debug_objfile_backlink)
24836     objfile = objfile->separate_debug_objfile_backlink;
24837
24838   return objfile;
24839 }
24840
24841 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24842    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24843    CU_HEADERP first.  */
24844
24845 static const struct comp_unit_head *
24846 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24847                        struct dwarf2_per_cu_data *per_cu)
24848 {
24849   const gdb_byte *info_ptr;
24850
24851   if (per_cu->cu)
24852     return &per_cu->cu->header;
24853
24854   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24855
24856   memset (cu_headerp, 0, sizeof (*cu_headerp));
24857   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24858                        rcuh_kind::COMPILE);
24859
24860   return cu_headerp;
24861 }
24862
24863 /* Return the address size given in the compilation unit header for CU.  */
24864
24865 int
24866 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24867 {
24868   struct comp_unit_head cu_header_local;
24869   const struct comp_unit_head *cu_headerp;
24870
24871   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24872
24873   return cu_headerp->addr_size;
24874 }
24875
24876 /* Return the offset size given in the compilation unit header for CU.  */
24877
24878 int
24879 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24880 {
24881   struct comp_unit_head cu_header_local;
24882   const struct comp_unit_head *cu_headerp;
24883
24884   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24885
24886   return cu_headerp->offset_size;
24887 }
24888
24889 /* See its dwarf2loc.h declaration.  */
24890
24891 int
24892 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24893 {
24894   struct comp_unit_head cu_header_local;
24895   const struct comp_unit_head *cu_headerp;
24896
24897   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24898
24899   if (cu_headerp->version == 2)
24900     return cu_headerp->addr_size;
24901   else
24902     return cu_headerp->offset_size;
24903 }
24904
24905 /* Return the text offset of the CU.  The returned offset comes from
24906    this CU's objfile.  If this objfile came from a separate debuginfo
24907    file, then the offset may be different from the corresponding
24908    offset in the parent objfile.  */
24909
24910 CORE_ADDR
24911 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24912 {
24913   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24914
24915   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24916 }
24917
24918 /* Return DWARF version number of PER_CU.  */
24919
24920 short
24921 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24922 {
24923   return per_cu->dwarf_version;
24924 }
24925
24926 /* Locate the .debug_info compilation unit from CU's objfile which contains
24927    the DIE at OFFSET.  Raises an error on failure.  */
24928
24929 static struct dwarf2_per_cu_data *
24930 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24931                                   unsigned int offset_in_dwz,
24932                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24933 {
24934   struct dwarf2_per_cu_data *this_cu;
24935   int low, high;
24936   const sect_offset *cu_off;
24937
24938   low = 0;
24939   high = dwarf2_per_objfile->all_comp_units.size () - 1;
24940   while (high > low)
24941     {
24942       struct dwarf2_per_cu_data *mid_cu;
24943       int mid = low + (high - low) / 2;
24944
24945       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24946       cu_off = &mid_cu->sect_off;
24947       if (mid_cu->is_dwz > offset_in_dwz
24948           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24949         high = mid;
24950       else
24951         low = mid + 1;
24952     }
24953   gdb_assert (low == high);
24954   this_cu = dwarf2_per_objfile->all_comp_units[low];
24955   cu_off = &this_cu->sect_off;
24956   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24957     {
24958       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24959         error (_("Dwarf Error: could not find partial DIE containing "
24960                "offset %s [in module %s]"),
24961                sect_offset_str (sect_off),
24962                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
24963
24964       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24965                   <= sect_off);
24966       return dwarf2_per_objfile->all_comp_units[low-1];
24967     }
24968   else
24969     {
24970       this_cu = dwarf2_per_objfile->all_comp_units[low];
24971       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
24972           && sect_off >= this_cu->sect_off + this_cu->length)
24973         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
24974       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24975       return this_cu;
24976     }
24977 }
24978
24979 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24980
24981 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
24982   : per_cu (per_cu_),
24983     mark (0),
24984     has_loclist (0),
24985     checked_producer (0),
24986     producer_is_gxx_lt_4_6 (0),
24987     producer_is_gcc_lt_4_3 (0),
24988     producer_is_icc_lt_14 (0),
24989     processing_has_namespace_info (0)
24990 {
24991   per_cu->cu = this;
24992 }
24993
24994 /* Destroy a dwarf2_cu.  */
24995
24996 dwarf2_cu::~dwarf2_cu ()
24997 {
24998   per_cu->cu = NULL;
24999 }
25000
25001 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25002
25003 static void
25004 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25005                        enum language pretend_language)
25006 {
25007   struct attribute *attr;
25008
25009   /* Set the language we're debugging.  */
25010   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25011   if (attr)
25012     set_cu_language (DW_UNSND (attr), cu);
25013   else
25014     {
25015       cu->language = pretend_language;
25016       cu->language_defn = language_def (cu->language);
25017     }
25018
25019   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25020 }
25021
25022 /* Increase the age counter on each cached compilation unit, and free
25023    any that are too old.  */
25024
25025 static void
25026 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25027 {
25028   struct dwarf2_per_cu_data *per_cu, **last_chain;
25029
25030   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25031   per_cu = dwarf2_per_objfile->read_in_chain;
25032   while (per_cu != NULL)
25033     {
25034       per_cu->cu->last_used ++;
25035       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25036         dwarf2_mark (per_cu->cu);
25037       per_cu = per_cu->cu->read_in_chain;
25038     }
25039
25040   per_cu = dwarf2_per_objfile->read_in_chain;
25041   last_chain = &dwarf2_per_objfile->read_in_chain;
25042   while (per_cu != NULL)
25043     {
25044       struct dwarf2_per_cu_data *next_cu;
25045
25046       next_cu = per_cu->cu->read_in_chain;
25047
25048       if (!per_cu->cu->mark)
25049         {
25050           delete per_cu->cu;
25051           *last_chain = next_cu;
25052         }
25053       else
25054         last_chain = &per_cu->cu->read_in_chain;
25055
25056       per_cu = next_cu;
25057     }
25058 }
25059
25060 /* Remove a single compilation unit from the cache.  */
25061
25062 static void
25063 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25064 {
25065   struct dwarf2_per_cu_data *per_cu, **last_chain;
25066   struct dwarf2_per_objfile *dwarf2_per_objfile
25067     = target_per_cu->dwarf2_per_objfile;
25068
25069   per_cu = dwarf2_per_objfile->read_in_chain;
25070   last_chain = &dwarf2_per_objfile->read_in_chain;
25071   while (per_cu != NULL)
25072     {
25073       struct dwarf2_per_cu_data *next_cu;
25074
25075       next_cu = per_cu->cu->read_in_chain;
25076
25077       if (per_cu == target_per_cu)
25078         {
25079           delete per_cu->cu;
25080           per_cu->cu = NULL;
25081           *last_chain = next_cu;
25082           break;
25083         }
25084       else
25085         last_chain = &per_cu->cu->read_in_chain;
25086
25087       per_cu = next_cu;
25088     }
25089 }
25090
25091 /* Cleanup function for the dwarf2_per_objfile data.  */
25092
25093 static void
25094 dwarf2_free_objfile (struct objfile *objfile, void *datum)
25095 {
25096   struct dwarf2_per_objfile *dwarf2_per_objfile
25097     = static_cast<struct dwarf2_per_objfile *> (datum);
25098
25099   delete dwarf2_per_objfile;
25100 }
25101
25102 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25103    We store these in a hash table separate from the DIEs, and preserve them
25104    when the DIEs are flushed out of cache.
25105
25106    The CU "per_cu" pointer is needed because offset alone is not enough to
25107    uniquely identify the type.  A file may have multiple .debug_types sections,
25108    or the type may come from a DWO file.  Furthermore, while it's more logical
25109    to use per_cu->section+offset, with Fission the section with the data is in
25110    the DWO file but we don't know that section at the point we need it.
25111    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25112    because we can enter the lookup routine, get_die_type_at_offset, from
25113    outside this file, and thus won't necessarily have PER_CU->cu.
25114    Fortunately, PER_CU is stable for the life of the objfile.  */
25115
25116 struct dwarf2_per_cu_offset_and_type
25117 {
25118   const struct dwarf2_per_cu_data *per_cu;
25119   sect_offset sect_off;
25120   struct type *type;
25121 };
25122
25123 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25124
25125 static hashval_t
25126 per_cu_offset_and_type_hash (const void *item)
25127 {
25128   const struct dwarf2_per_cu_offset_and_type *ofs
25129     = (const struct dwarf2_per_cu_offset_and_type *) item;
25130
25131   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25132 }
25133
25134 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25135
25136 static int
25137 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25138 {
25139   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25140     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25141   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25142     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25143
25144   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25145           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25146 }
25147
25148 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25149    table if necessary.  For convenience, return TYPE.
25150
25151    The DIEs reading must have careful ordering to:
25152     * Not cause infite loops trying to read in DIEs as a prerequisite for
25153       reading current DIE.
25154     * Not trying to dereference contents of still incompletely read in types
25155       while reading in other DIEs.
25156     * Enable referencing still incompletely read in types just by a pointer to
25157       the type without accessing its fields.
25158
25159    Therefore caller should follow these rules:
25160      * Try to fetch any prerequisite types we may need to build this DIE type
25161        before building the type and calling set_die_type.
25162      * After building type call set_die_type for current DIE as soon as
25163        possible before fetching more types to complete the current type.
25164      * Make the type as complete as possible before fetching more types.  */
25165
25166 static struct type *
25167 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25168 {
25169   struct dwarf2_per_objfile *dwarf2_per_objfile
25170     = cu->per_cu->dwarf2_per_objfile;
25171   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25172   struct objfile *objfile = dwarf2_per_objfile->objfile;
25173   struct attribute *attr;
25174   struct dynamic_prop prop;
25175
25176   /* For Ada types, make sure that the gnat-specific data is always
25177      initialized (if not already set).  There are a few types where
25178      we should not be doing so, because the type-specific area is
25179      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25180      where the type-specific area is used to store the floatformat).
25181      But this is not a problem, because the gnat-specific information
25182      is actually not needed for these types.  */
25183   if (need_gnat_info (cu)
25184       && TYPE_CODE (type) != TYPE_CODE_FUNC
25185       && TYPE_CODE (type) != TYPE_CODE_FLT
25186       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25187       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25188       && TYPE_CODE (type) != TYPE_CODE_METHOD
25189       && !HAVE_GNAT_AUX_INFO (type))
25190     INIT_GNAT_SPECIFIC (type);
25191
25192   /* Read DW_AT_allocated and set in type.  */
25193   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25194   if (attr_form_is_block (attr))
25195     {
25196       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25197         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25198     }
25199   else if (attr != NULL)
25200     {
25201       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25202                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25203                  sect_offset_str (die->sect_off));
25204     }
25205
25206   /* Read DW_AT_associated and set in type.  */
25207   attr = dwarf2_attr (die, DW_AT_associated, cu);
25208   if (attr_form_is_block (attr))
25209     {
25210       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25211         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25212     }
25213   else if (attr != NULL)
25214     {
25215       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25216                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25217                  sect_offset_str (die->sect_off));
25218     }
25219
25220   /* Read DW_AT_data_location and set in type.  */
25221   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25222   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25223     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25224
25225   if (dwarf2_per_objfile->die_type_hash == NULL)
25226     {
25227       dwarf2_per_objfile->die_type_hash =
25228         htab_create_alloc_ex (127,
25229                               per_cu_offset_and_type_hash,
25230                               per_cu_offset_and_type_eq,
25231                               NULL,
25232                               &objfile->objfile_obstack,
25233                               hashtab_obstack_allocate,
25234                               dummy_obstack_deallocate);
25235     }
25236
25237   ofs.per_cu = cu->per_cu;
25238   ofs.sect_off = die->sect_off;
25239   ofs.type = type;
25240   slot = (struct dwarf2_per_cu_offset_and_type **)
25241     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25242   if (*slot)
25243     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25244                sect_offset_str (die->sect_off));
25245   *slot = XOBNEW (&objfile->objfile_obstack,
25246                   struct dwarf2_per_cu_offset_and_type);
25247   **slot = ofs;
25248   return type;
25249 }
25250
25251 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25252    or return NULL if the die does not have a saved type.  */
25253
25254 static struct type *
25255 get_die_type_at_offset (sect_offset sect_off,
25256                         struct dwarf2_per_cu_data *per_cu)
25257 {
25258   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25259   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25260
25261   if (dwarf2_per_objfile->die_type_hash == NULL)
25262     return NULL;
25263
25264   ofs.per_cu = per_cu;
25265   ofs.sect_off = sect_off;
25266   slot = ((struct dwarf2_per_cu_offset_and_type *)
25267           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25268   if (slot)
25269     return slot->type;
25270   else
25271     return NULL;
25272 }
25273
25274 /* Look up the type for DIE in CU in die_type_hash,
25275    or return NULL if DIE does not have a saved type.  */
25276
25277 static struct type *
25278 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25279 {
25280   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25281 }
25282
25283 /* Add a dependence relationship from CU to REF_PER_CU.  */
25284
25285 static void
25286 dwarf2_add_dependence (struct dwarf2_cu *cu,
25287                        struct dwarf2_per_cu_data *ref_per_cu)
25288 {
25289   void **slot;
25290
25291   if (cu->dependencies == NULL)
25292     cu->dependencies
25293       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25294                               NULL, &cu->comp_unit_obstack,
25295                               hashtab_obstack_allocate,
25296                               dummy_obstack_deallocate);
25297
25298   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25299   if (*slot == NULL)
25300     *slot = ref_per_cu;
25301 }
25302
25303 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25304    Set the mark field in every compilation unit in the
25305    cache that we must keep because we are keeping CU.  */
25306
25307 static int
25308 dwarf2_mark_helper (void **slot, void *data)
25309 {
25310   struct dwarf2_per_cu_data *per_cu;
25311
25312   per_cu = (struct dwarf2_per_cu_data *) *slot;
25313
25314   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25315      reading of the chain.  As such dependencies remain valid it is not much
25316      useful to track and undo them during QUIT cleanups.  */
25317   if (per_cu->cu == NULL)
25318     return 1;
25319
25320   if (per_cu->cu->mark)
25321     return 1;
25322   per_cu->cu->mark = 1;
25323
25324   if (per_cu->cu->dependencies != NULL)
25325     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25326
25327   return 1;
25328 }
25329
25330 /* Set the mark field in CU and in every other compilation unit in the
25331    cache that we must keep because we are keeping CU.  */
25332
25333 static void
25334 dwarf2_mark (struct dwarf2_cu *cu)
25335 {
25336   if (cu->mark)
25337     return;
25338   cu->mark = 1;
25339   if (cu->dependencies != NULL)
25340     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25341 }
25342
25343 static void
25344 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25345 {
25346   while (per_cu)
25347     {
25348       per_cu->cu->mark = 0;
25349       per_cu = per_cu->cu->read_in_chain;
25350     }
25351 }
25352
25353 /* Trivial hash function for partial_die_info: the hash value of a DIE
25354    is its offset in .debug_info for this objfile.  */
25355
25356 static hashval_t
25357 partial_die_hash (const void *item)
25358 {
25359   const struct partial_die_info *part_die
25360     = (const struct partial_die_info *) item;
25361
25362   return to_underlying (part_die->sect_off);
25363 }
25364
25365 /* Trivial comparison function for partial_die_info structures: two DIEs
25366    are equal if they have the same offset.  */
25367
25368 static int
25369 partial_die_eq (const void *item_lhs, const void *item_rhs)
25370 {
25371   const struct partial_die_info *part_die_lhs
25372     = (const struct partial_die_info *) item_lhs;
25373   const struct partial_die_info *part_die_rhs
25374     = (const struct partial_die_info *) item_rhs;
25375
25376   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25377 }
25378
25379 struct cmd_list_element *set_dwarf_cmdlist;
25380 struct cmd_list_element *show_dwarf_cmdlist;
25381
25382 static void
25383 set_dwarf_cmd (const char *args, int from_tty)
25384 {
25385   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25386              gdb_stdout);
25387 }
25388
25389 static void
25390 show_dwarf_cmd (const char *args, int from_tty)
25391 {
25392   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25393 }
25394
25395 int dwarf_always_disassemble;
25396
25397 static void
25398 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25399                                struct cmd_list_element *c, const char *value)
25400 {
25401   fprintf_filtered (file,
25402                     _("Whether to always disassemble "
25403                       "DWARF expressions is %s.\n"),
25404                     value);
25405 }
25406
25407 static void
25408 show_check_physname (struct ui_file *file, int from_tty,
25409                      struct cmd_list_element *c, const char *value)
25410 {
25411   fprintf_filtered (file,
25412                     _("Whether to check \"physname\" is %s.\n"),
25413                     value);
25414 }
25415
25416 void
25417 _initialize_dwarf2_read (void)
25418 {
25419   dwarf2_objfile_data_key
25420     = register_objfile_data_with_cleanup (nullptr, dwarf2_free_objfile);
25421
25422   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25423 Set DWARF specific variables.\n\
25424 Configure DWARF variables such as the cache size"),
25425                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25426                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25427
25428   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25429 Show DWARF specific variables\n\
25430 Show DWARF variables such as the cache size"),
25431                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25432                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25433
25434   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25435                             &dwarf_max_cache_age, _("\
25436 Set the upper bound on the age of cached DWARF compilation units."), _("\
25437 Show the upper bound on the age of cached DWARF compilation units."), _("\
25438 A higher limit means that cached compilation units will be stored\n\
25439 in memory longer, and more total memory will be used.  Zero disables\n\
25440 caching, which can slow down startup."),
25441                             NULL,
25442                             show_dwarf_max_cache_age,
25443                             &set_dwarf_cmdlist,
25444                             &show_dwarf_cmdlist);
25445
25446   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25447                            &dwarf_always_disassemble, _("\
25448 Set whether `info address' always disassembles DWARF expressions."), _("\
25449 Show whether `info address' always disassembles DWARF expressions."), _("\
25450 When enabled, DWARF expressions are always printed in an assembly-like\n\
25451 syntax.  When disabled, expressions will be printed in a more\n\
25452 conversational style, when possible."),
25453                            NULL,
25454                            show_dwarf_always_disassemble,
25455                            &set_dwarf_cmdlist,
25456                            &show_dwarf_cmdlist);
25457
25458   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25459 Set debugging of the DWARF reader."), _("\
25460 Show debugging of the DWARF reader."), _("\
25461 When enabled (non-zero), debugging messages are printed during DWARF\n\
25462 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25463 information.  A value greater than 1 provides more verbose information."),
25464                             NULL,
25465                             NULL,
25466                             &setdebuglist, &showdebuglist);
25467
25468   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25469 Set debugging of the DWARF DIE reader."), _("\
25470 Show debugging of the DWARF DIE reader."), _("\
25471 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25472 The value is the maximum depth to print."),
25473                              NULL,
25474                              NULL,
25475                              &setdebuglist, &showdebuglist);
25476
25477   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25478 Set debugging of the dwarf line reader."), _("\
25479 Show debugging of the dwarf line reader."), _("\
25480 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25481 A value of 1 (one) provides basic information.\n\
25482 A value greater than 1 provides more verbose information."),
25483                              NULL,
25484                              NULL,
25485                              &setdebuglist, &showdebuglist);
25486
25487   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25488 Set cross-checking of \"physname\" code against demangler."), _("\
25489 Show cross-checking of \"physname\" code against demangler."), _("\
25490 When enabled, GDB's internal \"physname\" code is checked against\n\
25491 the demangler."),
25492                            NULL, show_check_physname,
25493                            &setdebuglist, &showdebuglist);
25494
25495   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25496                            no_class, &use_deprecated_index_sections, _("\
25497 Set whether to use deprecated gdb_index sections."), _("\
25498 Show whether to use deprecated gdb_index sections."), _("\
25499 When enabled, deprecated .gdb_index sections are used anyway.\n\
25500 Normally they are ignored either because of a missing feature or\n\
25501 performance issue.\n\
25502 Warning: This option must be enabled before gdb reads the file."),
25503                            NULL,
25504                            NULL,
25505                            &setlist, &showlist);
25506
25507   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25508                                                         &dwarf2_locexpr_funcs);
25509   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25510                                                         &dwarf2_loclist_funcs);
25511
25512   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25513                                         &dwarf2_block_frame_base_locexpr_funcs);
25514   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25515                                         &dwarf2_block_frame_base_loclist_funcs);
25516
25517 #if GDB_SELF_TEST
25518   selftests::register_test ("dw2_expand_symtabs_matching",
25519                             selftests::dw2_expand_symtabs_matching::run_test);
25520 #endif
25521 }