Automatic date update in version.in
[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 generic symbol table building routines have separate lists for
439      file scope symbols and all all other scopes (local scopes).  So
440      we need to select the right one to pass to add_symbol_to_list().
441      We do it by keeping a pointer to the correct list in list_in_scope.
442
443      FIXME: The original dwarf code just treated the file scope as the
444      first local scope, and all other local scopes as nested local
445      scopes, and worked fine.  Check to see if we really need to
446      distinguish these in buildsym.c.  */
447   struct pending **list_in_scope = nullptr;
448
449   /* Hash table holding all the loaded partial DIEs
450      with partial_die->offset.SECT_OFF as hash.  */
451   htab_t partial_dies = nullptr;
452
453   /* Storage for things with the same lifetime as this read-in compilation
454      unit, including partial DIEs.  */
455   auto_obstack comp_unit_obstack;
456
457   /* When multiple dwarf2_cu structures are living in memory, this field
458      chains them all together, so that they can be released efficiently.
459      We will probably also want a generation counter so that most-recently-used
460      compilation units are cached...  */
461   struct dwarf2_per_cu_data *read_in_chain = nullptr;
462
463   /* Backlink to our per_cu entry.  */
464   struct dwarf2_per_cu_data *per_cu;
465
466   /* How many compilation units ago was this CU last referenced?  */
467   int last_used = 0;
468
469   /* A hash table of DIE cu_offset for following references with
470      die_info->offset.sect_off as hash.  */
471   htab_t die_hash = nullptr;
472
473   /* Full DIEs if read in.  */
474   struct die_info *dies = nullptr;
475
476   /* A set of pointers to dwarf2_per_cu_data objects for compilation
477      units referenced by this one.  Only set during full symbol processing;
478      partial symbol tables do not have dependencies.  */
479   htab_t dependencies = nullptr;
480
481   /* Header data from the line table, during full symbol processing.  */
482   struct line_header *line_header = nullptr;
483   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
484      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
485      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
486      to the line header as long as this DIE is being processed.  See
487      process_die_scope.  */
488   die_info *line_header_die_owner = nullptr;
489
490   /* A list of methods which need to have physnames computed
491      after all type information has been read.  */
492   std::vector<delayed_method_info> method_list;
493
494   /* To be copied to symtab->call_site_htab.  */
495   htab_t call_site_htab = nullptr;
496
497   /* Non-NULL if this CU came from a DWO file.
498      There is an invariant here that is important to remember:
499      Except for attributes copied from the top level DIE in the "main"
500      (or "stub") file in preparation for reading the DWO file
501      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
502      Either there isn't a DWO file (in which case this is NULL and the point
503      is moot), or there is and either we're not going to read it (in which
504      case this is NULL) or there is and we are reading it (in which case this
505      is non-NULL).  */
506   struct dwo_unit *dwo_unit = nullptr;
507
508   /* The DW_AT_addr_base attribute if present, zero otherwise
509      (zero is a valid value though).
510      Note this value comes from the Fission stub CU/TU's DIE.  */
511   ULONGEST addr_base = 0;
512
513   /* The DW_AT_ranges_base attribute if present, zero otherwise
514      (zero is a valid value though).
515      Note this value comes from the Fission stub CU/TU's DIE.
516      Also note that the value is zero in the non-DWO case so this value can
517      be used without needing to know whether DWO files are in use or not.
518      N.B. This does not apply to DW_AT_ranges appearing in
519      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
520      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
521      DW_AT_ranges_base *would* have to be applied, and we'd have to care
522      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
523   ULONGEST ranges_base = 0;
524
525   /* When reading debug info generated by older versions of rustc, we
526      have to rewrite some union types to be struct types with a
527      variant part.  This rewriting must be done after the CU is fully
528      read in, because otherwise at the point of rewriting some struct
529      type might not have been fully processed.  So, we keep a list of
530      all such types here and process them after expansion.  */
531   std::vector<struct type *> rust_unions;
532
533   /* Mark used when releasing cached dies.  */
534   unsigned int mark : 1;
535
536   /* This CU references .debug_loc.  See the symtab->locations_valid field.
537      This test is imperfect as there may exist optimized debug code not using
538      any location list and still facing inlining issues if handled as
539      unoptimized code.  For a future better test see GCC PR other/32998.  */
540   unsigned int has_loclist : 1;
541
542   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
543      if all the producer_is_* fields are valid.  This information is cached
544      because profiling CU expansion showed excessive time spent in
545      producer_is_gxx_lt_4_6.  */
546   unsigned int checked_producer : 1;
547   unsigned int producer_is_gxx_lt_4_6 : 1;
548   unsigned int producer_is_gcc_lt_4_3 : 1;
549   unsigned int producer_is_icc_lt_14 : 1;
550
551   /* When set, the file that we're processing is known to have
552      debugging info for C++ namespaces.  GCC 3.3.x did not produce
553      this information, but later versions do.  */
554
555   unsigned int processing_has_namespace_info : 1;
556
557   struct partial_die_info *find_partial_die (sect_offset sect_off);
558 };
559
560 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
561    This includes type_unit_group and quick_file_names.  */
562
563 struct stmt_list_hash
564 {
565   /* The DWO unit this table is from or NULL if there is none.  */
566   struct dwo_unit *dwo_unit;
567
568   /* Offset in .debug_line or .debug_line.dwo.  */
569   sect_offset line_sect_off;
570 };
571
572 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
573    an object of this type.  */
574
575 struct type_unit_group
576 {
577   /* dwarf2read.c's main "handle" on a TU symtab.
578      To simplify things we create an artificial CU that "includes" all the
579      type units using this stmt_list so that the rest of the code still has
580      a "per_cu" handle on the symtab.
581      This PER_CU is recognized by having no section.  */
582 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
583   struct dwarf2_per_cu_data per_cu;
584
585   /* The TUs that share this DW_AT_stmt_list entry.
586      This is added to while parsing type units to build partial symtabs,
587      and is deleted afterwards and not used again.  */
588   VEC (sig_type_ptr) *tus;
589
590   /* The compunit symtab.
591      Type units in a group needn't all be defined in the same source file,
592      so we create an essentially anonymous symtab as the compunit symtab.  */
593   struct compunit_symtab *compunit_symtab;
594
595   /* The data used to construct the hash key.  */
596   struct stmt_list_hash hash;
597
598   /* The number of symtabs from the line header.
599      The value here must match line_header.num_file_names.  */
600   unsigned int num_symtabs;
601
602   /* The symbol tables for this TU (obtained from the files listed in
603      DW_AT_stmt_list).
604      WARNING: The order of entries here must match the order of entries
605      in the line header.  After the first TU using this type_unit_group, the
606      line header for the subsequent TUs is recreated from this.  This is done
607      because we need to use the same symtabs for each TU using the same
608      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
609      there's no guarantee the line header doesn't have duplicate entries.  */
610   struct symtab **symtabs;
611 };
612
613 /* These sections are what may appear in a (real or virtual) DWO file.  */
614
615 struct dwo_sections
616 {
617   struct dwarf2_section_info abbrev;
618   struct dwarf2_section_info line;
619   struct dwarf2_section_info loc;
620   struct dwarf2_section_info loclists;
621   struct dwarf2_section_info macinfo;
622   struct dwarf2_section_info macro;
623   struct dwarf2_section_info str;
624   struct dwarf2_section_info str_offsets;
625   /* In the case of a virtual DWO file, these two are unused.  */
626   struct dwarf2_section_info info;
627   VEC (dwarf2_section_info_def) *types;
628 };
629
630 /* CUs/TUs in DWP/DWO files.  */
631
632 struct dwo_unit
633 {
634   /* Backlink to the containing struct dwo_file.  */
635   struct dwo_file *dwo_file;
636
637   /* The "id" that distinguishes this CU/TU.
638      .debug_info calls this "dwo_id", .debug_types calls this "signature".
639      Since signatures came first, we stick with it for consistency.  */
640   ULONGEST signature;
641
642   /* The section this CU/TU lives in, in the DWO file.  */
643   struct dwarf2_section_info *section;
644
645   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
646   sect_offset sect_off;
647   unsigned int length;
648
649   /* For types, offset in the type's DIE of the type defined by this TU.  */
650   cu_offset type_offset_in_tu;
651 };
652
653 /* include/dwarf2.h defines the DWP section codes.
654    It defines a max value but it doesn't define a min value, which we
655    use for error checking, so provide one.  */
656
657 enum dwp_v2_section_ids
658 {
659   DW_SECT_MIN = 1
660 };
661
662 /* Data for one DWO file.
663
664    This includes virtual DWO files (a virtual DWO file is a DWO file as it
665    appears in a DWP file).  DWP files don't really have DWO files per se -
666    comdat folding of types "loses" the DWO file they came from, and from
667    a high level view DWP files appear to contain a mass of random types.
668    However, to maintain consistency with the non-DWP case we pretend DWP
669    files contain virtual DWO files, and we assign each TU with one virtual
670    DWO file (generally based on the line and abbrev section offsets -
671    a heuristic that seems to work in practice).  */
672
673 struct dwo_file
674 {
675   /* The DW_AT_GNU_dwo_name attribute.
676      For virtual DWO files the name is constructed from the section offsets
677      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
678      from related CU+TUs.  */
679   const char *dwo_name;
680
681   /* The DW_AT_comp_dir attribute.  */
682   const char *comp_dir;
683
684   /* The bfd, when the file is open.  Otherwise this is NULL.
685      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
686   bfd *dbfd;
687
688   /* The sections that make up this DWO file.
689      Remember that for virtual DWO files in DWP V2, these are virtual
690      sections (for lack of a better name).  */
691   struct dwo_sections sections;
692
693   /* The CUs in the file.
694      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
695      an extension to handle LLVM's Link Time Optimization output (where
696      multiple source files may be compiled into a single object/dwo pair). */
697   htab_t cus;
698
699   /* Table of TUs in the file.
700      Each element is a struct dwo_unit.  */
701   htab_t tus;
702 };
703
704 /* These sections are what may appear in a DWP file.  */
705
706 struct dwp_sections
707 {
708   /* These are used by both DWP version 1 and 2.  */
709   struct dwarf2_section_info str;
710   struct dwarf2_section_info cu_index;
711   struct dwarf2_section_info tu_index;
712
713   /* These are only used by DWP version 2 files.
714      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
715      sections are referenced by section number, and are not recorded here.
716      In DWP version 2 there is at most one copy of all these sections, each
717      section being (effectively) comprised of the concatenation of all of the
718      individual sections that exist in the version 1 format.
719      To keep the code simple we treat each of these concatenated pieces as a
720      section itself (a virtual section?).  */
721   struct dwarf2_section_info abbrev;
722   struct dwarf2_section_info info;
723   struct dwarf2_section_info line;
724   struct dwarf2_section_info loc;
725   struct dwarf2_section_info macinfo;
726   struct dwarf2_section_info macro;
727   struct dwarf2_section_info str_offsets;
728   struct dwarf2_section_info types;
729 };
730
731 /* These sections are what may appear in a virtual DWO file in DWP version 1.
732    A virtual DWO file is a DWO file as it appears in a DWP file.  */
733
734 struct virtual_v1_dwo_sections
735 {
736   struct dwarf2_section_info abbrev;
737   struct dwarf2_section_info line;
738   struct dwarf2_section_info loc;
739   struct dwarf2_section_info macinfo;
740   struct dwarf2_section_info macro;
741   struct dwarf2_section_info str_offsets;
742   /* Each DWP hash table entry records one CU or one TU.
743      That is recorded here, and copied to dwo_unit.section.  */
744   struct dwarf2_section_info info_or_types;
745 };
746
747 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
748    In version 2, the sections of the DWO files are concatenated together
749    and stored in one section of that name.  Thus each ELF section contains
750    several "virtual" sections.  */
751
752 struct virtual_v2_dwo_sections
753 {
754   bfd_size_type abbrev_offset;
755   bfd_size_type abbrev_size;
756
757   bfd_size_type line_offset;
758   bfd_size_type line_size;
759
760   bfd_size_type loc_offset;
761   bfd_size_type loc_size;
762
763   bfd_size_type macinfo_offset;
764   bfd_size_type macinfo_size;
765
766   bfd_size_type macro_offset;
767   bfd_size_type macro_size;
768
769   bfd_size_type str_offsets_offset;
770   bfd_size_type str_offsets_size;
771
772   /* Each DWP hash table entry records one CU or one TU.
773      That is recorded here, and copied to dwo_unit.section.  */
774   bfd_size_type info_or_types_offset;
775   bfd_size_type info_or_types_size;
776 };
777
778 /* Contents of DWP hash tables.  */
779
780 struct dwp_hash_table
781 {
782   uint32_t version, nr_columns;
783   uint32_t nr_units, nr_slots;
784   const gdb_byte *hash_table, *unit_table;
785   union
786   {
787     struct
788     {
789       const gdb_byte *indices;
790     } v1;
791     struct
792     {
793       /* This is indexed by column number and gives the id of the section
794          in that column.  */
795 #define MAX_NR_V2_DWO_SECTIONS \
796   (1 /* .debug_info or .debug_types */ \
797    + 1 /* .debug_abbrev */ \
798    + 1 /* .debug_line */ \
799    + 1 /* .debug_loc */ \
800    + 1 /* .debug_str_offsets */ \
801    + 1 /* .debug_macro or .debug_macinfo */)
802       int section_ids[MAX_NR_V2_DWO_SECTIONS];
803       const gdb_byte *offsets;
804       const gdb_byte *sizes;
805     } v2;
806   } section_pool;
807 };
808
809 /* Data for one DWP file.  */
810
811 struct dwp_file
812 {
813   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
814     : name (name_),
815       dbfd (std::move (abfd))
816   {
817   }
818
819   /* Name of the file.  */
820   const char *name;
821
822   /* File format version.  */
823   int version = 0;
824
825   /* The bfd.  */
826   gdb_bfd_ref_ptr dbfd;
827
828   /* Section info for this file.  */
829   struct dwp_sections sections {};
830
831   /* Table of CUs in the file.  */
832   const struct dwp_hash_table *cus = nullptr;
833
834   /* Table of TUs in the file.  */
835   const struct dwp_hash_table *tus = nullptr;
836
837   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
838   htab_t loaded_cus {};
839   htab_t loaded_tus {};
840
841   /* Table to map ELF section numbers to their sections.
842      This is only needed for the DWP V1 file format.  */
843   unsigned int num_sections = 0;
844   asection **elf_sections = nullptr;
845 };
846
847 /* This represents a '.dwz' file.  */
848
849 struct dwz_file
850 {
851   dwz_file (gdb_bfd_ref_ptr &&bfd)
852     : dwz_bfd (std::move (bfd))
853   {
854   }
855
856   /* A dwz file can only contain a few sections.  */
857   struct dwarf2_section_info abbrev {};
858   struct dwarf2_section_info info {};
859   struct dwarf2_section_info str {};
860   struct dwarf2_section_info line {};
861   struct dwarf2_section_info macro {};
862   struct dwarf2_section_info gdb_index {};
863   struct dwarf2_section_info debug_names {};
864
865   /* The dwz's BFD.  */
866   gdb_bfd_ref_ptr dwz_bfd;
867 };
868
869 /* Struct used to pass misc. parameters to read_die_and_children, et
870    al.  which are used for both .debug_info and .debug_types dies.
871    All parameters here are unchanging for the life of the call.  This
872    struct exists to abstract away the constant parameters of die reading.  */
873
874 struct die_reader_specs
875 {
876   /* The bfd of die_section.  */
877   bfd* abfd;
878
879   /* The CU of the DIE we are parsing.  */
880   struct dwarf2_cu *cu;
881
882   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
883   struct dwo_file *dwo_file;
884
885   /* The section the die comes from.
886      This is either .debug_info or .debug_types, or the .dwo variants.  */
887   struct dwarf2_section_info *die_section;
888
889   /* die_section->buffer.  */
890   const gdb_byte *buffer;
891
892   /* The end of the buffer.  */
893   const gdb_byte *buffer_end;
894
895   /* The value of the DW_AT_comp_dir attribute.  */
896   const char *comp_dir;
897
898   /* The abbreviation table to use when reading the DIEs.  */
899   struct abbrev_table *abbrev_table;
900 };
901
902 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
903 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
904                                       const gdb_byte *info_ptr,
905                                       struct die_info *comp_unit_die,
906                                       int has_children,
907                                       void *data);
908
909 /* A 1-based directory index.  This is a strong typedef to prevent
910    accidentally using a directory index as a 0-based index into an
911    array/vector.  */
912 enum class dir_index : unsigned int {};
913
914 /* Likewise, a 1-based file name index.  */
915 enum class file_name_index : unsigned int {};
916
917 struct file_entry
918 {
919   file_entry () = default;
920
921   file_entry (const char *name_, dir_index d_index_,
922               unsigned int mod_time_, unsigned int length_)
923     : name (name_),
924       d_index (d_index_),
925       mod_time (mod_time_),
926       length (length_)
927   {}
928
929   /* Return the include directory at D_INDEX stored in LH.  Returns
930      NULL if D_INDEX is out of bounds.  */
931   const char *include_dir (const line_header *lh) const;
932
933   /* The file name.  Note this is an observing pointer.  The memory is
934      owned by debug_line_buffer.  */
935   const char *name {};
936
937   /* The directory index (1-based).  */
938   dir_index d_index {};
939
940   unsigned int mod_time {};
941
942   unsigned int length {};
943
944   /* True if referenced by the Line Number Program.  */
945   bool included_p {};
946
947   /* The associated symbol table, if any.  */
948   struct symtab *symtab {};
949 };
950
951 /* The line number information for a compilation unit (found in the
952    .debug_line section) begins with a "statement program header",
953    which contains the following information.  */
954 struct line_header
955 {
956   line_header ()
957     : offset_in_dwz {}
958   {}
959
960   /* Add an entry to the include directory table.  */
961   void add_include_dir (const char *include_dir);
962
963   /* Add an entry to the file name table.  */
964   void add_file_name (const char *name, dir_index d_index,
965                       unsigned int mod_time, unsigned int length);
966
967   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
968      is out of bounds.  */
969   const char *include_dir_at (dir_index index) const
970   {
971     /* Convert directory index number (1-based) to vector index
972        (0-based).  */
973     size_t vec_index = to_underlying (index) - 1;
974
975     if (vec_index >= include_dirs.size ())
976       return NULL;
977     return include_dirs[vec_index];
978   }
979
980   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
981      is out of bounds.  */
982   file_entry *file_name_at (file_name_index index)
983   {
984     /* Convert file name index number (1-based) to vector index
985        (0-based).  */
986     size_t vec_index = to_underlying (index) - 1;
987
988     if (vec_index >= file_names.size ())
989       return NULL;
990     return &file_names[vec_index];
991   }
992
993   /* Const version of the above.  */
994   const file_entry *file_name_at (unsigned int index) const
995   {
996     if (index >= file_names.size ())
997       return NULL;
998     return &file_names[index];
999   }
1000
1001   /* Offset of line number information in .debug_line section.  */
1002   sect_offset sect_off {};
1003
1004   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1005   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1006
1007   unsigned int total_length {};
1008   unsigned short version {};
1009   unsigned int header_length {};
1010   unsigned char minimum_instruction_length {};
1011   unsigned char maximum_ops_per_instruction {};
1012   unsigned char default_is_stmt {};
1013   int line_base {};
1014   unsigned char line_range {};
1015   unsigned char opcode_base {};
1016
1017   /* standard_opcode_lengths[i] is the number of operands for the
1018      standard opcode whose value is i.  This means that
1019      standard_opcode_lengths[0] is unused, and the last meaningful
1020      element is standard_opcode_lengths[opcode_base - 1].  */
1021   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1022
1023   /* The include_directories table.  Note these are observing
1024      pointers.  The memory is owned by debug_line_buffer.  */
1025   std::vector<const char *> include_dirs;
1026
1027   /* The file_names table.  */
1028   std::vector<file_entry> file_names;
1029
1030   /* The start and end of the statement program following this
1031      header.  These point into dwarf2_per_objfile->line_buffer.  */
1032   const gdb_byte *statement_program_start {}, *statement_program_end {};
1033 };
1034
1035 typedef std::unique_ptr<line_header> line_header_up;
1036
1037 const char *
1038 file_entry::include_dir (const line_header *lh) const
1039 {
1040   return lh->include_dir_at (d_index);
1041 }
1042
1043 /* When we construct a partial symbol table entry we only
1044    need this much information.  */
1045 struct partial_die_info : public allocate_on_obstack
1046   {
1047     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1048
1049     /* Disable assign but still keep copy ctor, which is needed
1050        load_partial_dies.   */
1051     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1052
1053     /* Adjust the partial die before generating a symbol for it.  This
1054        function may set the is_external flag or change the DIE's
1055        name.  */
1056     void fixup (struct dwarf2_cu *cu);
1057
1058     /* Read a minimal amount of information into the minimal die
1059        structure.  */
1060     const gdb_byte *read (const struct die_reader_specs *reader,
1061                           const struct abbrev_info &abbrev,
1062                           const gdb_byte *info_ptr);
1063
1064     /* Offset of this DIE.  */
1065     const sect_offset sect_off;
1066
1067     /* DWARF-2 tag for this DIE.  */
1068     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1069
1070     /* Assorted flags describing the data found in this DIE.  */
1071     const unsigned int has_children : 1;
1072
1073     unsigned int is_external : 1;
1074     unsigned int is_declaration : 1;
1075     unsigned int has_type : 1;
1076     unsigned int has_specification : 1;
1077     unsigned int has_pc_info : 1;
1078     unsigned int may_be_inlined : 1;
1079
1080     /* This DIE has been marked DW_AT_main_subprogram.  */
1081     unsigned int main_subprogram : 1;
1082
1083     /* Flag set if the SCOPE field of this structure has been
1084        computed.  */
1085     unsigned int scope_set : 1;
1086
1087     /* Flag set if the DIE has a byte_size attribute.  */
1088     unsigned int has_byte_size : 1;
1089
1090     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1091     unsigned int has_const_value : 1;
1092
1093     /* Flag set if any of the DIE's children are template arguments.  */
1094     unsigned int has_template_arguments : 1;
1095
1096     /* Flag set if fixup has been called on this die.  */
1097     unsigned int fixup_called : 1;
1098
1099     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1100     unsigned int is_dwz : 1;
1101
1102     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1103     unsigned int spec_is_dwz : 1;
1104
1105     /* The name of this DIE.  Normally the value of DW_AT_name, but
1106        sometimes a default name for unnamed DIEs.  */
1107     const char *name = nullptr;
1108
1109     /* The linkage name, if present.  */
1110     const char *linkage_name = nullptr;
1111
1112     /* The scope to prepend to our children.  This is generally
1113        allocated on the comp_unit_obstack, so will disappear
1114        when this compilation unit leaves the cache.  */
1115     const char *scope = nullptr;
1116
1117     /* Some data associated with the partial DIE.  The tag determines
1118        which field is live.  */
1119     union
1120     {
1121       /* The location description associated with this DIE, if any.  */
1122       struct dwarf_block *locdesc;
1123       /* The offset of an import, for DW_TAG_imported_unit.  */
1124       sect_offset sect_off;
1125     } d {};
1126
1127     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1128     CORE_ADDR lowpc = 0;
1129     CORE_ADDR highpc = 0;
1130
1131     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1132        DW_AT_sibling, if any.  */
1133     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1134        could return DW_AT_sibling values to its caller load_partial_dies.  */
1135     const gdb_byte *sibling = nullptr;
1136
1137     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1138        DW_AT_specification (or DW_AT_abstract_origin or
1139        DW_AT_extension).  */
1140     sect_offset spec_offset {};
1141
1142     /* Pointers to this DIE's parent, first child, and next sibling,
1143        if any.  */
1144     struct partial_die_info *die_parent = nullptr;
1145     struct partial_die_info *die_child = nullptr;
1146     struct partial_die_info *die_sibling = nullptr;
1147
1148     friend struct partial_die_info *
1149     dwarf2_cu::find_partial_die (sect_offset sect_off);
1150
1151   private:
1152     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1153     partial_die_info (sect_offset sect_off)
1154       : partial_die_info (sect_off, DW_TAG_padding, 0)
1155     {
1156     }
1157
1158     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1159                       int has_children_)
1160       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1161     {
1162       is_external = 0;
1163       is_declaration = 0;
1164       has_type = 0;
1165       has_specification = 0;
1166       has_pc_info = 0;
1167       may_be_inlined = 0;
1168       main_subprogram = 0;
1169       scope_set = 0;
1170       has_byte_size = 0;
1171       has_const_value = 0;
1172       has_template_arguments = 0;
1173       fixup_called = 0;
1174       is_dwz = 0;
1175       spec_is_dwz = 0;
1176     }
1177   };
1178
1179 /* This data structure holds the information of an abbrev.  */
1180 struct abbrev_info
1181   {
1182     unsigned int number;        /* number identifying abbrev */
1183     enum dwarf_tag tag;         /* dwarf tag */
1184     unsigned short has_children;                /* boolean */
1185     unsigned short num_attrs;   /* number of attributes */
1186     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1187     struct abbrev_info *next;   /* next in chain */
1188   };
1189
1190 struct attr_abbrev
1191   {
1192     ENUM_BITFIELD(dwarf_attribute) name : 16;
1193     ENUM_BITFIELD(dwarf_form) form : 16;
1194
1195     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1196     LONGEST implicit_const;
1197   };
1198
1199 /* Size of abbrev_table.abbrev_hash_table.  */
1200 #define ABBREV_HASH_SIZE 121
1201
1202 /* Top level data structure to contain an abbreviation table.  */
1203
1204 struct abbrev_table
1205 {
1206   explicit abbrev_table (sect_offset off)
1207     : sect_off (off)
1208   {
1209     m_abbrevs =
1210       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1211     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1212   }
1213
1214   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1215
1216   /* Allocate space for a struct abbrev_info object in
1217      ABBREV_TABLE.  */
1218   struct abbrev_info *alloc_abbrev ();
1219
1220   /* Add an abbreviation to the table.  */
1221   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1222
1223   /* Look up an abbrev in the table.
1224      Returns NULL if the abbrev is not found.  */
1225
1226   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1227
1228
1229   /* Where the abbrev table came from.
1230      This is used as a sanity check when the table is used.  */
1231   const sect_offset sect_off;
1232
1233   /* Storage for the abbrev table.  */
1234   auto_obstack abbrev_obstack;
1235
1236 private:
1237
1238   /* Hash table of abbrevs.
1239      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1240      It could be statically allocated, but the previous code didn't so we
1241      don't either.  */
1242   struct abbrev_info **m_abbrevs;
1243 };
1244
1245 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1246
1247 /* Attributes have a name and a value.  */
1248 struct attribute
1249   {
1250     ENUM_BITFIELD(dwarf_attribute) name : 16;
1251     ENUM_BITFIELD(dwarf_form) form : 15;
1252
1253     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1254        field should be in u.str (existing only for DW_STRING) but it is kept
1255        here for better struct attribute alignment.  */
1256     unsigned int string_is_canonical : 1;
1257
1258     union
1259       {
1260         const char *str;
1261         struct dwarf_block *blk;
1262         ULONGEST unsnd;
1263         LONGEST snd;
1264         CORE_ADDR addr;
1265         ULONGEST signature;
1266       }
1267     u;
1268   };
1269
1270 /* This data structure holds a complete die structure.  */
1271 struct die_info
1272   {
1273     /* DWARF-2 tag for this DIE.  */
1274     ENUM_BITFIELD(dwarf_tag) tag : 16;
1275
1276     /* Number of attributes */
1277     unsigned char num_attrs;
1278
1279     /* True if we're presently building the full type name for the
1280        type derived from this DIE.  */
1281     unsigned char building_fullname : 1;
1282
1283     /* True if this die is in process.  PR 16581.  */
1284     unsigned char in_process : 1;
1285
1286     /* Abbrev number */
1287     unsigned int abbrev;
1288
1289     /* Offset in .debug_info or .debug_types section.  */
1290     sect_offset sect_off;
1291
1292     /* The dies in a compilation unit form an n-ary tree.  PARENT
1293        points to this die's parent; CHILD points to the first child of
1294        this node; and all the children of a given node are chained
1295        together via their SIBLING fields.  */
1296     struct die_info *child;     /* Its first child, if any.  */
1297     struct die_info *sibling;   /* Its next sibling, if any.  */
1298     struct die_info *parent;    /* Its parent, if any.  */
1299
1300     /* An array of attributes, with NUM_ATTRS elements.  There may be
1301        zero, but it's not common and zero-sized arrays are not
1302        sufficiently portable C.  */
1303     struct attribute attrs[1];
1304   };
1305
1306 /* Get at parts of an attribute structure.  */
1307
1308 #define DW_STRING(attr)    ((attr)->u.str)
1309 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1310 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1311 #define DW_BLOCK(attr)     ((attr)->u.blk)
1312 #define DW_SND(attr)       ((attr)->u.snd)
1313 #define DW_ADDR(attr)      ((attr)->u.addr)
1314 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1315
1316 /* Blocks are a bunch of untyped bytes.  */
1317 struct dwarf_block
1318   {
1319     size_t size;
1320
1321     /* Valid only if SIZE is not zero.  */
1322     const gdb_byte *data;
1323   };
1324
1325 #ifndef ATTR_ALLOC_CHUNK
1326 #define ATTR_ALLOC_CHUNK 4
1327 #endif
1328
1329 /* Allocate fields for structs, unions and enums in this size.  */
1330 #ifndef DW_FIELD_ALLOC_CHUNK
1331 #define DW_FIELD_ALLOC_CHUNK 4
1332 #endif
1333
1334 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1335    but this would require a corresponding change in unpack_field_as_long
1336    and friends.  */
1337 static int bits_per_byte = 8;
1338
1339 /* When reading a variant or variant part, we track a bit more
1340    information about the field, and store it in an object of this
1341    type.  */
1342
1343 struct variant_field
1344 {
1345   /* If we see a DW_TAG_variant, then this will be the discriminant
1346      value.  */
1347   ULONGEST discriminant_value;
1348   /* If we see a DW_TAG_variant, then this will be set if this is the
1349      default branch.  */
1350   bool default_branch;
1351   /* While reading a DW_TAG_variant_part, this will be set if this
1352      field is the discriminant.  */
1353   bool is_discriminant;
1354 };
1355
1356 struct nextfield
1357 {
1358   int accessibility = 0;
1359   int virtuality = 0;
1360   /* Extra information to describe a variant or variant part.  */
1361   struct variant_field variant {};
1362   struct field field {};
1363 };
1364
1365 struct fnfieldlist
1366 {
1367   const char *name = nullptr;
1368   std::vector<struct fn_field> fnfields;
1369 };
1370
1371 /* The routines that read and process dies for a C struct or C++ class
1372    pass lists of data member fields and lists of member function fields
1373    in an instance of a field_info structure, as defined below.  */
1374 struct field_info
1375   {
1376     /* List of data member and baseclasses fields.  */
1377     std::vector<struct nextfield> fields;
1378     std::vector<struct nextfield> baseclasses;
1379
1380     /* Number of fields (including baseclasses).  */
1381     int nfields = 0;
1382
1383     /* Set if the accesibility of one of the fields is not public.  */
1384     int non_public_fields = 0;
1385
1386     /* Member function fieldlist array, contains name of possibly overloaded
1387        member function, number of overloaded member functions and a pointer
1388        to the head of the member function field chain.  */
1389     std::vector<struct fnfieldlist> fnfieldlists;
1390
1391     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1392        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1393     std::vector<struct decl_field> typedef_field_list;
1394
1395     /* Nested types defined by this class and the number of elements in this
1396        list.  */
1397     std::vector<struct decl_field> nested_types_list;
1398   };
1399
1400 /* One item on the queue of compilation units to read in full symbols
1401    for.  */
1402 struct dwarf2_queue_item
1403 {
1404   struct dwarf2_per_cu_data *per_cu;
1405   enum language pretend_language;
1406   struct dwarf2_queue_item *next;
1407 };
1408
1409 /* The current queue.  */
1410 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1411
1412 /* Loaded secondary compilation units are kept in memory until they
1413    have not been referenced for the processing of this many
1414    compilation units.  Set this to zero to disable caching.  Cache
1415    sizes of up to at least twenty will improve startup time for
1416    typical inter-CU-reference binaries, at an obvious memory cost.  */
1417 static int dwarf_max_cache_age = 5;
1418 static void
1419 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1420                           struct cmd_list_element *c, const char *value)
1421 {
1422   fprintf_filtered (file, _("The upper bound on the age of cached "
1423                             "DWARF compilation units is %s.\n"),
1424                     value);
1425 }
1426 \f
1427 /* local function prototypes */
1428
1429 static const char *get_section_name (const struct dwarf2_section_info *);
1430
1431 static const char *get_section_file_name (const struct dwarf2_section_info *);
1432
1433 static void dwarf2_find_base_address (struct die_info *die,
1434                                       struct dwarf2_cu *cu);
1435
1436 static struct partial_symtab *create_partial_symtab
1437   (struct dwarf2_per_cu_data *per_cu, const char *name);
1438
1439 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1440                                         const gdb_byte *info_ptr,
1441                                         struct die_info *type_unit_die,
1442                                         int has_children, void *data);
1443
1444 static void dwarf2_build_psymtabs_hard
1445   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1446
1447 static void scan_partial_symbols (struct partial_die_info *,
1448                                   CORE_ADDR *, CORE_ADDR *,
1449                                   int, struct dwarf2_cu *);
1450
1451 static void add_partial_symbol (struct partial_die_info *,
1452                                 struct dwarf2_cu *);
1453
1454 static void add_partial_namespace (struct partial_die_info *pdi,
1455                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1456                                    int set_addrmap, struct dwarf2_cu *cu);
1457
1458 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1459                                 CORE_ADDR *highpc, int set_addrmap,
1460                                 struct dwarf2_cu *cu);
1461
1462 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1463                                      struct dwarf2_cu *cu);
1464
1465 static void add_partial_subprogram (struct partial_die_info *pdi,
1466                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1467                                     int need_pc, struct dwarf2_cu *cu);
1468
1469 static void dwarf2_read_symtab (struct partial_symtab *,
1470                                 struct objfile *);
1471
1472 static void psymtab_to_symtab_1 (struct partial_symtab *);
1473
1474 static abbrev_table_up abbrev_table_read_table
1475   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1476    sect_offset);
1477
1478 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1479
1480 static struct partial_die_info *load_partial_dies
1481   (const struct die_reader_specs *, const gdb_byte *, int);
1482
1483 static struct partial_die_info *find_partial_die (sect_offset, int,
1484                                                   struct dwarf2_cu *);
1485
1486 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1487                                        struct attribute *, struct attr_abbrev *,
1488                                        const gdb_byte *);
1489
1490 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1491
1492 static int read_1_signed_byte (bfd *, const gdb_byte *);
1493
1494 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1495
1496 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1497
1498 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1499
1500 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1501                                unsigned int *);
1502
1503 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1504
1505 static LONGEST read_checked_initial_length_and_offset
1506   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1507    unsigned int *, unsigned int *);
1508
1509 static LONGEST read_offset (bfd *, const gdb_byte *,
1510                             const struct comp_unit_head *,
1511                             unsigned int *);
1512
1513 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1514
1515 static sect_offset read_abbrev_offset
1516   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1517    struct dwarf2_section_info *, sect_offset);
1518
1519 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1520
1521 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1522
1523 static const char *read_indirect_string
1524   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1525    const struct comp_unit_head *, unsigned int *);
1526
1527 static const char *read_indirect_line_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_string_at_offset
1532   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1533    LONGEST str_offset);
1534
1535 static const char *read_indirect_string_from_dwz
1536   (struct objfile *objfile, struct dwz_file *, LONGEST);
1537
1538 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1539
1540 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1541                                               const gdb_byte *,
1542                                               unsigned int *);
1543
1544 static const char *read_str_index (const struct die_reader_specs *reader,
1545                                    ULONGEST str_index);
1546
1547 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1548
1549 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1550                                       struct dwarf2_cu *);
1551
1552 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1553                                                 unsigned int);
1554
1555 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1556                                        struct dwarf2_cu *cu);
1557
1558 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1559                                struct dwarf2_cu *cu);
1560
1561 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1562
1563 static struct die_info *die_specification (struct die_info *die,
1564                                            struct dwarf2_cu **);
1565
1566 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1567                                                 struct dwarf2_cu *cu);
1568
1569 static void dwarf_decode_lines (struct line_header *, const char *,
1570                                 struct dwarf2_cu *, struct partial_symtab *,
1571                                 CORE_ADDR, int decode_mapping);
1572
1573 static void dwarf2_start_subfile (const char *, const char *);
1574
1575 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1576                                                     const char *, const char *,
1577                                                     CORE_ADDR);
1578
1579 static struct symbol *new_symbol (struct die_info *, struct type *,
1580                                   struct dwarf2_cu *, struct symbol * = NULL);
1581
1582 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1583                                 struct dwarf2_cu *);
1584
1585 static void dwarf2_const_value_attr (const struct attribute *attr,
1586                                      struct type *type,
1587                                      const char *name,
1588                                      struct obstack *obstack,
1589                                      struct dwarf2_cu *cu, LONGEST *value,
1590                                      const gdb_byte **bytes,
1591                                      struct dwarf2_locexpr_baton **baton);
1592
1593 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1594
1595 static int need_gnat_info (struct dwarf2_cu *);
1596
1597 static struct type *die_descriptive_type (struct die_info *,
1598                                           struct dwarf2_cu *);
1599
1600 static void set_descriptive_type (struct type *, struct die_info *,
1601                                   struct dwarf2_cu *);
1602
1603 static struct type *die_containing_type (struct die_info *,
1604                                          struct dwarf2_cu *);
1605
1606 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1607                                      struct dwarf2_cu *);
1608
1609 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1610
1611 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1612
1613 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1614
1615 static char *typename_concat (struct obstack *obs, const char *prefix,
1616                               const char *suffix, int physname,
1617                               struct dwarf2_cu *cu);
1618
1619 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1620
1621 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1622
1623 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1624
1625 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1626
1627 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1628
1629 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1630
1631 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1632                                struct dwarf2_cu *, struct partial_symtab *);
1633
1634 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1635    values.  Keep the items ordered with increasing constraints compliance.  */
1636 enum pc_bounds_kind
1637 {
1638   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1639   PC_BOUNDS_NOT_PRESENT,
1640
1641   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1642      were present but they do not form a valid range of PC addresses.  */
1643   PC_BOUNDS_INVALID,
1644
1645   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1646   PC_BOUNDS_RANGES,
1647
1648   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1649   PC_BOUNDS_HIGH_LOW,
1650 };
1651
1652 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1653                                                  CORE_ADDR *, CORE_ADDR *,
1654                                                  struct dwarf2_cu *,
1655                                                  struct partial_symtab *);
1656
1657 static void get_scope_pc_bounds (struct die_info *,
1658                                  CORE_ADDR *, CORE_ADDR *,
1659                                  struct dwarf2_cu *);
1660
1661 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1662                                         CORE_ADDR, struct dwarf2_cu *);
1663
1664 static void dwarf2_add_field (struct field_info *, struct die_info *,
1665                               struct dwarf2_cu *);
1666
1667 static void dwarf2_attach_fields_to_type (struct field_info *,
1668                                           struct type *, struct dwarf2_cu *);
1669
1670 static void dwarf2_add_member_fn (struct field_info *,
1671                                   struct die_info *, struct type *,
1672                                   struct dwarf2_cu *);
1673
1674 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1675                                              struct type *,
1676                                              struct dwarf2_cu *);
1677
1678 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1679
1680 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1681
1682 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1683
1684 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1685
1686 static struct using_direct **using_directives (enum language);
1687
1688 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1689
1690 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1691
1692 static struct type *read_module_type (struct die_info *die,
1693                                       struct dwarf2_cu *cu);
1694
1695 static const char *namespace_name (struct die_info *die,
1696                                    int *is_anonymous, struct dwarf2_cu *);
1697
1698 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1699
1700 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1701
1702 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1703                                                        struct dwarf2_cu *);
1704
1705 static struct die_info *read_die_and_siblings_1
1706   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1707    struct die_info *);
1708
1709 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1710                                                const gdb_byte *info_ptr,
1711                                                const gdb_byte **new_info_ptr,
1712                                                struct die_info *parent);
1713
1714 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1715                                         struct die_info **, const gdb_byte *,
1716                                         int *, int);
1717
1718 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1719                                       struct die_info **, const gdb_byte *,
1720                                       int *);
1721
1722 static void process_die (struct die_info *, struct dwarf2_cu *);
1723
1724 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1725                                              struct obstack *);
1726
1727 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1728
1729 static const char *dwarf2_full_name (const char *name,
1730                                      struct die_info *die,
1731                                      struct dwarf2_cu *cu);
1732
1733 static const char *dwarf2_physname (const char *name, struct die_info *die,
1734                                     struct dwarf2_cu *cu);
1735
1736 static struct die_info *dwarf2_extension (struct die_info *die,
1737                                           struct dwarf2_cu **);
1738
1739 static const char *dwarf_tag_name (unsigned int);
1740
1741 static const char *dwarf_attr_name (unsigned int);
1742
1743 static const char *dwarf_form_name (unsigned int);
1744
1745 static const char *dwarf_bool_name (unsigned int);
1746
1747 static const char *dwarf_type_encoding_name (unsigned int);
1748
1749 static struct die_info *sibling_die (struct die_info *);
1750
1751 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1752
1753 static void dump_die_for_error (struct die_info *);
1754
1755 static void dump_die_1 (struct ui_file *, int level, int max_level,
1756                         struct die_info *);
1757
1758 /*static*/ void dump_die (struct die_info *, int max_level);
1759
1760 static void store_in_ref_table (struct die_info *,
1761                                 struct dwarf2_cu *);
1762
1763 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1764
1765 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1766
1767 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1768                                                const struct attribute *,
1769                                                struct dwarf2_cu **);
1770
1771 static struct die_info *follow_die_ref (struct die_info *,
1772                                         const struct attribute *,
1773                                         struct dwarf2_cu **);
1774
1775 static struct die_info *follow_die_sig (struct die_info *,
1776                                         const struct attribute *,
1777                                         struct dwarf2_cu **);
1778
1779 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1780                                          struct dwarf2_cu *);
1781
1782 static struct type *get_DW_AT_signature_type (struct die_info *,
1783                                               const struct attribute *,
1784                                               struct dwarf2_cu *);
1785
1786 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1787
1788 static void read_signatured_type (struct signatured_type *);
1789
1790 static int attr_to_dynamic_prop (const struct attribute *attr,
1791                                  struct die_info *die, struct dwarf2_cu *cu,
1792                                  struct dynamic_prop *prop);
1793
1794 /* memory allocation interface */
1795
1796 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1797
1798 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1799
1800 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1801
1802 static int attr_form_is_block (const struct attribute *);
1803
1804 static int attr_form_is_section_offset (const struct attribute *);
1805
1806 static int attr_form_is_constant (const struct attribute *);
1807
1808 static int attr_form_is_ref (const struct attribute *);
1809
1810 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1811                                    struct dwarf2_loclist_baton *baton,
1812                                    const struct attribute *attr);
1813
1814 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1815                                          struct symbol *sym,
1816                                          struct dwarf2_cu *cu,
1817                                          int is_block);
1818
1819 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1820                                      const gdb_byte *info_ptr,
1821                                      struct abbrev_info *abbrev);
1822
1823 static hashval_t partial_die_hash (const void *item);
1824
1825 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1826
1827 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1828   (sect_offset sect_off, unsigned int offset_in_dwz,
1829    struct dwarf2_per_objfile *dwarf2_per_objfile);
1830
1831 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1832                                    struct die_info *comp_unit_die,
1833                                    enum language pretend_language);
1834
1835 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1836
1837 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1838
1839 static struct type *set_die_type (struct die_info *, struct type *,
1840                                   struct dwarf2_cu *);
1841
1842 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1843
1844 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1845
1846 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1847                                  enum language);
1848
1849 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1850                                     enum language);
1851
1852 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1853                                     enum language);
1854
1855 static void dwarf2_add_dependence (struct dwarf2_cu *,
1856                                    struct dwarf2_per_cu_data *);
1857
1858 static void dwarf2_mark (struct dwarf2_cu *);
1859
1860 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1861
1862 static struct type *get_die_type_at_offset (sect_offset,
1863                                             struct dwarf2_per_cu_data *);
1864
1865 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1866
1867 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1868                              enum language pretend_language);
1869
1870 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1871
1872 /* Class, the destructor of which frees all allocated queue entries.  This
1873    will only have work to do if an error was thrown while processing the
1874    dwarf.  If no error was thrown then the queue entries should have all
1875    been processed, and freed, as we went along.  */
1876
1877 class dwarf2_queue_guard
1878 {
1879 public:
1880   dwarf2_queue_guard () = default;
1881
1882   /* Free any entries remaining on the queue.  There should only be
1883      entries left if we hit an error while processing the dwarf.  */
1884   ~dwarf2_queue_guard ()
1885   {
1886     struct dwarf2_queue_item *item, *last;
1887
1888     item = dwarf2_queue;
1889     while (item)
1890       {
1891         /* Anything still marked queued is likely to be in an
1892            inconsistent state, so discard it.  */
1893         if (item->per_cu->queued)
1894           {
1895             if (item->per_cu->cu != NULL)
1896               free_one_cached_comp_unit (item->per_cu);
1897             item->per_cu->queued = 0;
1898           }
1899
1900         last = item;
1901         item = item->next;
1902         xfree (last);
1903       }
1904
1905     dwarf2_queue = dwarf2_queue_tail = NULL;
1906   }
1907 };
1908
1909 /* The return type of find_file_and_directory.  Note, the enclosed
1910    string pointers are only valid while this object is valid.  */
1911
1912 struct file_and_directory
1913 {
1914   /* The filename.  This is never NULL.  */
1915   const char *name;
1916
1917   /* The compilation directory.  NULL if not known.  If we needed to
1918      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1919      points directly to the DW_AT_comp_dir string attribute owned by
1920      the obstack that owns the DIE.  */
1921   const char *comp_dir;
1922
1923   /* If we needed to build a new string for comp_dir, this is what
1924      owns the storage.  */
1925   std::string comp_dir_storage;
1926 };
1927
1928 static file_and_directory find_file_and_directory (struct die_info *die,
1929                                                    struct dwarf2_cu *cu);
1930
1931 static char *file_full_name (int file, struct line_header *lh,
1932                              const char *comp_dir);
1933
1934 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1935 enum class rcuh_kind { COMPILE, TYPE };
1936
1937 static const gdb_byte *read_and_check_comp_unit_head
1938   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1939    struct comp_unit_head *header,
1940    struct dwarf2_section_info *section,
1941    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1942    rcuh_kind section_kind);
1943
1944 static void init_cutu_and_read_dies
1945   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1946    int use_existing_cu, int keep, bool skip_partial,
1947    die_reader_func_ftype *die_reader_func, void *data);
1948
1949 static void init_cutu_and_read_dies_simple
1950   (struct dwarf2_per_cu_data *this_cu,
1951    die_reader_func_ftype *die_reader_func, void *data);
1952
1953 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1954
1955 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1956
1957 static struct dwo_unit *lookup_dwo_unit_in_dwp
1958   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1959    struct dwp_file *dwp_file, const char *comp_dir,
1960    ULONGEST signature, int is_debug_types);
1961
1962 static struct dwp_file *get_dwp_file
1963   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1964
1965 static struct dwo_unit *lookup_dwo_comp_unit
1966   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1967
1968 static struct dwo_unit *lookup_dwo_type_unit
1969   (struct signatured_type *, const char *, const char *);
1970
1971 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1972
1973 static void free_dwo_file (struct dwo_file *);
1974
1975 /* A unique_ptr helper to free a dwo_file.  */
1976
1977 struct dwo_file_deleter
1978 {
1979   void operator() (struct dwo_file *df) const
1980   {
1981     free_dwo_file (df);
1982   }
1983 };
1984
1985 /* A unique pointer to a dwo_file.  */
1986
1987 typedef std::unique_ptr<struct dwo_file, dwo_file_deleter> dwo_file_up;
1988
1989 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
1990
1991 static void check_producer (struct dwarf2_cu *cu);
1992
1993 static void free_line_header_voidp (void *arg);
1994 \f
1995 /* Various complaints about symbol reading that don't abort the process.  */
1996
1997 static void
1998 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1999 {
2000   complaint (_("statement list doesn't fit in .debug_line section"));
2001 }
2002
2003 static void
2004 dwarf2_debug_line_missing_file_complaint (void)
2005 {
2006   complaint (_(".debug_line section has line data without a file"));
2007 }
2008
2009 static void
2010 dwarf2_debug_line_missing_end_sequence_complaint (void)
2011 {
2012   complaint (_(".debug_line section has line "
2013                "program sequence without an end"));
2014 }
2015
2016 static void
2017 dwarf2_complex_location_expr_complaint (void)
2018 {
2019   complaint (_("location expression too complex"));
2020 }
2021
2022 static void
2023 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2024                                               int arg3)
2025 {
2026   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
2027              arg1, arg2, arg3);
2028 }
2029
2030 static void
2031 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2032 {
2033   complaint (_("debug info runs off end of %s section"
2034                " [in module %s]"),
2035              get_section_name (section),
2036              get_section_file_name (section));
2037 }
2038
2039 static void
2040 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2041 {
2042   complaint (_("macro debug info contains a "
2043                "malformed macro definition:\n`%s'"),
2044              arg1);
2045 }
2046
2047 static void
2048 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2049 {
2050   complaint (_("invalid attribute class or form for '%s' in '%s'"),
2051              arg1, arg2);
2052 }
2053
2054 /* Hash function for line_header_hash.  */
2055
2056 static hashval_t
2057 line_header_hash (const struct line_header *ofs)
2058 {
2059   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2060 }
2061
2062 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2063
2064 static hashval_t
2065 line_header_hash_voidp (const void *item)
2066 {
2067   const struct line_header *ofs = (const struct line_header *) item;
2068
2069   return line_header_hash (ofs);
2070 }
2071
2072 /* Equality function for line_header_hash.  */
2073
2074 static int
2075 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2076 {
2077   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2078   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2079
2080   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2081           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2082 }
2083
2084 \f
2085
2086 /* Read the given attribute value as an address, taking the attribute's
2087    form into account.  */
2088
2089 static CORE_ADDR
2090 attr_value_as_address (struct attribute *attr)
2091 {
2092   CORE_ADDR addr;
2093
2094   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2095     {
2096       /* Aside from a few clearly defined exceptions, attributes that
2097          contain an address must always be in DW_FORM_addr form.
2098          Unfortunately, some compilers happen to be violating this
2099          requirement by encoding addresses using other forms, such
2100          as DW_FORM_data4 for example.  For those broken compilers,
2101          we try to do our best, without any guarantee of success,
2102          to interpret the address correctly.  It would also be nice
2103          to generate a complaint, but that would require us to maintain
2104          a list of legitimate cases where a non-address form is allowed,
2105          as well as update callers to pass in at least the CU's DWARF
2106          version.  This is more overhead than what we're willing to
2107          expand for a pretty rare case.  */
2108       addr = DW_UNSND (attr);
2109     }
2110   else
2111     addr = DW_ADDR (attr);
2112
2113   return addr;
2114 }
2115
2116 /* See declaration.  */
2117
2118 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2119                                         const dwarf2_debug_sections *names)
2120   : objfile (objfile_)
2121 {
2122   if (names == NULL)
2123     names = &dwarf2_elf_names;
2124
2125   bfd *obfd = objfile->obfd;
2126
2127   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2128     locate_sections (obfd, sec, *names);
2129 }
2130
2131 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2132
2133 dwarf2_per_objfile::~dwarf2_per_objfile ()
2134 {
2135   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2136   free_cached_comp_units ();
2137
2138   if (quick_file_names_table)
2139     htab_delete (quick_file_names_table);
2140
2141   if (line_header_hash)
2142     htab_delete (line_header_hash);
2143
2144   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2145     VEC_free (dwarf2_per_cu_ptr, per_cu->imported_symtabs);
2146
2147   for (signatured_type *sig_type : all_type_units)
2148     VEC_free (dwarf2_per_cu_ptr, sig_type->per_cu.imported_symtabs);
2149
2150   VEC_free (dwarf2_section_info_def, types);
2151
2152   if (dwo_files != NULL)
2153     free_dwo_files (dwo_files, objfile);
2154
2155   /* Everything else should be on the objfile obstack.  */
2156 }
2157
2158 /* See declaration.  */
2159
2160 void
2161 dwarf2_per_objfile::free_cached_comp_units ()
2162 {
2163   dwarf2_per_cu_data *per_cu = read_in_chain;
2164   dwarf2_per_cu_data **last_chain = &read_in_chain;
2165   while (per_cu != NULL)
2166     {
2167       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2168
2169       delete per_cu->cu;
2170       *last_chain = next_cu;
2171       per_cu = next_cu;
2172     }
2173 }
2174
2175 /* A helper class that calls free_cached_comp_units on
2176    destruction.  */
2177
2178 class free_cached_comp_units
2179 {
2180 public:
2181
2182   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2183     : m_per_objfile (per_objfile)
2184   {
2185   }
2186
2187   ~free_cached_comp_units ()
2188   {
2189     m_per_objfile->free_cached_comp_units ();
2190   }
2191
2192   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2193
2194 private:
2195
2196   dwarf2_per_objfile *m_per_objfile;
2197 };
2198
2199 /* Try to locate the sections we need for DWARF 2 debugging
2200    information and return true if we have enough to do something.
2201    NAMES points to the dwarf2 section names, or is NULL if the standard
2202    ELF names are used.  */
2203
2204 int
2205 dwarf2_has_info (struct objfile *objfile,
2206                  const struct dwarf2_debug_sections *names)
2207 {
2208   if (objfile->flags & OBJF_READNEVER)
2209     return 0;
2210
2211   struct dwarf2_per_objfile *dwarf2_per_objfile
2212     = get_dwarf2_per_objfile (objfile);
2213
2214   if (dwarf2_per_objfile == NULL)
2215     {
2216       /* Initialize per-objfile state.  */
2217       dwarf2_per_objfile
2218         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2219                                                                      names);
2220       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2221     }
2222   return (!dwarf2_per_objfile->info.is_virtual
2223           && dwarf2_per_objfile->info.s.section != NULL
2224           && !dwarf2_per_objfile->abbrev.is_virtual
2225           && dwarf2_per_objfile->abbrev.s.section != NULL);
2226 }
2227
2228 /* Return the containing section of virtual section SECTION.  */
2229
2230 static struct dwarf2_section_info *
2231 get_containing_section (const struct dwarf2_section_info *section)
2232 {
2233   gdb_assert (section->is_virtual);
2234   return section->s.containing_section;
2235 }
2236
2237 /* Return the bfd owner of SECTION.  */
2238
2239 static struct bfd *
2240 get_section_bfd_owner (const struct dwarf2_section_info *section)
2241 {
2242   if (section->is_virtual)
2243     {
2244       section = get_containing_section (section);
2245       gdb_assert (!section->is_virtual);
2246     }
2247   return section->s.section->owner;
2248 }
2249
2250 /* Return the bfd section of SECTION.
2251    Returns NULL if the section is not present.  */
2252
2253 static asection *
2254 get_section_bfd_section (const struct dwarf2_section_info *section)
2255 {
2256   if (section->is_virtual)
2257     {
2258       section = get_containing_section (section);
2259       gdb_assert (!section->is_virtual);
2260     }
2261   return section->s.section;
2262 }
2263
2264 /* Return the name of SECTION.  */
2265
2266 static const char *
2267 get_section_name (const struct dwarf2_section_info *section)
2268 {
2269   asection *sectp = get_section_bfd_section (section);
2270
2271   gdb_assert (sectp != NULL);
2272   return bfd_section_name (get_section_bfd_owner (section), sectp);
2273 }
2274
2275 /* Return the name of the file SECTION is in.  */
2276
2277 static const char *
2278 get_section_file_name (const struct dwarf2_section_info *section)
2279 {
2280   bfd *abfd = get_section_bfd_owner (section);
2281
2282   return bfd_get_filename (abfd);
2283 }
2284
2285 /* Return the id of SECTION.
2286    Returns 0 if SECTION doesn't exist.  */
2287
2288 static int
2289 get_section_id (const struct dwarf2_section_info *section)
2290 {
2291   asection *sectp = get_section_bfd_section (section);
2292
2293   if (sectp == NULL)
2294     return 0;
2295   return sectp->id;
2296 }
2297
2298 /* Return the flags of SECTION.
2299    SECTION (or containing section if this is a virtual section) must exist.  */
2300
2301 static int
2302 get_section_flags (const struct dwarf2_section_info *section)
2303 {
2304   asection *sectp = get_section_bfd_section (section);
2305
2306   gdb_assert (sectp != NULL);
2307   return bfd_get_section_flags (sectp->owner, sectp);
2308 }
2309
2310 /* When loading sections, we look either for uncompressed section or for
2311    compressed section names.  */
2312
2313 static int
2314 section_is_p (const char *section_name,
2315               const struct dwarf2_section_names *names)
2316 {
2317   if (names->normal != NULL
2318       && strcmp (section_name, names->normal) == 0)
2319     return 1;
2320   if (names->compressed != NULL
2321       && strcmp (section_name, names->compressed) == 0)
2322     return 1;
2323   return 0;
2324 }
2325
2326 /* See declaration.  */
2327
2328 void
2329 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2330                                      const dwarf2_debug_sections &names)
2331 {
2332   flagword aflag = bfd_get_section_flags (abfd, sectp);
2333
2334   if ((aflag & SEC_HAS_CONTENTS) == 0)
2335     {
2336     }
2337   else if (section_is_p (sectp->name, &names.info))
2338     {
2339       this->info.s.section = sectp;
2340       this->info.size = bfd_get_section_size (sectp);
2341     }
2342   else if (section_is_p (sectp->name, &names.abbrev))
2343     {
2344       this->abbrev.s.section = sectp;
2345       this->abbrev.size = bfd_get_section_size (sectp);
2346     }
2347   else if (section_is_p (sectp->name, &names.line))
2348     {
2349       this->line.s.section = sectp;
2350       this->line.size = bfd_get_section_size (sectp);
2351     }
2352   else if (section_is_p (sectp->name, &names.loc))
2353     {
2354       this->loc.s.section = sectp;
2355       this->loc.size = bfd_get_section_size (sectp);
2356     }
2357   else if (section_is_p (sectp->name, &names.loclists))
2358     {
2359       this->loclists.s.section = sectp;
2360       this->loclists.size = bfd_get_section_size (sectp);
2361     }
2362   else if (section_is_p (sectp->name, &names.macinfo))
2363     {
2364       this->macinfo.s.section = sectp;
2365       this->macinfo.size = bfd_get_section_size (sectp);
2366     }
2367   else if (section_is_p (sectp->name, &names.macro))
2368     {
2369       this->macro.s.section = sectp;
2370       this->macro.size = bfd_get_section_size (sectp);
2371     }
2372   else if (section_is_p (sectp->name, &names.str))
2373     {
2374       this->str.s.section = sectp;
2375       this->str.size = bfd_get_section_size (sectp);
2376     }
2377   else if (section_is_p (sectp->name, &names.line_str))
2378     {
2379       this->line_str.s.section = sectp;
2380       this->line_str.size = bfd_get_section_size (sectp);
2381     }
2382   else if (section_is_p (sectp->name, &names.addr))
2383     {
2384       this->addr.s.section = sectp;
2385       this->addr.size = bfd_get_section_size (sectp);
2386     }
2387   else if (section_is_p (sectp->name, &names.frame))
2388     {
2389       this->frame.s.section = sectp;
2390       this->frame.size = bfd_get_section_size (sectp);
2391     }
2392   else if (section_is_p (sectp->name, &names.eh_frame))
2393     {
2394       this->eh_frame.s.section = sectp;
2395       this->eh_frame.size = bfd_get_section_size (sectp);
2396     }
2397   else if (section_is_p (sectp->name, &names.ranges))
2398     {
2399       this->ranges.s.section = sectp;
2400       this->ranges.size = bfd_get_section_size (sectp);
2401     }
2402   else if (section_is_p (sectp->name, &names.rnglists))
2403     {
2404       this->rnglists.s.section = sectp;
2405       this->rnglists.size = bfd_get_section_size (sectp);
2406     }
2407   else if (section_is_p (sectp->name, &names.types))
2408     {
2409       struct dwarf2_section_info type_section;
2410
2411       memset (&type_section, 0, sizeof (type_section));
2412       type_section.s.section = sectp;
2413       type_section.size = bfd_get_section_size (sectp);
2414
2415       VEC_safe_push (dwarf2_section_info_def, this->types,
2416                      &type_section);
2417     }
2418   else if (section_is_p (sectp->name, &names.gdb_index))
2419     {
2420       this->gdb_index.s.section = sectp;
2421       this->gdb_index.size = bfd_get_section_size (sectp);
2422     }
2423   else if (section_is_p (sectp->name, &names.debug_names))
2424     {
2425       this->debug_names.s.section = sectp;
2426       this->debug_names.size = bfd_get_section_size (sectp);
2427     }
2428   else if (section_is_p (sectp->name, &names.debug_aranges))
2429     {
2430       this->debug_aranges.s.section = sectp;
2431       this->debug_aranges.size = bfd_get_section_size (sectp);
2432     }
2433
2434   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2435       && bfd_section_vma (abfd, sectp) == 0)
2436     this->has_section_at_zero = true;
2437 }
2438
2439 /* A helper function that decides whether a section is empty,
2440    or not present.  */
2441
2442 static int
2443 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2444 {
2445   if (section->is_virtual)
2446     return section->size == 0;
2447   return section->s.section == NULL || section->size == 0;
2448 }
2449
2450 /* See dwarf2read.h.  */
2451
2452 void
2453 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2454 {
2455   asection *sectp;
2456   bfd *abfd;
2457   gdb_byte *buf, *retbuf;
2458
2459   if (info->readin)
2460     return;
2461   info->buffer = NULL;
2462   info->readin = 1;
2463
2464   if (dwarf2_section_empty_p (info))
2465     return;
2466
2467   sectp = get_section_bfd_section (info);
2468
2469   /* If this is a virtual section we need to read in the real one first.  */
2470   if (info->is_virtual)
2471     {
2472       struct dwarf2_section_info *containing_section =
2473         get_containing_section (info);
2474
2475       gdb_assert (sectp != NULL);
2476       if ((sectp->flags & SEC_RELOC) != 0)
2477         {
2478           error (_("Dwarf Error: DWP format V2 with relocations is not"
2479                    " supported in section %s [in module %s]"),
2480                  get_section_name (info), get_section_file_name (info));
2481         }
2482       dwarf2_read_section (objfile, containing_section);
2483       /* Other code should have already caught virtual sections that don't
2484          fit.  */
2485       gdb_assert (info->virtual_offset + info->size
2486                   <= containing_section->size);
2487       /* If the real section is empty or there was a problem reading the
2488          section we shouldn't get here.  */
2489       gdb_assert (containing_section->buffer != NULL);
2490       info->buffer = containing_section->buffer + info->virtual_offset;
2491       return;
2492     }
2493
2494   /* If the section has relocations, we must read it ourselves.
2495      Otherwise we attach it to the BFD.  */
2496   if ((sectp->flags & SEC_RELOC) == 0)
2497     {
2498       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2499       return;
2500     }
2501
2502   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2503   info->buffer = buf;
2504
2505   /* When debugging .o files, we may need to apply relocations; see
2506      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2507      We never compress sections in .o files, so we only need to
2508      try this when the section is not compressed.  */
2509   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2510   if (retbuf != NULL)
2511     {
2512       info->buffer = retbuf;
2513       return;
2514     }
2515
2516   abfd = get_section_bfd_owner (info);
2517   gdb_assert (abfd != NULL);
2518
2519   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2520       || bfd_bread (buf, info->size, abfd) != info->size)
2521     {
2522       error (_("Dwarf Error: Can't read DWARF data"
2523                " in section %s [in module %s]"),
2524              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2525     }
2526 }
2527
2528 /* A helper function that returns the size of a section in a safe way.
2529    If you are positive that the section has been read before using the
2530    size, then it is safe to refer to the dwarf2_section_info object's
2531    "size" field directly.  In other cases, you must call this
2532    function, because for compressed sections the size field is not set
2533    correctly until the section has been read.  */
2534
2535 static bfd_size_type
2536 dwarf2_section_size (struct objfile *objfile,
2537                      struct dwarf2_section_info *info)
2538 {
2539   if (!info->readin)
2540     dwarf2_read_section (objfile, info);
2541   return info->size;
2542 }
2543
2544 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2545    SECTION_NAME.  */
2546
2547 void
2548 dwarf2_get_section_info (struct objfile *objfile,
2549                          enum dwarf2_section_enum sect,
2550                          asection **sectp, const gdb_byte **bufp,
2551                          bfd_size_type *sizep)
2552 {
2553   struct dwarf2_per_objfile *data
2554     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2555                                                   dwarf2_objfile_data_key);
2556   struct dwarf2_section_info *info;
2557
2558   /* We may see an objfile without any DWARF, in which case we just
2559      return nothing.  */
2560   if (data == NULL)
2561     {
2562       *sectp = NULL;
2563       *bufp = NULL;
2564       *sizep = 0;
2565       return;
2566     }
2567   switch (sect)
2568     {
2569     case DWARF2_DEBUG_FRAME:
2570       info = &data->frame;
2571       break;
2572     case DWARF2_EH_FRAME:
2573       info = &data->eh_frame;
2574       break;
2575     default:
2576       gdb_assert_not_reached ("unexpected section");
2577     }
2578
2579   dwarf2_read_section (objfile, info);
2580
2581   *sectp = get_section_bfd_section (info);
2582   *bufp = info->buffer;
2583   *sizep = info->size;
2584 }
2585
2586 /* A helper function to find the sections for a .dwz file.  */
2587
2588 static void
2589 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2590 {
2591   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2592
2593   /* Note that we only support the standard ELF names, because .dwz
2594      is ELF-only (at the time of writing).  */
2595   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2596     {
2597       dwz_file->abbrev.s.section = sectp;
2598       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2599     }
2600   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2601     {
2602       dwz_file->info.s.section = sectp;
2603       dwz_file->info.size = bfd_get_section_size (sectp);
2604     }
2605   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2606     {
2607       dwz_file->str.s.section = sectp;
2608       dwz_file->str.size = bfd_get_section_size (sectp);
2609     }
2610   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2611     {
2612       dwz_file->line.s.section = sectp;
2613       dwz_file->line.size = bfd_get_section_size (sectp);
2614     }
2615   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2616     {
2617       dwz_file->macro.s.section = sectp;
2618       dwz_file->macro.size = bfd_get_section_size (sectp);
2619     }
2620   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2621     {
2622       dwz_file->gdb_index.s.section = sectp;
2623       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2624     }
2625   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2626     {
2627       dwz_file->debug_names.s.section = sectp;
2628       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2629     }
2630 }
2631
2632 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2633    there is no .gnu_debugaltlink section in the file.  Error if there
2634    is such a section but the file cannot be found.  */
2635
2636 static struct dwz_file *
2637 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2638 {
2639   const char *filename;
2640   bfd_size_type buildid_len_arg;
2641   size_t buildid_len;
2642   bfd_byte *buildid;
2643
2644   if (dwarf2_per_objfile->dwz_file != NULL)
2645     return dwarf2_per_objfile->dwz_file.get ();
2646
2647   bfd_set_error (bfd_error_no_error);
2648   gdb::unique_xmalloc_ptr<char> data
2649     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2650                                   &buildid_len_arg, &buildid));
2651   if (data == NULL)
2652     {
2653       if (bfd_get_error () == bfd_error_no_error)
2654         return NULL;
2655       error (_("could not read '.gnu_debugaltlink' section: %s"),
2656              bfd_errmsg (bfd_get_error ()));
2657     }
2658
2659   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2660
2661   buildid_len = (size_t) buildid_len_arg;
2662
2663   filename = data.get ();
2664
2665   std::string abs_storage;
2666   if (!IS_ABSOLUTE_PATH (filename))
2667     {
2668       gdb::unique_xmalloc_ptr<char> abs
2669         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2670
2671       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2672       filename = abs_storage.c_str ();
2673     }
2674
2675   /* First try the file name given in the section.  If that doesn't
2676      work, try to use the build-id instead.  */
2677   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2678   if (dwz_bfd != NULL)
2679     {
2680       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2681         dwz_bfd.release ();
2682     }
2683
2684   if (dwz_bfd == NULL)
2685     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2686
2687   if (dwz_bfd == NULL)
2688     error (_("could not find '.gnu_debugaltlink' file for %s"),
2689            objfile_name (dwarf2_per_objfile->objfile));
2690
2691   std::unique_ptr<struct dwz_file> result
2692     (new struct dwz_file (std::move (dwz_bfd)));
2693
2694   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2695                          result.get ());
2696
2697   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2698                             result->dwz_bfd.get ());
2699   dwarf2_per_objfile->dwz_file = std::move (result);
2700   return dwarf2_per_objfile->dwz_file.get ();
2701 }
2702 \f
2703 /* DWARF quick_symbols_functions support.  */
2704
2705 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2706    unique line tables, so we maintain a separate table of all .debug_line
2707    derived entries to support the sharing.
2708    All the quick functions need is the list of file names.  We discard the
2709    line_header when we're done and don't need to record it here.  */
2710 struct quick_file_names
2711 {
2712   /* The data used to construct the hash key.  */
2713   struct stmt_list_hash hash;
2714
2715   /* The number of entries in file_names, real_names.  */
2716   unsigned int num_file_names;
2717
2718   /* The file names from the line table, after being run through
2719      file_full_name.  */
2720   const char **file_names;
2721
2722   /* The file names from the line table after being run through
2723      gdb_realpath.  These are computed lazily.  */
2724   const char **real_names;
2725 };
2726
2727 /* When using the index (and thus not using psymtabs), each CU has an
2728    object of this type.  This is used to hold information needed by
2729    the various "quick" methods.  */
2730 struct dwarf2_per_cu_quick_data
2731 {
2732   /* The file table.  This can be NULL if there was no file table
2733      or it's currently not read in.
2734      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2735   struct quick_file_names *file_names;
2736
2737   /* The corresponding symbol table.  This is NULL if symbols for this
2738      CU have not yet been read.  */
2739   struct compunit_symtab *compunit_symtab;
2740
2741   /* A temporary mark bit used when iterating over all CUs in
2742      expand_symtabs_matching.  */
2743   unsigned int mark : 1;
2744
2745   /* True if we've tried to read the file table and found there isn't one.
2746      There will be no point in trying to read it again next time.  */
2747   unsigned int no_file_data : 1;
2748 };
2749
2750 /* Utility hash function for a stmt_list_hash.  */
2751
2752 static hashval_t
2753 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2754 {
2755   hashval_t v = 0;
2756
2757   if (stmt_list_hash->dwo_unit != NULL)
2758     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2759   v += to_underlying (stmt_list_hash->line_sect_off);
2760   return v;
2761 }
2762
2763 /* Utility equality function for a stmt_list_hash.  */
2764
2765 static int
2766 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2767                     const struct stmt_list_hash *rhs)
2768 {
2769   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2770     return 0;
2771   if (lhs->dwo_unit != NULL
2772       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2773     return 0;
2774
2775   return lhs->line_sect_off == rhs->line_sect_off;
2776 }
2777
2778 /* Hash function for a quick_file_names.  */
2779
2780 static hashval_t
2781 hash_file_name_entry (const void *e)
2782 {
2783   const struct quick_file_names *file_data
2784     = (const struct quick_file_names *) e;
2785
2786   return hash_stmt_list_entry (&file_data->hash);
2787 }
2788
2789 /* Equality function for a quick_file_names.  */
2790
2791 static int
2792 eq_file_name_entry (const void *a, const void *b)
2793 {
2794   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2795   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2796
2797   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2798 }
2799
2800 /* Delete function for a quick_file_names.  */
2801
2802 static void
2803 delete_file_name_entry (void *e)
2804 {
2805   struct quick_file_names *file_data = (struct quick_file_names *) e;
2806   int i;
2807
2808   for (i = 0; i < file_data->num_file_names; ++i)
2809     {
2810       xfree ((void*) file_data->file_names[i]);
2811       if (file_data->real_names)
2812         xfree ((void*) file_data->real_names[i]);
2813     }
2814
2815   /* The space for the struct itself lives on objfile_obstack,
2816      so we don't free it here.  */
2817 }
2818
2819 /* Create a quick_file_names hash table.  */
2820
2821 static htab_t
2822 create_quick_file_names_table (unsigned int nr_initial_entries)
2823 {
2824   return htab_create_alloc (nr_initial_entries,
2825                             hash_file_name_entry, eq_file_name_entry,
2826                             delete_file_name_entry, xcalloc, xfree);
2827 }
2828
2829 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2830    have to be created afterwards.  You should call age_cached_comp_units after
2831    processing PER_CU->CU.  dw2_setup must have been already called.  */
2832
2833 static void
2834 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2835 {
2836   if (per_cu->is_debug_types)
2837     load_full_type_unit (per_cu);
2838   else
2839     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2840
2841   if (per_cu->cu == NULL)
2842     return;  /* Dummy CU.  */
2843
2844   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2845 }
2846
2847 /* Read in the symbols for PER_CU.  */
2848
2849 static void
2850 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2851 {
2852   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2853
2854   /* Skip type_unit_groups, reading the type units they contain
2855      is handled elsewhere.  */
2856   if (IS_TYPE_UNIT_GROUP (per_cu))
2857     return;
2858
2859   /* The destructor of dwarf2_queue_guard frees any entries left on
2860      the queue.  After this point we're guaranteed to leave this function
2861      with the dwarf queue empty.  */
2862   dwarf2_queue_guard q_guard;
2863
2864   if (dwarf2_per_objfile->using_index
2865       ? per_cu->v.quick->compunit_symtab == NULL
2866       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2867     {
2868       queue_comp_unit (per_cu, language_minimal);
2869       load_cu (per_cu, skip_partial);
2870
2871       /* If we just loaded a CU from a DWO, and we're working with an index
2872          that may badly handle TUs, load all the TUs in that DWO as well.
2873          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2874       if (!per_cu->is_debug_types
2875           && per_cu->cu != NULL
2876           && per_cu->cu->dwo_unit != NULL
2877           && dwarf2_per_objfile->index_table != NULL
2878           && dwarf2_per_objfile->index_table->version <= 7
2879           /* DWP files aren't supported yet.  */
2880           && get_dwp_file (dwarf2_per_objfile) == NULL)
2881         queue_and_load_all_dwo_tus (per_cu);
2882     }
2883
2884   process_queue (dwarf2_per_objfile);
2885
2886   /* Age the cache, releasing compilation units that have not
2887      been used recently.  */
2888   age_cached_comp_units (dwarf2_per_objfile);
2889 }
2890
2891 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2892    the objfile from which this CU came.  Returns the resulting symbol
2893    table.  */
2894
2895 static struct compunit_symtab *
2896 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2897 {
2898   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2899
2900   gdb_assert (dwarf2_per_objfile->using_index);
2901   if (!per_cu->v.quick->compunit_symtab)
2902     {
2903       free_cached_comp_units freer (dwarf2_per_objfile);
2904       scoped_restore decrementer = increment_reading_symtab ();
2905       dw2_do_instantiate_symtab (per_cu, skip_partial);
2906       process_cu_includes (dwarf2_per_objfile);
2907     }
2908
2909   return per_cu->v.quick->compunit_symtab;
2910 }
2911
2912 /* See declaration.  */
2913
2914 dwarf2_per_cu_data *
2915 dwarf2_per_objfile::get_cutu (int index)
2916 {
2917   if (index >= this->all_comp_units.size ())
2918     {
2919       index -= this->all_comp_units.size ();
2920       gdb_assert (index < this->all_type_units.size ());
2921       return &this->all_type_units[index]->per_cu;
2922     }
2923
2924   return this->all_comp_units[index];
2925 }
2926
2927 /* See declaration.  */
2928
2929 dwarf2_per_cu_data *
2930 dwarf2_per_objfile::get_cu (int index)
2931 {
2932   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2933
2934   return this->all_comp_units[index];
2935 }
2936
2937 /* See declaration.  */
2938
2939 signatured_type *
2940 dwarf2_per_objfile::get_tu (int index)
2941 {
2942   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2943
2944   return this->all_type_units[index];
2945 }
2946
2947 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2948    objfile_obstack, and constructed with the specified field
2949    values.  */
2950
2951 static dwarf2_per_cu_data *
2952 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2953                           struct dwarf2_section_info *section,
2954                           int is_dwz,
2955                           sect_offset sect_off, ULONGEST length)
2956 {
2957   struct objfile *objfile = dwarf2_per_objfile->objfile;
2958   dwarf2_per_cu_data *the_cu
2959     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2960                      struct dwarf2_per_cu_data);
2961   the_cu->sect_off = sect_off;
2962   the_cu->length = length;
2963   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2964   the_cu->section = section;
2965   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2966                                    struct dwarf2_per_cu_quick_data);
2967   the_cu->is_dwz = is_dwz;
2968   return the_cu;
2969 }
2970
2971 /* A helper for create_cus_from_index that handles a given list of
2972    CUs.  */
2973
2974 static void
2975 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2976                             const gdb_byte *cu_list, offset_type n_elements,
2977                             struct dwarf2_section_info *section,
2978                             int is_dwz)
2979 {
2980   for (offset_type i = 0; i < n_elements; i += 2)
2981     {
2982       gdb_static_assert (sizeof (ULONGEST) >= 8);
2983
2984       sect_offset sect_off
2985         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2986       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2987       cu_list += 2 * 8;
2988
2989       dwarf2_per_cu_data *per_cu
2990         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2991                                      sect_off, length);
2992       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
2993     }
2994 }
2995
2996 /* Read the CU list from the mapped index, and use it to create all
2997    the CU objects for this objfile.  */
2998
2999 static void
3000 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3001                        const gdb_byte *cu_list, offset_type cu_list_elements,
3002                        const gdb_byte *dwz_list, offset_type dwz_elements)
3003 {
3004   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
3005   dwarf2_per_objfile->all_comp_units.reserve
3006     ((cu_list_elements + dwz_elements) / 2);
3007
3008   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
3009                               &dwarf2_per_objfile->info, 0);
3010
3011   if (dwz_elements == 0)
3012     return;
3013
3014   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3015   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
3016                               &dwz->info, 1);
3017 }
3018
3019 /* Create the signatured type hash table from the index.  */
3020
3021 static void
3022 create_signatured_type_table_from_index
3023   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3024    struct dwarf2_section_info *section,
3025    const gdb_byte *bytes,
3026    offset_type elements)
3027 {
3028   struct objfile *objfile = dwarf2_per_objfile->objfile;
3029
3030   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3031   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
3032
3033   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3034
3035   for (offset_type i = 0; i < elements; i += 3)
3036     {
3037       struct signatured_type *sig_type;
3038       ULONGEST signature;
3039       void **slot;
3040       cu_offset type_offset_in_tu;
3041
3042       gdb_static_assert (sizeof (ULONGEST) >= 8);
3043       sect_offset sect_off
3044         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3045       type_offset_in_tu
3046         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3047                                                 BFD_ENDIAN_LITTLE);
3048       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3049       bytes += 3 * 8;
3050
3051       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3052                                  struct signatured_type);
3053       sig_type->signature = signature;
3054       sig_type->type_offset_in_tu = type_offset_in_tu;
3055       sig_type->per_cu.is_debug_types = 1;
3056       sig_type->per_cu.section = section;
3057       sig_type->per_cu.sect_off = sect_off;
3058       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3059       sig_type->per_cu.v.quick
3060         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3061                           struct dwarf2_per_cu_quick_data);
3062
3063       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3064       *slot = sig_type;
3065
3066       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3067     }
3068
3069   dwarf2_per_objfile->signatured_types = sig_types_hash;
3070 }
3071
3072 /* Create the signatured type hash table from .debug_names.  */
3073
3074 static void
3075 create_signatured_type_table_from_debug_names
3076   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3077    const mapped_debug_names &map,
3078    struct dwarf2_section_info *section,
3079    struct dwarf2_section_info *abbrev_section)
3080 {
3081   struct objfile *objfile = dwarf2_per_objfile->objfile;
3082
3083   dwarf2_read_section (objfile, section);
3084   dwarf2_read_section (objfile, abbrev_section);
3085
3086   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3087   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
3088
3089   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3090
3091   for (uint32_t i = 0; i < map.tu_count; ++i)
3092     {
3093       struct signatured_type *sig_type;
3094       void **slot;
3095
3096       sect_offset sect_off
3097         = (sect_offset) (extract_unsigned_integer
3098                          (map.tu_table_reordered + i * map.offset_size,
3099                           map.offset_size,
3100                           map.dwarf5_byte_order));
3101
3102       comp_unit_head cu_header;
3103       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3104                                      abbrev_section,
3105                                      section->buffer + to_underlying (sect_off),
3106                                      rcuh_kind::TYPE);
3107
3108       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3109                                  struct signatured_type);
3110       sig_type->signature = cu_header.signature;
3111       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3112       sig_type->per_cu.is_debug_types = 1;
3113       sig_type->per_cu.section = section;
3114       sig_type->per_cu.sect_off = sect_off;
3115       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3116       sig_type->per_cu.v.quick
3117         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3118                           struct dwarf2_per_cu_quick_data);
3119
3120       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3121       *slot = sig_type;
3122
3123       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3124     }
3125
3126   dwarf2_per_objfile->signatured_types = sig_types_hash;
3127 }
3128
3129 /* Read the address map data from the mapped index, and use it to
3130    populate the objfile's psymtabs_addrmap.  */
3131
3132 static void
3133 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3134                            struct mapped_index *index)
3135 {
3136   struct objfile *objfile = dwarf2_per_objfile->objfile;
3137   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3138   const gdb_byte *iter, *end;
3139   struct addrmap *mutable_map;
3140   CORE_ADDR baseaddr;
3141
3142   auto_obstack temp_obstack;
3143
3144   mutable_map = addrmap_create_mutable (&temp_obstack);
3145
3146   iter = index->address_table.data ();
3147   end = iter + index->address_table.size ();
3148
3149   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3150
3151   while (iter < end)
3152     {
3153       ULONGEST hi, lo, cu_index;
3154       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3155       iter += 8;
3156       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3157       iter += 8;
3158       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3159       iter += 4;
3160
3161       if (lo > hi)
3162         {
3163           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
3164                      hex_string (lo), hex_string (hi));
3165           continue;
3166         }
3167
3168       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
3169         {
3170           complaint (_(".gdb_index address table has invalid CU number %u"),
3171                      (unsigned) cu_index);
3172           continue;
3173         }
3174
3175       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3176       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3177       addrmap_set_empty (mutable_map, lo, hi - 1,
3178                          dwarf2_per_objfile->get_cu (cu_index));
3179     }
3180
3181   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3182                                                     &objfile->objfile_obstack);
3183 }
3184
3185 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3186    populate the objfile's psymtabs_addrmap.  */
3187
3188 static void
3189 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3190                              struct dwarf2_section_info *section)
3191 {
3192   struct objfile *objfile = dwarf2_per_objfile->objfile;
3193   bfd *abfd = objfile->obfd;
3194   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3195   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3196                                        SECT_OFF_TEXT (objfile));
3197
3198   auto_obstack temp_obstack;
3199   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3200
3201   std::unordered_map<sect_offset,
3202                      dwarf2_per_cu_data *,
3203                      gdb::hash_enum<sect_offset>>
3204     debug_info_offset_to_per_cu;
3205   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3206     {
3207       const auto insertpair
3208         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3209       if (!insertpair.second)
3210         {
3211           warning (_("Section .debug_aranges in %s has duplicate "
3212                      "debug_info_offset %s, ignoring .debug_aranges."),
3213                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3214           return;
3215         }
3216     }
3217
3218   dwarf2_read_section (objfile, section);
3219
3220   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3221
3222   const gdb_byte *addr = section->buffer;
3223
3224   while (addr < section->buffer + section->size)
3225     {
3226       const gdb_byte *const entry_addr = addr;
3227       unsigned int bytes_read;
3228
3229       const LONGEST entry_length = read_initial_length (abfd, addr,
3230                                                         &bytes_read);
3231       addr += bytes_read;
3232
3233       const gdb_byte *const entry_end = addr + entry_length;
3234       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3235       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3236       if (addr + entry_length > section->buffer + section->size)
3237         {
3238           warning (_("Section .debug_aranges in %s entry at offset %zu "
3239                      "length %s exceeds section length %s, "
3240                      "ignoring .debug_aranges."),
3241                    objfile_name (objfile), entry_addr - section->buffer,
3242                    plongest (bytes_read + entry_length),
3243                    pulongest (section->size));
3244           return;
3245         }
3246
3247       /* The version number.  */
3248       const uint16_t version = read_2_bytes (abfd, addr);
3249       addr += 2;
3250       if (version != 2)
3251         {
3252           warning (_("Section .debug_aranges in %s entry at offset %zu "
3253                      "has unsupported version %d, ignoring .debug_aranges."),
3254                    objfile_name (objfile), entry_addr - section->buffer,
3255                    version);
3256           return;
3257         }
3258
3259       const uint64_t debug_info_offset
3260         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3261       addr += offset_size;
3262       const auto per_cu_it
3263         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3264       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3265         {
3266           warning (_("Section .debug_aranges in %s entry at offset %zu "
3267                      "debug_info_offset %s does not exists, "
3268                      "ignoring .debug_aranges."),
3269                    objfile_name (objfile), entry_addr - section->buffer,
3270                    pulongest (debug_info_offset));
3271           return;
3272         }
3273       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3274
3275       const uint8_t address_size = *addr++;
3276       if (address_size < 1 || address_size > 8)
3277         {
3278           warning (_("Section .debug_aranges in %s entry at offset %zu "
3279                      "address_size %u is invalid, ignoring .debug_aranges."),
3280                    objfile_name (objfile), entry_addr - section->buffer,
3281                    address_size);
3282           return;
3283         }
3284
3285       const uint8_t segment_selector_size = *addr++;
3286       if (segment_selector_size != 0)
3287         {
3288           warning (_("Section .debug_aranges in %s entry at offset %zu "
3289                      "segment_selector_size %u is not supported, "
3290                      "ignoring .debug_aranges."),
3291                    objfile_name (objfile), entry_addr - section->buffer,
3292                    segment_selector_size);
3293           return;
3294         }
3295
3296       /* Must pad to an alignment boundary that is twice the address
3297          size.  It is undocumented by the DWARF standard but GCC does
3298          use it.  */
3299       for (size_t padding = ((-(addr - section->buffer))
3300                              & (2 * address_size - 1));
3301            padding > 0; padding--)
3302         if (*addr++ != 0)
3303           {
3304             warning (_("Section .debug_aranges in %s entry at offset %zu "
3305                        "padding is not zero, ignoring .debug_aranges."),
3306                      objfile_name (objfile), entry_addr - section->buffer);
3307             return;
3308           }
3309
3310       for (;;)
3311         {
3312           if (addr + 2 * address_size > entry_end)
3313             {
3314               warning (_("Section .debug_aranges in %s entry at offset %zu "
3315                          "address list is not properly terminated, "
3316                          "ignoring .debug_aranges."),
3317                        objfile_name (objfile), entry_addr - section->buffer);
3318               return;
3319             }
3320           ULONGEST start = extract_unsigned_integer (addr, address_size,
3321                                                      dwarf5_byte_order);
3322           addr += address_size;
3323           ULONGEST length = extract_unsigned_integer (addr, address_size,
3324                                                       dwarf5_byte_order);
3325           addr += address_size;
3326           if (start == 0 && length == 0)
3327             break;
3328           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3329             {
3330               /* Symbol was eliminated due to a COMDAT group.  */
3331               continue;
3332             }
3333           ULONGEST end = start + length;
3334           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3335           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3336           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3337         }
3338     }
3339
3340   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3341                                                     &objfile->objfile_obstack);
3342 }
3343
3344 /* Find a slot in the mapped index INDEX for the object named NAME.
3345    If NAME is found, set *VEC_OUT to point to the CU vector in the
3346    constant pool and return true.  If NAME cannot be found, return
3347    false.  */
3348
3349 static bool
3350 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3351                           offset_type **vec_out)
3352 {
3353   offset_type hash;
3354   offset_type slot, step;
3355   int (*cmp) (const char *, const char *);
3356
3357   gdb::unique_xmalloc_ptr<char> without_params;
3358   if (current_language->la_language == language_cplus
3359       || current_language->la_language == language_fortran
3360       || current_language->la_language == language_d)
3361     {
3362       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3363          not contain any.  */
3364
3365       if (strchr (name, '(') != NULL)
3366         {
3367           without_params = cp_remove_params (name);
3368
3369           if (without_params != NULL)
3370             name = without_params.get ();
3371         }
3372     }
3373
3374   /* Index version 4 did not support case insensitive searches.  But the
3375      indices for case insensitive languages are built in lowercase, therefore
3376      simulate our NAME being searched is also lowercased.  */
3377   hash = mapped_index_string_hash ((index->version == 4
3378                                     && case_sensitivity == case_sensitive_off
3379                                     ? 5 : index->version),
3380                                    name);
3381
3382   slot = hash & (index->symbol_table.size () - 1);
3383   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3384   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3385
3386   for (;;)
3387     {
3388       const char *str;
3389
3390       const auto &bucket = index->symbol_table[slot];
3391       if (bucket.name == 0 && bucket.vec == 0)
3392         return false;
3393
3394       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3395       if (!cmp (name, str))
3396         {
3397           *vec_out = (offset_type *) (index->constant_pool
3398                                       + MAYBE_SWAP (bucket.vec));
3399           return true;
3400         }
3401
3402       slot = (slot + step) & (index->symbol_table.size () - 1);
3403     }
3404 }
3405
3406 /* A helper function that reads the .gdb_index from SECTION and fills
3407    in MAP.  FILENAME is the name of the file containing the section;
3408    it is used for error reporting.  DEPRECATED_OK is true if it is
3409    ok to use deprecated sections.
3410
3411    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3412    out parameters that are filled in with information about the CU and
3413    TU lists in the section.
3414
3415    Returns 1 if all went well, 0 otherwise.  */
3416
3417 static bool
3418 read_gdb_index_from_section (struct objfile *objfile,
3419                              const char *filename,
3420                              bool deprecated_ok,
3421                              struct dwarf2_section_info *section,
3422                              struct mapped_index *map,
3423                              const gdb_byte **cu_list,
3424                              offset_type *cu_list_elements,
3425                              const gdb_byte **types_list,
3426                              offset_type *types_list_elements)
3427 {
3428   const gdb_byte *addr;
3429   offset_type version;
3430   offset_type *metadata;
3431   int i;
3432
3433   if (dwarf2_section_empty_p (section))
3434     return 0;
3435
3436   /* Older elfutils strip versions could keep the section in the main
3437      executable while splitting it for the separate debug info file.  */
3438   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3439     return 0;
3440
3441   dwarf2_read_section (objfile, section);
3442
3443   addr = section->buffer;
3444   /* Version check.  */
3445   version = MAYBE_SWAP (*(offset_type *) addr);
3446   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3447      causes the index to behave very poorly for certain requests.  Version 3
3448      contained incomplete addrmap.  So, it seems better to just ignore such
3449      indices.  */
3450   if (version < 4)
3451     {
3452       static int warning_printed = 0;
3453       if (!warning_printed)
3454         {
3455           warning (_("Skipping obsolete .gdb_index section in %s."),
3456                    filename);
3457           warning_printed = 1;
3458         }
3459       return 0;
3460     }
3461   /* Index version 4 uses a different hash function than index version
3462      5 and later.
3463
3464      Versions earlier than 6 did not emit psymbols for inlined
3465      functions.  Using these files will cause GDB not to be able to
3466      set breakpoints on inlined functions by name, so we ignore these
3467      indices unless the user has done
3468      "set use-deprecated-index-sections on".  */
3469   if (version < 6 && !deprecated_ok)
3470     {
3471       static int warning_printed = 0;
3472       if (!warning_printed)
3473         {
3474           warning (_("\
3475 Skipping deprecated .gdb_index section in %s.\n\
3476 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3477 to use the section anyway."),
3478                    filename);
3479           warning_printed = 1;
3480         }
3481       return 0;
3482     }
3483   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3484      of the TU (for symbols coming from TUs),
3485      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3486      Plus gold-generated indices can have duplicate entries for global symbols,
3487      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3488      These are just performance bugs, and we can't distinguish gdb-generated
3489      indices from gold-generated ones, so issue no warning here.  */
3490
3491   /* Indexes with higher version than the one supported by GDB may be no
3492      longer backward compatible.  */
3493   if (version > 8)
3494     return 0;
3495
3496   map->version = version;
3497
3498   metadata = (offset_type *) (addr + sizeof (offset_type));
3499
3500   i = 0;
3501   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3502   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3503                        / 8);
3504   ++i;
3505
3506   *types_list = addr + MAYBE_SWAP (metadata[i]);
3507   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3508                            - MAYBE_SWAP (metadata[i]))
3509                           / 8);
3510   ++i;
3511
3512   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3513   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3514   map->address_table
3515     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3516   ++i;
3517
3518   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3519   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3520   map->symbol_table
3521     = gdb::array_view<mapped_index::symbol_table_slot>
3522        ((mapped_index::symbol_table_slot *) symbol_table,
3523         (mapped_index::symbol_table_slot *) symbol_table_end);
3524
3525   ++i;
3526   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3527
3528   return 1;
3529 }
3530
3531 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3532    elements of all the CUs and return 1.  Otherwise, return 0.  */
3533
3534 static int
3535 dwarf2_read_gdb_index (struct dwarf2_per_objfile *dwarf2_per_objfile)
3536 {
3537   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3538   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3539   struct dwz_file *dwz;
3540   struct objfile *objfile = dwarf2_per_objfile->objfile;
3541
3542   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3543   if (!read_gdb_index_from_section (objfile, objfile_name (objfile),
3544                                     use_deprecated_index_sections,
3545                                     &dwarf2_per_objfile->gdb_index, map.get (),
3546                                     &cu_list, &cu_list_elements,
3547                                     &types_list, &types_list_elements))
3548     return 0;
3549
3550   /* Don't use the index if it's empty.  */
3551   if (map->symbol_table.empty ())
3552     return 0;
3553
3554   /* If there is a .dwz file, read it so we can get its CU list as
3555      well.  */
3556   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3557   if (dwz != NULL)
3558     {
3559       struct mapped_index dwz_map;
3560       const gdb_byte *dwz_types_ignore;
3561       offset_type dwz_types_elements_ignore;
3562
3563       if (!read_gdb_index_from_section (objfile,
3564                                         bfd_get_filename (dwz->dwz_bfd), 1,
3565                                         &dwz->gdb_index, &dwz_map,
3566                                         &dwz_list, &dwz_list_elements,
3567                                         &dwz_types_ignore,
3568                                         &dwz_types_elements_ignore))
3569         {
3570           warning (_("could not read '.gdb_index' section from %s; skipping"),
3571                    bfd_get_filename (dwz->dwz_bfd));
3572           return 0;
3573         }
3574     }
3575
3576   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3577                          dwz_list, dwz_list_elements);
3578
3579   if (types_list_elements)
3580     {
3581       struct dwarf2_section_info *section;
3582
3583       /* We can only handle a single .debug_types when we have an
3584          index.  */
3585       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3586         return 0;
3587
3588       section = VEC_index (dwarf2_section_info_def,
3589                            dwarf2_per_objfile->types, 0);
3590
3591       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3592                                                types_list, types_list_elements);
3593     }
3594
3595   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3596
3597   dwarf2_per_objfile->index_table = std::move (map);
3598   dwarf2_per_objfile->using_index = 1;
3599   dwarf2_per_objfile->quick_file_names_table =
3600     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3601
3602   return 1;
3603 }
3604
3605 /* die_reader_func for dw2_get_file_names.  */
3606
3607 static void
3608 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3609                            const gdb_byte *info_ptr,
3610                            struct die_info *comp_unit_die,
3611                            int has_children,
3612                            void *data)
3613 {
3614   struct dwarf2_cu *cu = reader->cu;
3615   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3616   struct dwarf2_per_objfile *dwarf2_per_objfile
3617     = cu->per_cu->dwarf2_per_objfile;
3618   struct objfile *objfile = dwarf2_per_objfile->objfile;
3619   struct dwarf2_per_cu_data *lh_cu;
3620   struct attribute *attr;
3621   int i;
3622   void **slot;
3623   struct quick_file_names *qfn;
3624
3625   gdb_assert (! this_cu->is_debug_types);
3626
3627   /* Our callers never want to match partial units -- instead they
3628      will match the enclosing full CU.  */
3629   if (comp_unit_die->tag == DW_TAG_partial_unit)
3630     {
3631       this_cu->v.quick->no_file_data = 1;
3632       return;
3633     }
3634
3635   lh_cu = this_cu;
3636   slot = NULL;
3637
3638   line_header_up lh;
3639   sect_offset line_offset {};
3640
3641   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3642   if (attr)
3643     {
3644       struct quick_file_names find_entry;
3645
3646       line_offset = (sect_offset) DW_UNSND (attr);
3647
3648       /* We may have already read in this line header (TU line header sharing).
3649          If we have we're done.  */
3650       find_entry.hash.dwo_unit = cu->dwo_unit;
3651       find_entry.hash.line_sect_off = line_offset;
3652       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3653                              &find_entry, INSERT);
3654       if (*slot != NULL)
3655         {
3656           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3657           return;
3658         }
3659
3660       lh = dwarf_decode_line_header (line_offset, cu);
3661     }
3662   if (lh == NULL)
3663     {
3664       lh_cu->v.quick->no_file_data = 1;
3665       return;
3666     }
3667
3668   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3669   qfn->hash.dwo_unit = cu->dwo_unit;
3670   qfn->hash.line_sect_off = line_offset;
3671   gdb_assert (slot != NULL);
3672   *slot = qfn;
3673
3674   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3675
3676   qfn->num_file_names = lh->file_names.size ();
3677   qfn->file_names =
3678     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3679   for (i = 0; i < lh->file_names.size (); ++i)
3680     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3681   qfn->real_names = NULL;
3682
3683   lh_cu->v.quick->file_names = qfn;
3684 }
3685
3686 /* A helper for the "quick" functions which attempts to read the line
3687    table for THIS_CU.  */
3688
3689 static struct quick_file_names *
3690 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3691 {
3692   /* This should never be called for TUs.  */
3693   gdb_assert (! this_cu->is_debug_types);
3694   /* Nor type unit groups.  */
3695   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3696
3697   if (this_cu->v.quick->file_names != NULL)
3698     return this_cu->v.quick->file_names;
3699   /* If we know there is no line data, no point in looking again.  */
3700   if (this_cu->v.quick->no_file_data)
3701     return NULL;
3702
3703   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3704
3705   if (this_cu->v.quick->no_file_data)
3706     return NULL;
3707   return this_cu->v.quick->file_names;
3708 }
3709
3710 /* A helper for the "quick" functions which computes and caches the
3711    real path for a given file name from the line table.  */
3712
3713 static const char *
3714 dw2_get_real_path (struct objfile *objfile,
3715                    struct quick_file_names *qfn, int index)
3716 {
3717   if (qfn->real_names == NULL)
3718     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3719                                       qfn->num_file_names, const char *);
3720
3721   if (qfn->real_names[index] == NULL)
3722     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3723
3724   return qfn->real_names[index];
3725 }
3726
3727 static struct symtab *
3728 dw2_find_last_source_symtab (struct objfile *objfile)
3729 {
3730   struct dwarf2_per_objfile *dwarf2_per_objfile
3731     = get_dwarf2_per_objfile (objfile);
3732   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3733   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3734
3735   if (cust == NULL)
3736     return NULL;
3737
3738   return compunit_primary_filetab (cust);
3739 }
3740
3741 /* Traversal function for dw2_forget_cached_source_info.  */
3742
3743 static int
3744 dw2_free_cached_file_names (void **slot, void *info)
3745 {
3746   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3747
3748   if (file_data->real_names)
3749     {
3750       int i;
3751
3752       for (i = 0; i < file_data->num_file_names; ++i)
3753         {
3754           xfree ((void*) file_data->real_names[i]);
3755           file_data->real_names[i] = NULL;
3756         }
3757     }
3758
3759   return 1;
3760 }
3761
3762 static void
3763 dw2_forget_cached_source_info (struct objfile *objfile)
3764 {
3765   struct dwarf2_per_objfile *dwarf2_per_objfile
3766     = get_dwarf2_per_objfile (objfile);
3767
3768   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3769                           dw2_free_cached_file_names, NULL);
3770 }
3771
3772 /* Helper function for dw2_map_symtabs_matching_filename that expands
3773    the symtabs and calls the iterator.  */
3774
3775 static int
3776 dw2_map_expand_apply (struct objfile *objfile,
3777                       struct dwarf2_per_cu_data *per_cu,
3778                       const char *name, const char *real_path,
3779                       gdb::function_view<bool (symtab *)> callback)
3780 {
3781   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3782
3783   /* Don't visit already-expanded CUs.  */
3784   if (per_cu->v.quick->compunit_symtab)
3785     return 0;
3786
3787   /* This may expand more than one symtab, and we want to iterate over
3788      all of them.  */
3789   dw2_instantiate_symtab (per_cu, false);
3790
3791   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3792                                     last_made, callback);
3793 }
3794
3795 /* Implementation of the map_symtabs_matching_filename method.  */
3796
3797 static bool
3798 dw2_map_symtabs_matching_filename
3799   (struct objfile *objfile, const char *name, const char *real_path,
3800    gdb::function_view<bool (symtab *)> callback)
3801 {
3802   const char *name_basename = lbasename (name);
3803   struct dwarf2_per_objfile *dwarf2_per_objfile
3804     = get_dwarf2_per_objfile (objfile);
3805
3806   /* The rule is CUs specify all the files, including those used by
3807      any TU, so there's no need to scan TUs here.  */
3808
3809   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3810     {
3811       /* We only need to look at symtabs not already expanded.  */
3812       if (per_cu->v.quick->compunit_symtab)
3813         continue;
3814
3815       quick_file_names *file_data = dw2_get_file_names (per_cu);
3816       if (file_data == NULL)
3817         continue;
3818
3819       for (int j = 0; j < file_data->num_file_names; ++j)
3820         {
3821           const char *this_name = file_data->file_names[j];
3822           const char *this_real_name;
3823
3824           if (compare_filenames_for_search (this_name, name))
3825             {
3826               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3827                                         callback))
3828                 return true;
3829               continue;
3830             }
3831
3832           /* Before we invoke realpath, which can get expensive when many
3833              files are involved, do a quick comparison of the basenames.  */
3834           if (! basenames_may_differ
3835               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3836             continue;
3837
3838           this_real_name = dw2_get_real_path (objfile, file_data, j);
3839           if (compare_filenames_for_search (this_real_name, name))
3840             {
3841               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3842                                         callback))
3843                 return true;
3844               continue;
3845             }
3846
3847           if (real_path != NULL)
3848             {
3849               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3850               gdb_assert (IS_ABSOLUTE_PATH (name));
3851               if (this_real_name != NULL
3852                   && FILENAME_CMP (real_path, this_real_name) == 0)
3853                 {
3854                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3855                                             callback))
3856                     return true;
3857                   continue;
3858                 }
3859             }
3860         }
3861     }
3862
3863   return false;
3864 }
3865
3866 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3867
3868 struct dw2_symtab_iterator
3869 {
3870   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3871   struct dwarf2_per_objfile *dwarf2_per_objfile;
3872   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3873   int want_specific_block;
3874   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3875      Unused if !WANT_SPECIFIC_BLOCK.  */
3876   int block_index;
3877   /* The kind of symbol we're looking for.  */
3878   domain_enum domain;
3879   /* The list of CUs from the index entry of the symbol,
3880      or NULL if not found.  */
3881   offset_type *vec;
3882   /* The next element in VEC to look at.  */
3883   int next;
3884   /* The number of elements in VEC, or zero if there is no match.  */
3885   int length;
3886   /* Have we seen a global version of the symbol?
3887      If so we can ignore all further global instances.
3888      This is to work around gold/15646, inefficient gold-generated
3889      indices.  */
3890   int global_seen;
3891 };
3892
3893 /* Initialize the index symtab iterator ITER.
3894    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3895    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3896
3897 static void
3898 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3899                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3900                       int want_specific_block,
3901                       int block_index,
3902                       domain_enum domain,
3903                       const char *name)
3904 {
3905   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3906   iter->want_specific_block = want_specific_block;
3907   iter->block_index = block_index;
3908   iter->domain = domain;
3909   iter->next = 0;
3910   iter->global_seen = 0;
3911
3912   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3913
3914   /* index is NULL if OBJF_READNOW.  */
3915   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3916     iter->length = MAYBE_SWAP (*iter->vec);
3917   else
3918     {
3919       iter->vec = NULL;
3920       iter->length = 0;
3921     }
3922 }
3923
3924 /* Return the next matching CU or NULL if there are no more.  */
3925
3926 static struct dwarf2_per_cu_data *
3927 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3928 {
3929   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3930
3931   for ( ; iter->next < iter->length; ++iter->next)
3932     {
3933       offset_type cu_index_and_attrs =
3934         MAYBE_SWAP (iter->vec[iter->next + 1]);
3935       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3936       int want_static = iter->block_index != GLOBAL_BLOCK;
3937       /* This value is only valid for index versions >= 7.  */
3938       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3939       gdb_index_symbol_kind symbol_kind =
3940         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3941       /* Only check the symbol attributes if they're present.
3942          Indices prior to version 7 don't record them,
3943          and indices >= 7 may elide them for certain symbols
3944          (gold does this).  */
3945       int attrs_valid =
3946         (dwarf2_per_objfile->index_table->version >= 7
3947          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3948
3949       /* Don't crash on bad data.  */
3950       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3951                        + dwarf2_per_objfile->all_type_units.size ()))
3952         {
3953           complaint (_(".gdb_index entry has bad CU index"
3954                        " [in module %s]"),
3955                      objfile_name (dwarf2_per_objfile->objfile));
3956           continue;
3957         }
3958
3959       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3960
3961       /* Skip if already read in.  */
3962       if (per_cu->v.quick->compunit_symtab)
3963         continue;
3964
3965       /* Check static vs global.  */
3966       if (attrs_valid)
3967         {
3968           if (iter->want_specific_block
3969               && want_static != is_static)
3970             continue;
3971           /* Work around gold/15646.  */
3972           if (!is_static && iter->global_seen)
3973             continue;
3974           if (!is_static)
3975             iter->global_seen = 1;
3976         }
3977
3978       /* Only check the symbol's kind if it has one.  */
3979       if (attrs_valid)
3980         {
3981           switch (iter->domain)
3982             {
3983             case VAR_DOMAIN:
3984               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3985                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3986                   /* Some types are also in VAR_DOMAIN.  */
3987                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3988                 continue;
3989               break;
3990             case STRUCT_DOMAIN:
3991               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3992                 continue;
3993               break;
3994             case LABEL_DOMAIN:
3995               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3996                 continue;
3997               break;
3998             default:
3999               break;
4000             }
4001         }
4002
4003       ++iter->next;
4004       return per_cu;
4005     }
4006
4007   return NULL;
4008 }
4009
4010 static struct compunit_symtab *
4011 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4012                    const char *name, domain_enum domain)
4013 {
4014   struct compunit_symtab *stab_best = NULL;
4015   struct dwarf2_per_objfile *dwarf2_per_objfile
4016     = get_dwarf2_per_objfile (objfile);
4017
4018   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4019
4020   struct dw2_symtab_iterator iter;
4021   struct dwarf2_per_cu_data *per_cu;
4022
4023   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4024
4025   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4026     {
4027       struct symbol *sym, *with_opaque = NULL;
4028       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
4029       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4030       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4031
4032       sym = block_find_symbol (block, name, domain,
4033                                block_find_non_opaque_type_preferred,
4034                                &with_opaque);
4035
4036       /* Some caution must be observed with overloaded functions
4037          and methods, since the index will not contain any overload
4038          information (but NAME might contain it).  */
4039
4040       if (sym != NULL
4041           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4042         return stab;
4043       if (with_opaque != NULL
4044           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4045         stab_best = stab;
4046
4047       /* Keep looking through other CUs.  */
4048     }
4049
4050   return stab_best;
4051 }
4052
4053 static void
4054 dw2_print_stats (struct objfile *objfile)
4055 {
4056   struct dwarf2_per_objfile *dwarf2_per_objfile
4057     = get_dwarf2_per_objfile (objfile);
4058   int total = (dwarf2_per_objfile->all_comp_units.size ()
4059                + dwarf2_per_objfile->all_type_units.size ());
4060   int count = 0;
4061
4062   for (int i = 0; i < total; ++i)
4063     {
4064       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4065
4066       if (!per_cu->v.quick->compunit_symtab)
4067         ++count;
4068     }
4069   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4070   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4071 }
4072
4073 /* This dumps minimal information about the index.
4074    It is called via "mt print objfiles".
4075    One use is to verify .gdb_index has been loaded by the
4076    gdb.dwarf2/gdb-index.exp testcase.  */
4077
4078 static void
4079 dw2_dump (struct objfile *objfile)
4080 {
4081   struct dwarf2_per_objfile *dwarf2_per_objfile
4082     = get_dwarf2_per_objfile (objfile);
4083
4084   gdb_assert (dwarf2_per_objfile->using_index);
4085   printf_filtered (".gdb_index:");
4086   if (dwarf2_per_objfile->index_table != NULL)
4087     {
4088       printf_filtered (" version %d\n",
4089                        dwarf2_per_objfile->index_table->version);
4090     }
4091   else
4092     printf_filtered (" faked for \"readnow\"\n");
4093   printf_filtered ("\n");
4094 }
4095
4096 static void
4097 dw2_relocate (struct objfile *objfile,
4098               const struct section_offsets *new_offsets,
4099               const struct section_offsets *delta)
4100 {
4101   /* There's nothing to relocate here.  */
4102 }
4103
4104 static void
4105 dw2_expand_symtabs_for_function (struct objfile *objfile,
4106                                  const char *func_name)
4107 {
4108   struct dwarf2_per_objfile *dwarf2_per_objfile
4109     = get_dwarf2_per_objfile (objfile);
4110
4111   struct dw2_symtab_iterator iter;
4112   struct dwarf2_per_cu_data *per_cu;
4113
4114   /* Note: It doesn't matter what we pass for block_index here.  */
4115   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4116                         func_name);
4117
4118   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4119     dw2_instantiate_symtab (per_cu, false);
4120
4121 }
4122
4123 static void
4124 dw2_expand_all_symtabs (struct objfile *objfile)
4125 {
4126   struct dwarf2_per_objfile *dwarf2_per_objfile
4127     = get_dwarf2_per_objfile (objfile);
4128   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4129                      + dwarf2_per_objfile->all_type_units.size ());
4130
4131   for (int i = 0; i < total_units; ++i)
4132     {
4133       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4134
4135       /* We don't want to directly expand a partial CU, because if we
4136          read it with the wrong language, then assertion failures can
4137          be triggered later on.  See PR symtab/23010.  So, tell
4138          dw2_instantiate_symtab to skip partial CUs -- any important
4139          partial CU will be read via DW_TAG_imported_unit anyway.  */
4140       dw2_instantiate_symtab (per_cu, true);
4141     }
4142 }
4143
4144 static void
4145 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4146                                   const char *fullname)
4147 {
4148   struct dwarf2_per_objfile *dwarf2_per_objfile
4149     = get_dwarf2_per_objfile (objfile);
4150
4151   /* We don't need to consider type units here.
4152      This is only called for examining code, e.g. expand_line_sal.
4153      There can be an order of magnitude (or more) more type units
4154      than comp units, and we avoid them if we can.  */
4155
4156   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4157     {
4158       /* We only need to look at symtabs not already expanded.  */
4159       if (per_cu->v.quick->compunit_symtab)
4160         continue;
4161
4162       quick_file_names *file_data = dw2_get_file_names (per_cu);
4163       if (file_data == NULL)
4164         continue;
4165
4166       for (int j = 0; j < file_data->num_file_names; ++j)
4167         {
4168           const char *this_fullname = file_data->file_names[j];
4169
4170           if (filename_cmp (this_fullname, fullname) == 0)
4171             {
4172               dw2_instantiate_symtab (per_cu, false);
4173               break;
4174             }
4175         }
4176     }
4177 }
4178
4179 static void
4180 dw2_map_matching_symbols (struct objfile *objfile,
4181                           const char * name, domain_enum domain,
4182                           int global,
4183                           int (*callback) (struct block *,
4184                                            struct symbol *, void *),
4185                           void *data, symbol_name_match_type match,
4186                           symbol_compare_ftype *ordered_compare)
4187 {
4188   /* Currently unimplemented; used for Ada.  The function can be called if the
4189      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4190      does not look for non-Ada symbols this function should just return.  */
4191 }
4192
4193 /* Symbol name matcher for .gdb_index names.
4194
4195    Symbol names in .gdb_index have a few particularities:
4196
4197    - There's no indication of which is the language of each symbol.
4198
4199      Since each language has its own symbol name matching algorithm,
4200      and we don't know which language is the right one, we must match
4201      each symbol against all languages.  This would be a potential
4202      performance problem if it were not mitigated by the
4203      mapped_index::name_components lookup table, which significantly
4204      reduces the number of times we need to call into this matcher,
4205      making it a non-issue.
4206
4207    - Symbol names in the index have no overload (parameter)
4208      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4209      appear as "foo" in the index, for example.
4210
4211      This means that the lookup names passed to the symbol name
4212      matcher functions must have no parameter information either
4213      because (e.g.) symbol search name "foo" does not match
4214      lookup-name "foo(int)" [while swapping search name for lookup
4215      name would match].
4216 */
4217 class gdb_index_symbol_name_matcher
4218 {
4219 public:
4220   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4221   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4222
4223   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4224      Returns true if any matcher matches.  */
4225   bool matches (const char *symbol_name);
4226
4227 private:
4228   /* A reference to the lookup name we're matching against.  */
4229   const lookup_name_info &m_lookup_name;
4230
4231   /* A vector holding all the different symbol name matchers, for all
4232      languages.  */
4233   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4234 };
4235
4236 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4237   (const lookup_name_info &lookup_name)
4238     : m_lookup_name (lookup_name)
4239 {
4240   /* Prepare the vector of comparison functions upfront, to avoid
4241      doing the same work for each symbol.  Care is taken to avoid
4242      matching with the same matcher more than once if/when multiple
4243      languages use the same matcher function.  */
4244   auto &matchers = m_symbol_name_matcher_funcs;
4245   matchers.reserve (nr_languages);
4246
4247   matchers.push_back (default_symbol_name_matcher);
4248
4249   for (int i = 0; i < nr_languages; i++)
4250     {
4251       const language_defn *lang = language_def ((enum language) i);
4252       symbol_name_matcher_ftype *name_matcher
4253         = get_symbol_name_matcher (lang, m_lookup_name);
4254
4255       /* Don't insert the same comparison routine more than once.
4256          Note that we do this linear walk instead of a seemingly
4257          cheaper sorted insert, or use a std::set or something like
4258          that, because relative order of function addresses is not
4259          stable.  This is not a problem in practice because the number
4260          of supported languages is low, and the cost here is tiny
4261          compared to the number of searches we'll do afterwards using
4262          this object.  */
4263       if (name_matcher != default_symbol_name_matcher
4264           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4265               == matchers.end ()))
4266         matchers.push_back (name_matcher);
4267     }
4268 }
4269
4270 bool
4271 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4272 {
4273   for (auto matches_name : m_symbol_name_matcher_funcs)
4274     if (matches_name (symbol_name, m_lookup_name, NULL))
4275       return true;
4276
4277   return false;
4278 }
4279
4280 /* Starting from a search name, return the string that finds the upper
4281    bound of all strings that start with SEARCH_NAME in a sorted name
4282    list.  Returns the empty string to indicate that the upper bound is
4283    the end of the list.  */
4284
4285 static std::string
4286 make_sort_after_prefix_name (const char *search_name)
4287 {
4288   /* When looking to complete "func", we find the upper bound of all
4289      symbols that start with "func" by looking for where we'd insert
4290      the closest string that would follow "func" in lexicographical
4291      order.  Usually, that's "func"-with-last-character-incremented,
4292      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4293      will be UTF-8 multi-byte sequences, but we can't be certain.
4294      Especially mind the 0xff character, which is a valid character in
4295      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4296      rule out compilers allowing it in identifiers.  Note that
4297      conveniently, strcmp/strcasecmp are specified to compare
4298      characters interpreted as unsigned char.  So what we do is treat
4299      the whole string as a base 256 number composed of a sequence of
4300      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4301      to 0, and carries 1 to the following more-significant position.
4302      If the very first character in SEARCH_NAME ends up incremented
4303      and carries/overflows, then the upper bound is the end of the
4304      list.  The string after the empty string is also the empty
4305      string.
4306
4307      Some examples of this operation:
4308
4309        SEARCH_NAME  => "+1" RESULT
4310
4311        "abc"              => "abd"
4312        "ab\xff"           => "ac"
4313        "\xff" "a" "\xff"  => "\xff" "b"
4314        "\xff"             => ""
4315        "\xff\xff"         => ""
4316        ""                 => ""
4317
4318      Then, with these symbols for example:
4319
4320       func
4321       func1
4322       fund
4323
4324      completing "func" looks for symbols between "func" and
4325      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4326      which finds "func" and "func1", but not "fund".
4327
4328      And with:
4329
4330       funcÿ     (Latin1 'ÿ' [0xff])
4331       funcÿ1
4332       fund
4333
4334      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4335      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4336
4337      And with:
4338
4339       ÿÿ        (Latin1 'ÿ' [0xff])
4340       ÿÿ1
4341
4342      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4343      the end of the list.
4344   */
4345   std::string after = search_name;
4346   while (!after.empty () && (unsigned char) after.back () == 0xff)
4347     after.pop_back ();
4348   if (!after.empty ())
4349     after.back () = (unsigned char) after.back () + 1;
4350   return after;
4351 }
4352
4353 /* See declaration.  */
4354
4355 std::pair<std::vector<name_component>::const_iterator,
4356           std::vector<name_component>::const_iterator>
4357 mapped_index_base::find_name_components_bounds
4358   (const lookup_name_info &lookup_name_without_params) const
4359 {
4360   auto *name_cmp
4361     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4362
4363   const char *cplus
4364     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4365
4366   /* Comparison function object for lower_bound that matches against a
4367      given symbol name.  */
4368   auto lookup_compare_lower = [&] (const name_component &elem,
4369                                    const char *name)
4370     {
4371       const char *elem_qualified = this->symbol_name_at (elem.idx);
4372       const char *elem_name = elem_qualified + elem.name_offset;
4373       return name_cmp (elem_name, name) < 0;
4374     };
4375
4376   /* Comparison function object for upper_bound that matches against a
4377      given symbol name.  */
4378   auto lookup_compare_upper = [&] (const char *name,
4379                                    const name_component &elem)
4380     {
4381       const char *elem_qualified = this->symbol_name_at (elem.idx);
4382       const char *elem_name = elem_qualified + elem.name_offset;
4383       return name_cmp (name, elem_name) < 0;
4384     };
4385
4386   auto begin = this->name_components.begin ();
4387   auto end = this->name_components.end ();
4388
4389   /* Find the lower bound.  */
4390   auto lower = [&] ()
4391     {
4392       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4393         return begin;
4394       else
4395         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4396     } ();
4397
4398   /* Find the upper bound.  */
4399   auto upper = [&] ()
4400     {
4401       if (lookup_name_without_params.completion_mode ())
4402         {
4403           /* In completion mode, we want UPPER to point past all
4404              symbols names that have the same prefix.  I.e., with
4405              these symbols, and completing "func":
4406
4407               function        << lower bound
4408               function1
4409               other_function  << upper bound
4410
4411              We find the upper bound by looking for the insertion
4412              point of "func"-with-last-character-incremented,
4413              i.e. "fund".  */
4414           std::string after = make_sort_after_prefix_name (cplus);
4415           if (after.empty ())
4416             return end;
4417           return std::lower_bound (lower, end, after.c_str (),
4418                                    lookup_compare_lower);
4419         }
4420       else
4421         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4422     } ();
4423
4424   return {lower, upper};
4425 }
4426
4427 /* See declaration.  */
4428
4429 void
4430 mapped_index_base::build_name_components ()
4431 {
4432   if (!this->name_components.empty ())
4433     return;
4434
4435   this->name_components_casing = case_sensitivity;
4436   auto *name_cmp
4437     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4438
4439   /* The code below only knows how to break apart components of C++
4440      symbol names (and other languages that use '::' as
4441      namespace/module separator).  If we add support for wild matching
4442      to some language that uses some other operator (E.g., Ada, Go and
4443      D use '.'), then we'll need to try splitting the symbol name
4444      according to that language too.  Note that Ada does support wild
4445      matching, but doesn't currently support .gdb_index.  */
4446   auto count = this->symbol_name_count ();
4447   for (offset_type idx = 0; idx < count; idx++)
4448     {
4449       if (this->symbol_name_slot_invalid (idx))
4450         continue;
4451
4452       const char *name = this->symbol_name_at (idx);
4453
4454       /* Add each name component to the name component table.  */
4455       unsigned int previous_len = 0;
4456       for (unsigned int current_len = cp_find_first_component (name);
4457            name[current_len] != '\0';
4458            current_len += cp_find_first_component (name + current_len))
4459         {
4460           gdb_assert (name[current_len] == ':');
4461           this->name_components.push_back ({previous_len, idx});
4462           /* Skip the '::'.  */
4463           current_len += 2;
4464           previous_len = current_len;
4465         }
4466       this->name_components.push_back ({previous_len, idx});
4467     }
4468
4469   /* Sort name_components elements by name.  */
4470   auto name_comp_compare = [&] (const name_component &left,
4471                                 const name_component &right)
4472     {
4473       const char *left_qualified = this->symbol_name_at (left.idx);
4474       const char *right_qualified = this->symbol_name_at (right.idx);
4475
4476       const char *left_name = left_qualified + left.name_offset;
4477       const char *right_name = right_qualified + right.name_offset;
4478
4479       return name_cmp (left_name, right_name) < 0;
4480     };
4481
4482   std::sort (this->name_components.begin (),
4483              this->name_components.end (),
4484              name_comp_compare);
4485 }
4486
4487 /* Helper for dw2_expand_symtabs_matching that works with a
4488    mapped_index_base instead of the containing objfile.  This is split
4489    to a separate function in order to be able to unit test the
4490    name_components matching using a mock mapped_index_base.  For each
4491    symbol name that matches, calls MATCH_CALLBACK, passing it the
4492    symbol's index in the mapped_index_base symbol table.  */
4493
4494 static void
4495 dw2_expand_symtabs_matching_symbol
4496   (mapped_index_base &index,
4497    const lookup_name_info &lookup_name_in,
4498    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4499    enum search_domain kind,
4500    gdb::function_view<void (offset_type)> match_callback)
4501 {
4502   lookup_name_info lookup_name_without_params
4503     = lookup_name_in.make_ignore_params ();
4504   gdb_index_symbol_name_matcher lookup_name_matcher
4505     (lookup_name_without_params);
4506
4507   /* Build the symbol name component sorted vector, if we haven't
4508      yet.  */
4509   index.build_name_components ();
4510
4511   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4512
4513   /* Now for each symbol name in range, check to see if we have a name
4514      match, and if so, call the MATCH_CALLBACK callback.  */
4515
4516   /* The same symbol may appear more than once in the range though.
4517      E.g., if we're looking for symbols that complete "w", and we have
4518      a symbol named "w1::w2", we'll find the two name components for
4519      that same symbol in the range.  To be sure we only call the
4520      callback once per symbol, we first collect the symbol name
4521      indexes that matched in a temporary vector and ignore
4522      duplicates.  */
4523   std::vector<offset_type> matches;
4524   matches.reserve (std::distance (bounds.first, bounds.second));
4525
4526   for (; bounds.first != bounds.second; ++bounds.first)
4527     {
4528       const char *qualified = index.symbol_name_at (bounds.first->idx);
4529
4530       if (!lookup_name_matcher.matches (qualified)
4531           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4532         continue;
4533
4534       matches.push_back (bounds.first->idx);
4535     }
4536
4537   std::sort (matches.begin (), matches.end ());
4538
4539   /* Finally call the callback, once per match.  */
4540   ULONGEST prev = -1;
4541   for (offset_type idx : matches)
4542     {
4543       if (prev != idx)
4544         {
4545           match_callback (idx);
4546           prev = idx;
4547         }
4548     }
4549
4550   /* Above we use a type wider than idx's for 'prev', since 0 and
4551      (offset_type)-1 are both possible values.  */
4552   static_assert (sizeof (prev) > sizeof (offset_type), "");
4553 }
4554
4555 #if GDB_SELF_TEST
4556
4557 namespace selftests { namespace dw2_expand_symtabs_matching {
4558
4559 /* A mock .gdb_index/.debug_names-like name index table, enough to
4560    exercise dw2_expand_symtabs_matching_symbol, which works with the
4561    mapped_index_base interface.  Builds an index from the symbol list
4562    passed as parameter to the constructor.  */
4563 class mock_mapped_index : public mapped_index_base
4564 {
4565 public:
4566   mock_mapped_index (gdb::array_view<const char *> symbols)
4567     : m_symbol_table (symbols)
4568   {}
4569
4570   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4571
4572   /* Return the number of names in the symbol table.  */
4573   size_t symbol_name_count () const override
4574   {
4575     return m_symbol_table.size ();
4576   }
4577
4578   /* Get the name of the symbol at IDX in the symbol table.  */
4579   const char *symbol_name_at (offset_type idx) const override
4580   {
4581     return m_symbol_table[idx];
4582   }
4583
4584 private:
4585   gdb::array_view<const char *> m_symbol_table;
4586 };
4587
4588 /* Convenience function that converts a NULL pointer to a "<null>"
4589    string, to pass to print routines.  */
4590
4591 static const char *
4592 string_or_null (const char *str)
4593 {
4594   return str != NULL ? str : "<null>";
4595 }
4596
4597 /* Check if a lookup_name_info built from
4598    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4599    index.  EXPECTED_LIST is the list of expected matches, in expected
4600    matching order.  If no match expected, then an empty list is
4601    specified.  Returns true on success.  On failure prints a warning
4602    indicating the file:line that failed, and returns false.  */
4603
4604 static bool
4605 check_match (const char *file, int line,
4606              mock_mapped_index &mock_index,
4607              const char *name, symbol_name_match_type match_type,
4608              bool completion_mode,
4609              std::initializer_list<const char *> expected_list)
4610 {
4611   lookup_name_info lookup_name (name, match_type, completion_mode);
4612
4613   bool matched = true;
4614
4615   auto mismatch = [&] (const char *expected_str,
4616                        const char *got)
4617   {
4618     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4619                "expected=\"%s\", got=\"%s\"\n"),
4620              file, line,
4621              (match_type == symbol_name_match_type::FULL
4622               ? "FULL" : "WILD"),
4623              name, string_or_null (expected_str), string_or_null (got));
4624     matched = false;
4625   };
4626
4627   auto expected_it = expected_list.begin ();
4628   auto expected_end = expected_list.end ();
4629
4630   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4631                                       NULL, ALL_DOMAIN,
4632                                       [&] (offset_type idx)
4633   {
4634     const char *matched_name = mock_index.symbol_name_at (idx);
4635     const char *expected_str
4636       = expected_it == expected_end ? NULL : *expected_it++;
4637
4638     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4639       mismatch (expected_str, matched_name);
4640   });
4641
4642   const char *expected_str
4643   = expected_it == expected_end ? NULL : *expected_it++;
4644   if (expected_str != NULL)
4645     mismatch (expected_str, NULL);
4646
4647   return matched;
4648 }
4649
4650 /* The symbols added to the mock mapped_index for testing (in
4651    canonical form).  */
4652 static const char *test_symbols[] = {
4653   "function",
4654   "std::bar",
4655   "std::zfunction",
4656   "std::zfunction2",
4657   "w1::w2",
4658   "ns::foo<char*>",
4659   "ns::foo<int>",
4660   "ns::foo<long>",
4661   "ns2::tmpl<int>::foo2",
4662   "(anonymous namespace)::A::B::C",
4663
4664   /* These are used to check that the increment-last-char in the
4665      matching algorithm for completion doesn't match "t1_fund" when
4666      completing "t1_func".  */
4667   "t1_func",
4668   "t1_func1",
4669   "t1_fund",
4670   "t1_fund1",
4671
4672   /* A UTF-8 name with multi-byte sequences to make sure that
4673      cp-name-parser understands this as a single identifier ("função"
4674      is "function" in PT).  */
4675   u8"u8função",
4676
4677   /* \377 (0xff) is Latin1 'ÿ'.  */
4678   "yfunc\377",
4679
4680   /* \377 (0xff) is Latin1 'ÿ'.  */
4681   "\377",
4682   "\377\377123",
4683
4684   /* A name with all sorts of complications.  Starts with "z" to make
4685      it easier for the completion tests below.  */
4686 #define Z_SYM_NAME \
4687   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4688     "::tuple<(anonymous namespace)::ui*, " \
4689     "std::default_delete<(anonymous namespace)::ui>, void>"
4690
4691   Z_SYM_NAME
4692 };
4693
4694 /* Returns true if the mapped_index_base::find_name_component_bounds
4695    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4696    in completion mode.  */
4697
4698 static bool
4699 check_find_bounds_finds (mapped_index_base &index,
4700                          const char *search_name,
4701                          gdb::array_view<const char *> expected_syms)
4702 {
4703   lookup_name_info lookup_name (search_name,
4704                                 symbol_name_match_type::FULL, true);
4705
4706   auto bounds = index.find_name_components_bounds (lookup_name);
4707
4708   size_t distance = std::distance (bounds.first, bounds.second);
4709   if (distance != expected_syms.size ())
4710     return false;
4711
4712   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4713     {
4714       auto nc_elem = bounds.first + exp_elem;
4715       const char *qualified = index.symbol_name_at (nc_elem->idx);
4716       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4717         return false;
4718     }
4719
4720   return true;
4721 }
4722
4723 /* Test the lower-level mapped_index::find_name_component_bounds
4724    method.  */
4725
4726 static void
4727 test_mapped_index_find_name_component_bounds ()
4728 {
4729   mock_mapped_index mock_index (test_symbols);
4730
4731   mock_index.build_name_components ();
4732
4733   /* Test the lower-level mapped_index::find_name_component_bounds
4734      method in completion mode.  */
4735   {
4736     static const char *expected_syms[] = {
4737       "t1_func",
4738       "t1_func1",
4739     };
4740
4741     SELF_CHECK (check_find_bounds_finds (mock_index,
4742                                          "t1_func", expected_syms));
4743   }
4744
4745   /* Check that the increment-last-char in the name matching algorithm
4746      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4747   {
4748     static const char *expected_syms1[] = {
4749       "\377",
4750       "\377\377123",
4751     };
4752     SELF_CHECK (check_find_bounds_finds (mock_index,
4753                                          "\377", expected_syms1));
4754
4755     static const char *expected_syms2[] = {
4756       "\377\377123",
4757     };
4758     SELF_CHECK (check_find_bounds_finds (mock_index,
4759                                          "\377\377", expected_syms2));
4760   }
4761 }
4762
4763 /* Test dw2_expand_symtabs_matching_symbol.  */
4764
4765 static void
4766 test_dw2_expand_symtabs_matching_symbol ()
4767 {
4768   mock_mapped_index mock_index (test_symbols);
4769
4770   /* We let all tests run until the end even if some fails, for debug
4771      convenience.  */
4772   bool any_mismatch = false;
4773
4774   /* Create the expected symbols list (an initializer_list).  Needed
4775      because lists have commas, and we need to pass them to CHECK,
4776      which is a macro.  */
4777 #define EXPECT(...) { __VA_ARGS__ }
4778
4779   /* Wrapper for check_match that passes down the current
4780      __FILE__/__LINE__.  */
4781 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4782   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4783                                 mock_index,                             \
4784                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4785                                 EXPECTED_LIST)
4786
4787   /* Identity checks.  */
4788   for (const char *sym : test_symbols)
4789     {
4790       /* Should be able to match all existing symbols.  */
4791       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4792                    EXPECT (sym));
4793
4794       /* Should be able to match all existing symbols with
4795          parameters.  */
4796       std::string with_params = std::string (sym) + "(int)";
4797       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4798                    EXPECT (sym));
4799
4800       /* Should be able to match all existing symbols with
4801          parameters and qualifiers.  */
4802       with_params = std::string (sym) + " ( int ) const";
4803       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4804                    EXPECT (sym));
4805
4806       /* This should really find sym, but cp-name-parser.y doesn't
4807          know about lvalue/rvalue qualifiers yet.  */
4808       with_params = std::string (sym) + " ( int ) &&";
4809       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4810                    {});
4811     }
4812
4813   /* Check that the name matching algorithm for completion doesn't get
4814      confused with Latin1 'ÿ' / 0xff.  */
4815   {
4816     static const char str[] = "\377";
4817     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4818                  EXPECT ("\377", "\377\377123"));
4819   }
4820
4821   /* Check that the increment-last-char in the matching algorithm for
4822      completion doesn't match "t1_fund" when completing "t1_func".  */
4823   {
4824     static const char str[] = "t1_func";
4825     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4826                  EXPECT ("t1_func", "t1_func1"));
4827   }
4828
4829   /* Check that completion mode works at each prefix of the expected
4830      symbol name.  */
4831   {
4832     static const char str[] = "function(int)";
4833     size_t len = strlen (str);
4834     std::string lookup;
4835
4836     for (size_t i = 1; i < len; i++)
4837       {
4838         lookup.assign (str, i);
4839         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4840                      EXPECT ("function"));
4841       }
4842   }
4843
4844   /* While "w" is a prefix of both components, the match function
4845      should still only be called once.  */
4846   {
4847     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4848                  EXPECT ("w1::w2"));
4849     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4850                  EXPECT ("w1::w2"));
4851   }
4852
4853   /* Same, with a "complicated" symbol.  */
4854   {
4855     static const char str[] = Z_SYM_NAME;
4856     size_t len = strlen (str);
4857     std::string lookup;
4858
4859     for (size_t i = 1; i < len; i++)
4860       {
4861         lookup.assign (str, i);
4862         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4863                      EXPECT (Z_SYM_NAME));
4864       }
4865   }
4866
4867   /* In FULL mode, an incomplete symbol doesn't match.  */
4868   {
4869     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4870                  {});
4871   }
4872
4873   /* A complete symbol with parameters matches any overload, since the
4874      index has no overload info.  */
4875   {
4876     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4877                  EXPECT ("std::zfunction", "std::zfunction2"));
4878     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4879                  EXPECT ("std::zfunction", "std::zfunction2"));
4880     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4881                  EXPECT ("std::zfunction", "std::zfunction2"));
4882   }
4883
4884   /* Check that whitespace is ignored appropriately.  A symbol with a
4885      template argument list. */
4886   {
4887     static const char expected[] = "ns::foo<int>";
4888     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4889                  EXPECT (expected));
4890     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4891                  EXPECT (expected));
4892   }
4893
4894   /* Check that whitespace is ignored appropriately.  A symbol with a
4895      template argument list that includes a pointer.  */
4896   {
4897     static const char expected[] = "ns::foo<char*>";
4898     /* Try both completion and non-completion modes.  */
4899     static const bool completion_mode[2] = {false, true};
4900     for (size_t i = 0; i < 2; i++)
4901       {
4902         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4903                      completion_mode[i], EXPECT (expected));
4904         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4905                      completion_mode[i], EXPECT (expected));
4906
4907         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4908                      completion_mode[i], EXPECT (expected));
4909         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4910                      completion_mode[i], EXPECT (expected));
4911       }
4912   }
4913
4914   {
4915     /* Check method qualifiers are ignored.  */
4916     static const char expected[] = "ns::foo<char*>";
4917     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4918                  symbol_name_match_type::FULL, true, EXPECT (expected));
4919     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4920                  symbol_name_match_type::FULL, true, EXPECT (expected));
4921     CHECK_MATCH ("foo < char * >  ( int ) const",
4922                  symbol_name_match_type::WILD, true, EXPECT (expected));
4923     CHECK_MATCH ("foo < char * >  ( int ) &&",
4924                  symbol_name_match_type::WILD, true, EXPECT (expected));
4925   }
4926
4927   /* Test lookup names that don't match anything.  */
4928   {
4929     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4930                  {});
4931
4932     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4933                  {});
4934   }
4935
4936   /* Some wild matching tests, exercising "(anonymous namespace)",
4937      which should not be confused with a parameter list.  */
4938   {
4939     static const char *syms[] = {
4940       "A::B::C",
4941       "B::C",
4942       "C",
4943       "A :: B :: C ( int )",
4944       "B :: C ( int )",
4945       "C ( int )",
4946     };
4947
4948     for (const char *s : syms)
4949       {
4950         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4951                      EXPECT ("(anonymous namespace)::A::B::C"));
4952       }
4953   }
4954
4955   {
4956     static const char expected[] = "ns2::tmpl<int>::foo2";
4957     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4958                  EXPECT (expected));
4959     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4960                  EXPECT (expected));
4961   }
4962
4963   SELF_CHECK (!any_mismatch);
4964
4965 #undef EXPECT
4966 #undef CHECK_MATCH
4967 }
4968
4969 static void
4970 run_test ()
4971 {
4972   test_mapped_index_find_name_component_bounds ();
4973   test_dw2_expand_symtabs_matching_symbol ();
4974 }
4975
4976 }} // namespace selftests::dw2_expand_symtabs_matching
4977
4978 #endif /* GDB_SELF_TEST */
4979
4980 /* If FILE_MATCHER is NULL or if PER_CU has
4981    dwarf2_per_cu_quick_data::MARK set (see
4982    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4983    EXPANSION_NOTIFY on it.  */
4984
4985 static void
4986 dw2_expand_symtabs_matching_one
4987   (struct dwarf2_per_cu_data *per_cu,
4988    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4989    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4990 {
4991   if (file_matcher == NULL || per_cu->v.quick->mark)
4992     {
4993       bool symtab_was_null
4994         = (per_cu->v.quick->compunit_symtab == NULL);
4995
4996       dw2_instantiate_symtab (per_cu, false);
4997
4998       if (expansion_notify != NULL
4999           && symtab_was_null
5000           && per_cu->v.quick->compunit_symtab != NULL)
5001         expansion_notify (per_cu->v.quick->compunit_symtab);
5002     }
5003 }
5004
5005 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5006    matched, to expand corresponding CUs that were marked.  IDX is the
5007    index of the symbol name that matched.  */
5008
5009 static void
5010 dw2_expand_marked_cus
5011   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5012    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5013    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5014    search_domain kind)
5015 {
5016   offset_type *vec, vec_len, vec_idx;
5017   bool global_seen = false;
5018   mapped_index &index = *dwarf2_per_objfile->index_table;
5019
5020   vec = (offset_type *) (index.constant_pool
5021                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5022   vec_len = MAYBE_SWAP (vec[0]);
5023   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5024     {
5025       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5026       /* This value is only valid for index versions >= 7.  */
5027       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5028       gdb_index_symbol_kind symbol_kind =
5029         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5030       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5031       /* Only check the symbol attributes if they're present.
5032          Indices prior to version 7 don't record them,
5033          and indices >= 7 may elide them for certain symbols
5034          (gold does this).  */
5035       int attrs_valid =
5036         (index.version >= 7
5037          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5038
5039       /* Work around gold/15646.  */
5040       if (attrs_valid)
5041         {
5042           if (!is_static && global_seen)
5043             continue;
5044           if (!is_static)
5045             global_seen = true;
5046         }
5047
5048       /* Only check the symbol's kind if it has one.  */
5049       if (attrs_valid)
5050         {
5051           switch (kind)
5052             {
5053             case VARIABLES_DOMAIN:
5054               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5055                 continue;
5056               break;
5057             case FUNCTIONS_DOMAIN:
5058               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5059                 continue;
5060               break;
5061             case TYPES_DOMAIN:
5062               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5063                 continue;
5064               break;
5065             default:
5066               break;
5067             }
5068         }
5069
5070       /* Don't crash on bad data.  */
5071       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5072                        + dwarf2_per_objfile->all_type_units.size ()))
5073         {
5074           complaint (_(".gdb_index entry has bad CU index"
5075                        " [in module %s]"),
5076                        objfile_name (dwarf2_per_objfile->objfile));
5077           continue;
5078         }
5079
5080       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5081       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5082                                        expansion_notify);
5083     }
5084 }
5085
5086 /* If FILE_MATCHER is non-NULL, set all the
5087    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5088    that match FILE_MATCHER.  */
5089
5090 static void
5091 dw_expand_symtabs_matching_file_matcher
5092   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5093    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5094 {
5095   if (file_matcher == NULL)
5096     return;
5097
5098   objfile *const objfile = dwarf2_per_objfile->objfile;
5099
5100   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5101                                             htab_eq_pointer,
5102                                             NULL, xcalloc, xfree));
5103   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5104                                                 htab_eq_pointer,
5105                                                 NULL, xcalloc, xfree));
5106
5107   /* The rule is CUs specify all the files, including those used by
5108      any TU, so there's no need to scan TUs here.  */
5109
5110   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5111     {
5112       QUIT;
5113
5114       per_cu->v.quick->mark = 0;
5115
5116       /* We only need to look at symtabs not already expanded.  */
5117       if (per_cu->v.quick->compunit_symtab)
5118         continue;
5119
5120       quick_file_names *file_data = dw2_get_file_names (per_cu);
5121       if (file_data == NULL)
5122         continue;
5123
5124       if (htab_find (visited_not_found.get (), file_data) != NULL)
5125         continue;
5126       else if (htab_find (visited_found.get (), file_data) != NULL)
5127         {
5128           per_cu->v.quick->mark = 1;
5129           continue;
5130         }
5131
5132       for (int j = 0; j < file_data->num_file_names; ++j)
5133         {
5134           const char *this_real_name;
5135
5136           if (file_matcher (file_data->file_names[j], false))
5137             {
5138               per_cu->v.quick->mark = 1;
5139               break;
5140             }
5141
5142           /* Before we invoke realpath, which can get expensive when many
5143              files are involved, do a quick comparison of the basenames.  */
5144           if (!basenames_may_differ
5145               && !file_matcher (lbasename (file_data->file_names[j]),
5146                                 true))
5147             continue;
5148
5149           this_real_name = dw2_get_real_path (objfile, file_data, j);
5150           if (file_matcher (this_real_name, false))
5151             {
5152               per_cu->v.quick->mark = 1;
5153               break;
5154             }
5155         }
5156
5157       void **slot = htab_find_slot (per_cu->v.quick->mark
5158                                     ? visited_found.get ()
5159                                     : visited_not_found.get (),
5160                                     file_data, INSERT);
5161       *slot = file_data;
5162     }
5163 }
5164
5165 static void
5166 dw2_expand_symtabs_matching
5167   (struct objfile *objfile,
5168    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5169    const lookup_name_info &lookup_name,
5170    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5171    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5172    enum search_domain kind)
5173 {
5174   struct dwarf2_per_objfile *dwarf2_per_objfile
5175     = get_dwarf2_per_objfile (objfile);
5176
5177   /* index_table is NULL if OBJF_READNOW.  */
5178   if (!dwarf2_per_objfile->index_table)
5179     return;
5180
5181   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5182
5183   mapped_index &index = *dwarf2_per_objfile->index_table;
5184
5185   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5186                                       symbol_matcher,
5187                                       kind, [&] (offset_type idx)
5188     {
5189       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5190                              expansion_notify, kind);
5191     });
5192 }
5193
5194 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5195    symtab.  */
5196
5197 static struct compunit_symtab *
5198 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5199                                           CORE_ADDR pc)
5200 {
5201   int i;
5202
5203   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5204       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5205     return cust;
5206
5207   if (cust->includes == NULL)
5208     return NULL;
5209
5210   for (i = 0; cust->includes[i]; ++i)
5211     {
5212       struct compunit_symtab *s = cust->includes[i];
5213
5214       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5215       if (s != NULL)
5216         return s;
5217     }
5218
5219   return NULL;
5220 }
5221
5222 static struct compunit_symtab *
5223 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5224                                   struct bound_minimal_symbol msymbol,
5225                                   CORE_ADDR pc,
5226                                   struct obj_section *section,
5227                                   int warn_if_readin)
5228 {
5229   struct dwarf2_per_cu_data *data;
5230   struct compunit_symtab *result;
5231
5232   if (!objfile->psymtabs_addrmap)
5233     return NULL;
5234
5235   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5236                                                      pc);
5237   if (!data)
5238     return NULL;
5239
5240   if (warn_if_readin && data->v.quick->compunit_symtab)
5241     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5242              paddress (get_objfile_arch (objfile), pc));
5243
5244   result
5245     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
5246                                                                         false),
5247                                                 pc);
5248   gdb_assert (result != NULL);
5249   return result;
5250 }
5251
5252 static void
5253 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5254                           void *data, int need_fullname)
5255 {
5256   struct dwarf2_per_objfile *dwarf2_per_objfile
5257     = get_dwarf2_per_objfile (objfile);
5258
5259   if (!dwarf2_per_objfile->filenames_cache)
5260     {
5261       dwarf2_per_objfile->filenames_cache.emplace ();
5262
5263       htab_up visited (htab_create_alloc (10,
5264                                           htab_hash_pointer, htab_eq_pointer,
5265                                           NULL, xcalloc, xfree));
5266
5267       /* The rule is CUs specify all the files, including those used
5268          by any TU, so there's no need to scan TUs here.  We can
5269          ignore file names coming from already-expanded CUs.  */
5270
5271       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5272         {
5273           if (per_cu->v.quick->compunit_symtab)
5274             {
5275               void **slot = htab_find_slot (visited.get (),
5276                                             per_cu->v.quick->file_names,
5277                                             INSERT);
5278
5279               *slot = per_cu->v.quick->file_names;
5280             }
5281         }
5282
5283       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5284         {
5285           /* We only need to look at symtabs not already expanded.  */
5286           if (per_cu->v.quick->compunit_symtab)
5287             continue;
5288
5289           quick_file_names *file_data = dw2_get_file_names (per_cu);
5290           if (file_data == NULL)
5291             continue;
5292
5293           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5294           if (*slot)
5295             {
5296               /* Already visited.  */
5297               continue;
5298             }
5299           *slot = file_data;
5300
5301           for (int j = 0; j < file_data->num_file_names; ++j)
5302             {
5303               const char *filename = file_data->file_names[j];
5304               dwarf2_per_objfile->filenames_cache->seen (filename);
5305             }
5306         }
5307     }
5308
5309   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5310     {
5311       gdb::unique_xmalloc_ptr<char> this_real_name;
5312
5313       if (need_fullname)
5314         this_real_name = gdb_realpath (filename);
5315       (*fun) (filename, this_real_name.get (), data);
5316     });
5317 }
5318
5319 static int
5320 dw2_has_symbols (struct objfile *objfile)
5321 {
5322   return 1;
5323 }
5324
5325 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5326 {
5327   dw2_has_symbols,
5328   dw2_find_last_source_symtab,
5329   dw2_forget_cached_source_info,
5330   dw2_map_symtabs_matching_filename,
5331   dw2_lookup_symbol,
5332   dw2_print_stats,
5333   dw2_dump,
5334   dw2_relocate,
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_relocate,
6148   dw2_debug_names_expand_symtabs_for_function,
6149   dw2_expand_all_symtabs,
6150   dw2_expand_symtabs_with_fullname,
6151   dw2_map_matching_symbols,
6152   dw2_debug_names_expand_symtabs_matching,
6153   dw2_find_pc_sect_compunit_symtab,
6154   NULL,
6155   dw2_map_symbol_filenames
6156 };
6157
6158 /* See symfile.h.  */
6159
6160 bool
6161 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6162 {
6163   struct dwarf2_per_objfile *dwarf2_per_objfile
6164     = get_dwarf2_per_objfile (objfile);
6165
6166   /* If we're about to read full symbols, don't bother with the
6167      indices.  In this case we also don't care if some other debug
6168      format is making psymtabs, because they are all about to be
6169      expanded anyway.  */
6170   if ((objfile->flags & OBJF_READNOW))
6171     {
6172       dwarf2_per_objfile->using_index = 1;
6173       create_all_comp_units (dwarf2_per_objfile);
6174       create_all_type_units (dwarf2_per_objfile);
6175       dwarf2_per_objfile->quick_file_names_table
6176         = create_quick_file_names_table
6177             (dwarf2_per_objfile->all_comp_units.size ());
6178
6179       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6180                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6181         {
6182           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6183
6184           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6185                                             struct dwarf2_per_cu_quick_data);
6186         }
6187
6188       /* Return 1 so that gdb sees the "quick" functions.  However,
6189          these functions will be no-ops because we will have expanded
6190          all symtabs.  */
6191       *index_kind = dw_index_kind::GDB_INDEX;
6192       return true;
6193     }
6194
6195   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6196     {
6197       *index_kind = dw_index_kind::DEBUG_NAMES;
6198       return true;
6199     }
6200
6201   if (dwarf2_read_gdb_index (dwarf2_per_objfile))
6202     {
6203       *index_kind = dw_index_kind::GDB_INDEX;
6204       return true;
6205     }
6206
6207   return false;
6208 }
6209
6210 \f
6211
6212 /* Build a partial symbol table.  */
6213
6214 void
6215 dwarf2_build_psymtabs (struct objfile *objfile)
6216 {
6217   struct dwarf2_per_objfile *dwarf2_per_objfile
6218     = get_dwarf2_per_objfile (objfile);
6219
6220   if (objfile->global_psymbols.capacity () == 0
6221       && objfile->static_psymbols.capacity () == 0)
6222     init_psymbol_list (objfile, 1024);
6223
6224   TRY
6225     {
6226       /* This isn't really ideal: all the data we allocate on the
6227          objfile's obstack is still uselessly kept around.  However,
6228          freeing it seems unsafe.  */
6229       psymtab_discarder psymtabs (objfile);
6230       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6231       psymtabs.keep ();
6232     }
6233   CATCH (except, RETURN_MASK_ERROR)
6234     {
6235       exception_print (gdb_stderr, except);
6236     }
6237   END_CATCH
6238 }
6239
6240 /* Return the total length of the CU described by HEADER.  */
6241
6242 static unsigned int
6243 get_cu_length (const struct comp_unit_head *header)
6244 {
6245   return header->initial_length_size + header->length;
6246 }
6247
6248 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6249
6250 static inline bool
6251 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6252 {
6253   sect_offset bottom = cu_header->sect_off;
6254   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6255
6256   return sect_off >= bottom && sect_off < top;
6257 }
6258
6259 /* Find the base address of the compilation unit for range lists and
6260    location lists.  It will normally be specified by DW_AT_low_pc.
6261    In DWARF-3 draft 4, the base address could be overridden by
6262    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6263    compilation units with discontinuous ranges.  */
6264
6265 static void
6266 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6267 {
6268   struct attribute *attr;
6269
6270   cu->base_known = 0;
6271   cu->base_address = 0;
6272
6273   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6274   if (attr)
6275     {
6276       cu->base_address = attr_value_as_address (attr);
6277       cu->base_known = 1;
6278     }
6279   else
6280     {
6281       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6282       if (attr)
6283         {
6284           cu->base_address = attr_value_as_address (attr);
6285           cu->base_known = 1;
6286         }
6287     }
6288 }
6289
6290 /* Read in the comp unit header information from the debug_info at info_ptr.
6291    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6292    NOTE: This leaves members offset, first_die_offset to be filled in
6293    by the caller.  */
6294
6295 static const gdb_byte *
6296 read_comp_unit_head (struct comp_unit_head *cu_header,
6297                      const gdb_byte *info_ptr,
6298                      struct dwarf2_section_info *section,
6299                      rcuh_kind section_kind)
6300 {
6301   int signed_addr;
6302   unsigned int bytes_read;
6303   const char *filename = get_section_file_name (section);
6304   bfd *abfd = get_section_bfd_owner (section);
6305
6306   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6307   cu_header->initial_length_size = bytes_read;
6308   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6309   info_ptr += bytes_read;
6310   cu_header->version = read_2_bytes (abfd, info_ptr);
6311   if (cu_header->version < 2 || cu_header->version > 5)
6312     error (_("Dwarf Error: wrong version in compilation unit header "
6313            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6314            cu_header->version, filename);
6315   info_ptr += 2;
6316   if (cu_header->version < 5)
6317     switch (section_kind)
6318       {
6319       case rcuh_kind::COMPILE:
6320         cu_header->unit_type = DW_UT_compile;
6321         break;
6322       case rcuh_kind::TYPE:
6323         cu_header->unit_type = DW_UT_type;
6324         break;
6325       default:
6326         internal_error (__FILE__, __LINE__,
6327                         _("read_comp_unit_head: invalid section_kind"));
6328       }
6329   else
6330     {
6331       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6332                                                  (read_1_byte (abfd, info_ptr));
6333       info_ptr += 1;
6334       switch (cu_header->unit_type)
6335         {
6336         case DW_UT_compile:
6337           if (section_kind != rcuh_kind::COMPILE)
6338             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6339                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6340                    filename);
6341           break;
6342         case DW_UT_type:
6343           section_kind = rcuh_kind::TYPE;
6344           break;
6345         default:
6346           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6347                  "(is %d, should be %d or %d) [in module %s]"),
6348                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6349         }
6350
6351       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6352       info_ptr += 1;
6353     }
6354   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6355                                                           cu_header,
6356                                                           &bytes_read);
6357   info_ptr += bytes_read;
6358   if (cu_header->version < 5)
6359     {
6360       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6361       info_ptr += 1;
6362     }
6363   signed_addr = bfd_get_sign_extend_vma (abfd);
6364   if (signed_addr < 0)
6365     internal_error (__FILE__, __LINE__,
6366                     _("read_comp_unit_head: dwarf from non elf file"));
6367   cu_header->signed_addr_p = signed_addr;
6368
6369   if (section_kind == rcuh_kind::TYPE)
6370     {
6371       LONGEST type_offset;
6372
6373       cu_header->signature = read_8_bytes (abfd, info_ptr);
6374       info_ptr += 8;
6375
6376       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6377       info_ptr += bytes_read;
6378       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6379       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6380         error (_("Dwarf Error: Too big type_offset in compilation unit "
6381                "header (is %s) [in module %s]"), plongest (type_offset),
6382                filename);
6383     }
6384
6385   return info_ptr;
6386 }
6387
6388 /* Helper function that returns the proper abbrev section for
6389    THIS_CU.  */
6390
6391 static struct dwarf2_section_info *
6392 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6393 {
6394   struct dwarf2_section_info *abbrev;
6395   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6396
6397   if (this_cu->is_dwz)
6398     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6399   else
6400     abbrev = &dwarf2_per_objfile->abbrev;
6401
6402   return abbrev;
6403 }
6404
6405 /* Subroutine of read_and_check_comp_unit_head and
6406    read_and_check_type_unit_head to simplify them.
6407    Perform various error checking on the header.  */
6408
6409 static void
6410 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6411                             struct comp_unit_head *header,
6412                             struct dwarf2_section_info *section,
6413                             struct dwarf2_section_info *abbrev_section)
6414 {
6415   const char *filename = get_section_file_name (section);
6416
6417   if (to_underlying (header->abbrev_sect_off)
6418       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6419     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6420            "(offset %s + 6) [in module %s]"),
6421            sect_offset_str (header->abbrev_sect_off),
6422            sect_offset_str (header->sect_off),
6423            filename);
6424
6425   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6426      avoid potential 32-bit overflow.  */
6427   if (((ULONGEST) header->sect_off + get_cu_length (header))
6428       > section->size)
6429     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6430            "(offset %s + 0) [in module %s]"),
6431            header->length, sect_offset_str (header->sect_off),
6432            filename);
6433 }
6434
6435 /* Read in a CU/TU header and perform some basic error checking.
6436    The contents of the header are stored in HEADER.
6437    The result is a pointer to the start of the first DIE.  */
6438
6439 static const gdb_byte *
6440 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6441                                struct comp_unit_head *header,
6442                                struct dwarf2_section_info *section,
6443                                struct dwarf2_section_info *abbrev_section,
6444                                const gdb_byte *info_ptr,
6445                                rcuh_kind section_kind)
6446 {
6447   const gdb_byte *beg_of_comp_unit = info_ptr;
6448
6449   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6450
6451   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6452
6453   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6454
6455   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6456                               abbrev_section);
6457
6458   return info_ptr;
6459 }
6460
6461 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6462
6463 static sect_offset
6464 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6465                     struct dwarf2_section_info *section,
6466                     sect_offset sect_off)
6467 {
6468   bfd *abfd = get_section_bfd_owner (section);
6469   const gdb_byte *info_ptr;
6470   unsigned int initial_length_size, offset_size;
6471   uint16_t version;
6472
6473   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6474   info_ptr = section->buffer + to_underlying (sect_off);
6475   read_initial_length (abfd, info_ptr, &initial_length_size);
6476   offset_size = initial_length_size == 4 ? 4 : 8;
6477   info_ptr += initial_length_size;
6478
6479   version = read_2_bytes (abfd, info_ptr);
6480   info_ptr += 2;
6481   if (version >= 5)
6482     {
6483       /* Skip unit type and address size.  */
6484       info_ptr += 2;
6485     }
6486
6487   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6488 }
6489
6490 /* Allocate a new partial symtab for file named NAME and mark this new
6491    partial symtab as being an include of PST.  */
6492
6493 static void
6494 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6495                                struct objfile *objfile)
6496 {
6497   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6498
6499   if (!IS_ABSOLUTE_PATH (subpst->filename))
6500     {
6501       /* It shares objfile->objfile_obstack.  */
6502       subpst->dirname = pst->dirname;
6503     }
6504
6505   subpst->textlow = 0;
6506   subpst->texthigh = 0;
6507
6508   subpst->dependencies
6509     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6510   subpst->dependencies[0] = pst;
6511   subpst->number_of_dependencies = 1;
6512
6513   subpst->globals_offset = 0;
6514   subpst->n_global_syms = 0;
6515   subpst->statics_offset = 0;
6516   subpst->n_static_syms = 0;
6517   subpst->compunit_symtab = NULL;
6518   subpst->read_symtab = pst->read_symtab;
6519   subpst->readin = 0;
6520
6521   /* No private part is necessary for include psymtabs.  This property
6522      can be used to differentiate between such include psymtabs and
6523      the regular ones.  */
6524   subpst->read_symtab_private = NULL;
6525 }
6526
6527 /* Read the Line Number Program data and extract the list of files
6528    included by the source file represented by PST.  Build an include
6529    partial symtab for each of these included files.  */
6530
6531 static void
6532 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6533                                struct die_info *die,
6534                                struct partial_symtab *pst)
6535 {
6536   line_header_up lh;
6537   struct attribute *attr;
6538
6539   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6540   if (attr)
6541     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6542   if (lh == NULL)
6543     return;  /* No linetable, so no includes.  */
6544
6545   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6546   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 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       char *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 = xstrprintf ("<type_units_%d>",
7765                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7766       else
7767         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
7768
7769       pst = create_partial_symtab (per_cu, name);
7770       pst->anonymous = 1;
7771
7772       xfree (name);
7773     }
7774
7775   tu_group->hash.dwo_unit = cu->dwo_unit;
7776   tu_group->hash.line_sect_off = line_offset_struct;
7777
7778   return tu_group;
7779 }
7780
7781 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7782    STMT_LIST is a DW_AT_stmt_list attribute.  */
7783
7784 static struct type_unit_group *
7785 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7786 {
7787   struct dwarf2_per_objfile *dwarf2_per_objfile
7788     = cu->per_cu->dwarf2_per_objfile;
7789   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7790   struct type_unit_group *tu_group;
7791   void **slot;
7792   unsigned int line_offset;
7793   struct type_unit_group type_unit_group_for_lookup;
7794
7795   if (dwarf2_per_objfile->type_unit_groups == NULL)
7796     {
7797       dwarf2_per_objfile->type_unit_groups =
7798         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7799     }
7800
7801   /* Do we need to create a new group, or can we use an existing one?  */
7802
7803   if (stmt_list)
7804     {
7805       line_offset = DW_UNSND (stmt_list);
7806       ++tu_stats->nr_symtab_sharers;
7807     }
7808   else
7809     {
7810       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7811          We can do various things here like create one group per TU or
7812          spread them over multiple groups to split up the expansion work.
7813          To avoid worst case scenarios (too many groups or too large groups)
7814          we, umm, group them in bunches.  */
7815       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7816                      | (tu_stats->nr_stmt_less_type_units
7817                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7818       ++tu_stats->nr_stmt_less_type_units;
7819     }
7820
7821   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7822   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7823   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7824                          &type_unit_group_for_lookup, INSERT);
7825   if (*slot != NULL)
7826     {
7827       tu_group = (struct type_unit_group *) *slot;
7828       gdb_assert (tu_group != NULL);
7829     }
7830   else
7831     {
7832       sect_offset line_offset_struct = (sect_offset) line_offset;
7833       tu_group = create_type_unit_group (cu, line_offset_struct);
7834       *slot = tu_group;
7835       ++tu_stats->nr_symtabs;
7836     }
7837
7838   return tu_group;
7839 }
7840 \f
7841 /* Partial symbol tables.  */
7842
7843 /* Create a psymtab named NAME and assign it to PER_CU.
7844
7845    The caller must fill in the following details:
7846    dirname, textlow, texthigh.  */
7847
7848 static struct partial_symtab *
7849 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7850 {
7851   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7852   struct partial_symtab *pst;
7853
7854   pst = start_psymtab_common (objfile, name, 0,
7855                               objfile->global_psymbols,
7856                               objfile->static_psymbols);
7857
7858   pst->psymtabs_addrmap_supported = 1;
7859
7860   /* This is the glue that links PST into GDB's symbol API.  */
7861   pst->read_symtab_private = per_cu;
7862   pst->read_symtab = dwarf2_read_symtab;
7863   per_cu->v.psymtab = pst;
7864
7865   return pst;
7866 }
7867
7868 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7869    type.  */
7870
7871 struct process_psymtab_comp_unit_data
7872 {
7873   /* True if we are reading a DW_TAG_partial_unit.  */
7874
7875   int want_partial_unit;
7876
7877   /* The "pretend" language that is used if the CU doesn't declare a
7878      language.  */
7879
7880   enum language pretend_language;
7881 };
7882
7883 /* die_reader_func for process_psymtab_comp_unit.  */
7884
7885 static void
7886 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7887                                   const gdb_byte *info_ptr,
7888                                   struct die_info *comp_unit_die,
7889                                   int has_children,
7890                                   void *data)
7891 {
7892   struct dwarf2_cu *cu = reader->cu;
7893   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7894   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7895   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7896   CORE_ADDR baseaddr;
7897   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7898   struct partial_symtab *pst;
7899   enum pc_bounds_kind cu_bounds_kind;
7900   const char *filename;
7901   struct process_psymtab_comp_unit_data *info
7902     = (struct process_psymtab_comp_unit_data *) data;
7903
7904   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7905     return;
7906
7907   gdb_assert (! per_cu->is_debug_types);
7908
7909   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7910
7911   cu->list_in_scope = &file_symbols;
7912
7913   /* Allocate a new partial symbol table structure.  */
7914   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7915   if (filename == NULL)
7916     filename = "";
7917
7918   pst = create_partial_symtab (per_cu, filename);
7919
7920   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7921   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7922
7923   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7924
7925   dwarf2_find_base_address (comp_unit_die, cu);
7926
7927   /* Possibly set the default values of LOWPC and HIGHPC from
7928      `DW_AT_ranges'.  */
7929   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7930                                          &best_highpc, cu, pst);
7931   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7932     /* Store the contiguous range if it is not empty; it can be empty for
7933        CUs with no code.  */
7934     addrmap_set_empty (objfile->psymtabs_addrmap,
7935                        gdbarch_adjust_dwarf2_addr (gdbarch,
7936                                                    best_lowpc + baseaddr),
7937                        gdbarch_adjust_dwarf2_addr (gdbarch,
7938                                                    best_highpc + baseaddr) - 1,
7939                        pst);
7940
7941   /* Check if comp unit has_children.
7942      If so, read the rest of the partial symbols from this comp unit.
7943      If not, there's no more debug_info for this comp unit.  */
7944   if (has_children)
7945     {
7946       struct partial_die_info *first_die;
7947       CORE_ADDR lowpc, highpc;
7948
7949       lowpc = ((CORE_ADDR) -1);
7950       highpc = ((CORE_ADDR) 0);
7951
7952       first_die = load_partial_dies (reader, info_ptr, 1);
7953
7954       scan_partial_symbols (first_die, &lowpc, &highpc,
7955                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7956
7957       /* If we didn't find a lowpc, set it to highpc to avoid
7958          complaints from `maint check'.  */
7959       if (lowpc == ((CORE_ADDR) -1))
7960         lowpc = highpc;
7961
7962       /* If the compilation unit didn't have an explicit address range,
7963          then use the information extracted from its child dies.  */
7964       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7965         {
7966           best_lowpc = lowpc;
7967           best_highpc = highpc;
7968         }
7969     }
7970   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
7971   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
7972
7973   end_psymtab_common (objfile, pst);
7974
7975   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
7976     {
7977       int i;
7978       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7979       struct dwarf2_per_cu_data *iter;
7980
7981       /* Fill in 'dependencies' here; we fill in 'users' in a
7982          post-pass.  */
7983       pst->number_of_dependencies = len;
7984       pst->dependencies =
7985         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7986       for (i = 0;
7987            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7988                         i, iter);
7989            ++i)
7990         pst->dependencies[i] = iter->v.psymtab;
7991
7992       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7993     }
7994
7995   /* Get the list of files included in the current compilation unit,
7996      and build a psymtab for each of them.  */
7997   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7998
7999   if (dwarf_read_debug)
8000     {
8001       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8002
8003       fprintf_unfiltered (gdb_stdlog,
8004                           "Psymtab for %s unit @%s: %s - %s"
8005                           ", %d global, %d static syms\n",
8006                           per_cu->is_debug_types ? "type" : "comp",
8007                           sect_offset_str (per_cu->sect_off),
8008                           paddress (gdbarch, pst->textlow),
8009                           paddress (gdbarch, pst->texthigh),
8010                           pst->n_global_syms, pst->n_static_syms);
8011     }
8012 }
8013
8014 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8015    Process compilation unit THIS_CU for a psymtab.  */
8016
8017 static void
8018 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8019                            int want_partial_unit,
8020                            enum language pretend_language)
8021 {
8022   /* If this compilation unit was already read in, free the
8023      cached copy in order to read it in again.  This is
8024      necessary because we skipped some symbols when we first
8025      read in the compilation unit (see load_partial_dies).
8026      This problem could be avoided, but the benefit is unclear.  */
8027   if (this_cu->cu != NULL)
8028     free_one_cached_comp_unit (this_cu);
8029
8030   if (this_cu->is_debug_types)
8031     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8032                              build_type_psymtabs_reader, NULL);
8033   else
8034     {
8035       process_psymtab_comp_unit_data info;
8036       info.want_partial_unit = want_partial_unit;
8037       info.pretend_language = pretend_language;
8038       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8039                                process_psymtab_comp_unit_reader, &info);
8040     }
8041
8042   /* Age out any secondary CUs.  */
8043   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8044 }
8045
8046 /* Reader function for build_type_psymtabs.  */
8047
8048 static void
8049 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8050                             const gdb_byte *info_ptr,
8051                             struct die_info *type_unit_die,
8052                             int has_children,
8053                             void *data)
8054 {
8055   struct dwarf2_per_objfile *dwarf2_per_objfile
8056     = reader->cu->per_cu->dwarf2_per_objfile;
8057   struct objfile *objfile = dwarf2_per_objfile->objfile;
8058   struct dwarf2_cu *cu = reader->cu;
8059   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8060   struct signatured_type *sig_type;
8061   struct type_unit_group *tu_group;
8062   struct attribute *attr;
8063   struct partial_die_info *first_die;
8064   CORE_ADDR lowpc, highpc;
8065   struct partial_symtab *pst;
8066
8067   gdb_assert (data == NULL);
8068   gdb_assert (per_cu->is_debug_types);
8069   sig_type = (struct signatured_type *) per_cu;
8070
8071   if (! has_children)
8072     return;
8073
8074   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8075   tu_group = get_type_unit_group (cu, attr);
8076
8077   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8078
8079   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8080   cu->list_in_scope = &file_symbols;
8081   pst = create_partial_symtab (per_cu, "");
8082   pst->anonymous = 1;
8083
8084   first_die = load_partial_dies (reader, info_ptr, 1);
8085
8086   lowpc = (CORE_ADDR) -1;
8087   highpc = (CORE_ADDR) 0;
8088   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8089
8090   end_psymtab_common (objfile, pst);
8091 }
8092
8093 /* Struct used to sort TUs by their abbreviation table offset.  */
8094
8095 struct tu_abbrev_offset
8096 {
8097   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8098   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8099   {}
8100
8101   signatured_type *sig_type;
8102   sect_offset abbrev_offset;
8103 };
8104
8105 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8106
8107 static bool
8108 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8109                           const struct tu_abbrev_offset &b)
8110 {
8111   return a.abbrev_offset < b.abbrev_offset;
8112 }
8113
8114 /* Efficiently read all the type units.
8115    This does the bulk of the work for build_type_psymtabs.
8116
8117    The efficiency is because we sort TUs by the abbrev table they use and
8118    only read each abbrev table once.  In one program there are 200K TUs
8119    sharing 8K abbrev tables.
8120
8121    The main purpose of this function is to support building the
8122    dwarf2_per_objfile->type_unit_groups table.
8123    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8124    can collapse the search space by grouping them by stmt_list.
8125    The savings can be significant, in the same program from above the 200K TUs
8126    share 8K stmt_list tables.
8127
8128    FUNC is expected to call get_type_unit_group, which will create the
8129    struct type_unit_group if necessary and add it to
8130    dwarf2_per_objfile->type_unit_groups.  */
8131
8132 static void
8133 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8134 {
8135   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8136   abbrev_table_up abbrev_table;
8137   sect_offset abbrev_offset;
8138
8139   /* It's up to the caller to not call us multiple times.  */
8140   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8141
8142   if (dwarf2_per_objfile->all_type_units.empty ())
8143     return;
8144
8145   /* TUs typically share abbrev tables, and there can be way more TUs than
8146      abbrev tables.  Sort by abbrev table to reduce the number of times we
8147      read each abbrev table in.
8148      Alternatives are to punt or to maintain a cache of abbrev tables.
8149      This is simpler and efficient enough for now.
8150
8151      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8152      symtab to use).  Typically TUs with the same abbrev offset have the same
8153      stmt_list value too so in practice this should work well.
8154
8155      The basic algorithm here is:
8156
8157       sort TUs by abbrev table
8158       for each TU with same abbrev table:
8159         read abbrev table if first user
8160         read TU top level DIE
8161           [IWBN if DWO skeletons had DW_AT_stmt_list]
8162         call FUNC  */
8163
8164   if (dwarf_read_debug)
8165     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8166
8167   /* Sort in a separate table to maintain the order of all_type_units
8168      for .gdb_index: TU indices directly index all_type_units.  */
8169   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8170   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8171
8172   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8173     sorted_by_abbrev.emplace_back
8174       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8175                                      sig_type->per_cu.section,
8176                                      sig_type->per_cu.sect_off));
8177
8178   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8179              sort_tu_by_abbrev_offset);
8180
8181   abbrev_offset = (sect_offset) ~(unsigned) 0;
8182
8183   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8184     {
8185       /* Switch to the next abbrev table if necessary.  */
8186       if (abbrev_table == NULL
8187           || tu.abbrev_offset != abbrev_offset)
8188         {
8189           abbrev_offset = tu.abbrev_offset;
8190           abbrev_table =
8191             abbrev_table_read_table (dwarf2_per_objfile,
8192                                      &dwarf2_per_objfile->abbrev,
8193                                      abbrev_offset);
8194           ++tu_stats->nr_uniq_abbrev_tables;
8195         }
8196
8197       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8198                                0, 0, false, build_type_psymtabs_reader, NULL);
8199     }
8200 }
8201
8202 /* Print collected type unit statistics.  */
8203
8204 static void
8205 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8206 {
8207   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8208
8209   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8210   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8211                       dwarf2_per_objfile->all_type_units.size ());
8212   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8213                       tu_stats->nr_uniq_abbrev_tables);
8214   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8215                       tu_stats->nr_symtabs);
8216   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8217                       tu_stats->nr_symtab_sharers);
8218   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8219                       tu_stats->nr_stmt_less_type_units);
8220   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8221                       tu_stats->nr_all_type_units_reallocs);
8222 }
8223
8224 /* Traversal function for build_type_psymtabs.  */
8225
8226 static int
8227 build_type_psymtab_dependencies (void **slot, void *info)
8228 {
8229   struct dwarf2_per_objfile *dwarf2_per_objfile
8230     = (struct dwarf2_per_objfile *) info;
8231   struct objfile *objfile = dwarf2_per_objfile->objfile;
8232   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8233   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8234   struct partial_symtab *pst = per_cu->v.psymtab;
8235   int len = VEC_length (sig_type_ptr, tu_group->tus);
8236   struct signatured_type *iter;
8237   int i;
8238
8239   gdb_assert (len > 0);
8240   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8241
8242   pst->number_of_dependencies = len;
8243   pst->dependencies =
8244     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8245   for (i = 0;
8246        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8247        ++i)
8248     {
8249       gdb_assert (iter->per_cu.is_debug_types);
8250       pst->dependencies[i] = iter->per_cu.v.psymtab;
8251       iter->type_unit_group = tu_group;
8252     }
8253
8254   VEC_free (sig_type_ptr, tu_group->tus);
8255
8256   return 1;
8257 }
8258
8259 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8260    Build partial symbol tables for the .debug_types comp-units.  */
8261
8262 static void
8263 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8264 {
8265   if (! create_all_type_units (dwarf2_per_objfile))
8266     return;
8267
8268   build_type_psymtabs_1 (dwarf2_per_objfile);
8269 }
8270
8271 /* Traversal function for process_skeletonless_type_unit.
8272    Read a TU in a DWO file and build partial symbols for it.  */
8273
8274 static int
8275 process_skeletonless_type_unit (void **slot, void *info)
8276 {
8277   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8278   struct dwarf2_per_objfile *dwarf2_per_objfile
8279     = (struct dwarf2_per_objfile *) info;
8280   struct signatured_type find_entry, *entry;
8281
8282   /* If this TU doesn't exist in the global table, add it and read it in.  */
8283
8284   if (dwarf2_per_objfile->signatured_types == NULL)
8285     {
8286       dwarf2_per_objfile->signatured_types
8287         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8288     }
8289
8290   find_entry.signature = dwo_unit->signature;
8291   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8292                          INSERT);
8293   /* If we've already seen this type there's nothing to do.  What's happening
8294      is we're doing our own version of comdat-folding here.  */
8295   if (*slot != NULL)
8296     return 1;
8297
8298   /* This does the job that create_all_type_units would have done for
8299      this TU.  */
8300   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8301   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8302   *slot = entry;
8303
8304   /* This does the job that build_type_psymtabs_1 would have done.  */
8305   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8306                            build_type_psymtabs_reader, NULL);
8307
8308   return 1;
8309 }
8310
8311 /* Traversal function for process_skeletonless_type_units.  */
8312
8313 static int
8314 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8315 {
8316   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8317
8318   if (dwo_file->tus != NULL)
8319     {
8320       htab_traverse_noresize (dwo_file->tus,
8321                               process_skeletonless_type_unit, info);
8322     }
8323
8324   return 1;
8325 }
8326
8327 /* Scan all TUs of DWO files, verifying we've processed them.
8328    This is needed in case a TU was emitted without its skeleton.
8329    Note: This can't be done until we know what all the DWO files are.  */
8330
8331 static void
8332 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8333 {
8334   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8335   if (get_dwp_file (dwarf2_per_objfile) == NULL
8336       && dwarf2_per_objfile->dwo_files != NULL)
8337     {
8338       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8339                               process_dwo_file_for_skeletonless_type_units,
8340                               dwarf2_per_objfile);
8341     }
8342 }
8343
8344 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8345
8346 static void
8347 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8348 {
8349   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8350     {
8351       struct partial_symtab *pst = per_cu->v.psymtab;
8352
8353       if (pst == NULL)
8354         continue;
8355
8356       for (int j = 0; j < pst->number_of_dependencies; ++j)
8357         {
8358           /* Set the 'user' field only if it is not already set.  */
8359           if (pst->dependencies[j]->user == NULL)
8360             pst->dependencies[j]->user = pst;
8361         }
8362     }
8363 }
8364
8365 /* Build the partial symbol table by doing a quick pass through the
8366    .debug_info and .debug_abbrev sections.  */
8367
8368 static void
8369 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8370 {
8371   struct objfile *objfile = dwarf2_per_objfile->objfile;
8372
8373   if (dwarf_read_debug)
8374     {
8375       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8376                           objfile_name (objfile));
8377     }
8378
8379   dwarf2_per_objfile->reading_partial_symbols = 1;
8380
8381   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8382
8383   /* Any cached compilation units will be linked by the per-objfile
8384      read_in_chain.  Make sure to free them when we're done.  */
8385   free_cached_comp_units freer (dwarf2_per_objfile);
8386
8387   build_type_psymtabs (dwarf2_per_objfile);
8388
8389   create_all_comp_units (dwarf2_per_objfile);
8390
8391   /* Create a temporary address map on a temporary obstack.  We later
8392      copy this to the final obstack.  */
8393   auto_obstack temp_obstack;
8394
8395   scoped_restore save_psymtabs_addrmap
8396     = make_scoped_restore (&objfile->psymtabs_addrmap,
8397                            addrmap_create_mutable (&temp_obstack));
8398
8399   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8400     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8401
8402   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8403   process_skeletonless_type_units (dwarf2_per_objfile);
8404
8405   /* Now that all TUs have been processed we can fill in the dependencies.  */
8406   if (dwarf2_per_objfile->type_unit_groups != NULL)
8407     {
8408       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8409                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8410     }
8411
8412   if (dwarf_read_debug)
8413     print_tu_stats (dwarf2_per_objfile);
8414
8415   set_partial_user (dwarf2_per_objfile);
8416
8417   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8418                                                     &objfile->objfile_obstack);
8419   /* At this point we want to keep the address map.  */
8420   save_psymtabs_addrmap.release ();
8421
8422   if (dwarf_read_debug)
8423     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8424                         objfile_name (objfile));
8425 }
8426
8427 /* die_reader_func for load_partial_comp_unit.  */
8428
8429 static void
8430 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8431                                const gdb_byte *info_ptr,
8432                                struct die_info *comp_unit_die,
8433                                int has_children,
8434                                void *data)
8435 {
8436   struct dwarf2_cu *cu = reader->cu;
8437
8438   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8439
8440   /* Check if comp unit has_children.
8441      If so, read the rest of the partial symbols from this comp unit.
8442      If not, there's no more debug_info for this comp unit.  */
8443   if (has_children)
8444     load_partial_dies (reader, info_ptr, 0);
8445 }
8446
8447 /* Load the partial DIEs for a secondary CU into memory.
8448    This is also used when rereading a primary CU with load_all_dies.  */
8449
8450 static void
8451 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8452 {
8453   init_cutu_and_read_dies (this_cu, NULL, 1, 1, false,
8454                            load_partial_comp_unit_reader, NULL);
8455 }
8456
8457 static void
8458 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8459                               struct dwarf2_section_info *section,
8460                               struct dwarf2_section_info *abbrev_section,
8461                               unsigned int is_dwz)
8462 {
8463   const gdb_byte *info_ptr;
8464   struct objfile *objfile = dwarf2_per_objfile->objfile;
8465
8466   if (dwarf_read_debug)
8467     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8468                         get_section_name (section),
8469                         get_section_file_name (section));
8470
8471   dwarf2_read_section (objfile, section);
8472
8473   info_ptr = section->buffer;
8474
8475   while (info_ptr < section->buffer + section->size)
8476     {
8477       struct dwarf2_per_cu_data *this_cu;
8478
8479       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8480
8481       comp_unit_head cu_header;
8482       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8483                                      abbrev_section, info_ptr,
8484                                      rcuh_kind::COMPILE);
8485
8486       /* Save the compilation unit for later lookup.  */
8487       if (cu_header.unit_type != DW_UT_type)
8488         {
8489           this_cu = XOBNEW (&objfile->objfile_obstack,
8490                             struct dwarf2_per_cu_data);
8491           memset (this_cu, 0, sizeof (*this_cu));
8492         }
8493       else
8494         {
8495           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8496                                   struct signatured_type);
8497           memset (sig_type, 0, sizeof (*sig_type));
8498           sig_type->signature = cu_header.signature;
8499           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8500           this_cu = &sig_type->per_cu;
8501         }
8502       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8503       this_cu->sect_off = sect_off;
8504       this_cu->length = cu_header.length + cu_header.initial_length_size;
8505       this_cu->is_dwz = is_dwz;
8506       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8507       this_cu->section = section;
8508
8509       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8510
8511       info_ptr = info_ptr + this_cu->length;
8512     }
8513 }
8514
8515 /* Create a list of all compilation units in OBJFILE.
8516    This is only done for -readnow and building partial symtabs.  */
8517
8518 static void
8519 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8520 {
8521   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8522   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8523                                 &dwarf2_per_objfile->abbrev, 0);
8524
8525   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8526   if (dwz != NULL)
8527     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8528                                   1);
8529 }
8530
8531 /* Process all loaded DIEs for compilation unit CU, starting at
8532    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8533    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8534    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8535    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8536
8537 static void
8538 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8539                       CORE_ADDR *highpc, int set_addrmap,
8540                       struct dwarf2_cu *cu)
8541 {
8542   struct partial_die_info *pdi;
8543
8544   /* Now, march along the PDI's, descending into ones which have
8545      interesting children but skipping the children of the other ones,
8546      until we reach the end of the compilation unit.  */
8547
8548   pdi = first_die;
8549
8550   while (pdi != NULL)
8551     {
8552       pdi->fixup (cu);
8553
8554       /* Anonymous namespaces or modules have no name but have interesting
8555          children, so we need to look at them.  Ditto for anonymous
8556          enums.  */
8557
8558       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8559           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8560           || pdi->tag == DW_TAG_imported_unit
8561           || pdi->tag == DW_TAG_inlined_subroutine)
8562         {
8563           switch (pdi->tag)
8564             {
8565             case DW_TAG_subprogram:
8566             case DW_TAG_inlined_subroutine:
8567               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8568               break;
8569             case DW_TAG_constant:
8570             case DW_TAG_variable:
8571             case DW_TAG_typedef:
8572             case DW_TAG_union_type:
8573               if (!pdi->is_declaration)
8574                 {
8575                   add_partial_symbol (pdi, cu);
8576                 }
8577               break;
8578             case DW_TAG_class_type:
8579             case DW_TAG_interface_type:
8580             case DW_TAG_structure_type:
8581               if (!pdi->is_declaration)
8582                 {
8583                   add_partial_symbol (pdi, cu);
8584                 }
8585               if ((cu->language == language_rust
8586                    || cu->language == language_cplus) && pdi->has_children)
8587                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8588                                       set_addrmap, cu);
8589               break;
8590             case DW_TAG_enumeration_type:
8591               if (!pdi->is_declaration)
8592                 add_partial_enumeration (pdi, cu);
8593               break;
8594             case DW_TAG_base_type:
8595             case DW_TAG_subrange_type:
8596               /* File scope base type definitions are added to the partial
8597                  symbol table.  */
8598               add_partial_symbol (pdi, cu);
8599               break;
8600             case DW_TAG_namespace:
8601               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8602               break;
8603             case DW_TAG_module:
8604               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8605               break;
8606             case DW_TAG_imported_unit:
8607               {
8608                 struct dwarf2_per_cu_data *per_cu;
8609
8610                 /* For now we don't handle imported units in type units.  */
8611                 if (cu->per_cu->is_debug_types)
8612                   {
8613                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8614                              " supported in type units [in module %s]"),
8615                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8616                   }
8617
8618                 per_cu = dwarf2_find_containing_comp_unit
8619                            (pdi->d.sect_off, pdi->is_dwz,
8620                             cu->per_cu->dwarf2_per_objfile);
8621
8622                 /* Go read the partial unit, if needed.  */
8623                 if (per_cu->v.psymtab == NULL)
8624                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8625
8626                 VEC_safe_push (dwarf2_per_cu_ptr,
8627                                cu->per_cu->imported_symtabs, per_cu);
8628               }
8629               break;
8630             case DW_TAG_imported_declaration:
8631               add_partial_symbol (pdi, cu);
8632               break;
8633             default:
8634               break;
8635             }
8636         }
8637
8638       /* If the die has a sibling, skip to the sibling.  */
8639
8640       pdi = pdi->die_sibling;
8641     }
8642 }
8643
8644 /* Functions used to compute the fully scoped name of a partial DIE.
8645
8646    Normally, this is simple.  For C++, the parent DIE's fully scoped
8647    name is concatenated with "::" and the partial DIE's name.
8648    Enumerators are an exception; they use the scope of their parent
8649    enumeration type, i.e. the name of the enumeration type is not
8650    prepended to the enumerator.
8651
8652    There are two complexities.  One is DW_AT_specification; in this
8653    case "parent" means the parent of the target of the specification,
8654    instead of the direct parent of the DIE.  The other is compilers
8655    which do not emit DW_TAG_namespace; in this case we try to guess
8656    the fully qualified name of structure types from their members'
8657    linkage names.  This must be done using the DIE's children rather
8658    than the children of any DW_AT_specification target.  We only need
8659    to do this for structures at the top level, i.e. if the target of
8660    any DW_AT_specification (if any; otherwise the DIE itself) does not
8661    have a parent.  */
8662
8663 /* Compute the scope prefix associated with PDI's parent, in
8664    compilation unit CU.  The result will be allocated on CU's
8665    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8666    field.  NULL is returned if no prefix is necessary.  */
8667 static const char *
8668 partial_die_parent_scope (struct partial_die_info *pdi,
8669                           struct dwarf2_cu *cu)
8670 {
8671   const char *grandparent_scope;
8672   struct partial_die_info *parent, *real_pdi;
8673
8674   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8675      then this means the parent of the specification DIE.  */
8676
8677   real_pdi = pdi;
8678   while (real_pdi->has_specification)
8679     real_pdi = find_partial_die (real_pdi->spec_offset,
8680                                  real_pdi->spec_is_dwz, cu);
8681
8682   parent = real_pdi->die_parent;
8683   if (parent == NULL)
8684     return NULL;
8685
8686   if (parent->scope_set)
8687     return parent->scope;
8688
8689   parent->fixup (cu);
8690
8691   grandparent_scope = partial_die_parent_scope (parent, cu);
8692
8693   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8694      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8695      Work around this problem here.  */
8696   if (cu->language == language_cplus
8697       && parent->tag == DW_TAG_namespace
8698       && strcmp (parent->name, "::") == 0
8699       && grandparent_scope == NULL)
8700     {
8701       parent->scope = NULL;
8702       parent->scope_set = 1;
8703       return NULL;
8704     }
8705
8706   if (pdi->tag == DW_TAG_enumerator)
8707     /* Enumerators should not get the name of the enumeration as a prefix.  */
8708     parent->scope = grandparent_scope;
8709   else if (parent->tag == DW_TAG_namespace
8710       || parent->tag == DW_TAG_module
8711       || parent->tag == DW_TAG_structure_type
8712       || parent->tag == DW_TAG_class_type
8713       || parent->tag == DW_TAG_interface_type
8714       || parent->tag == DW_TAG_union_type
8715       || parent->tag == DW_TAG_enumeration_type)
8716     {
8717       if (grandparent_scope == NULL)
8718         parent->scope = parent->name;
8719       else
8720         parent->scope = typename_concat (&cu->comp_unit_obstack,
8721                                          grandparent_scope,
8722                                          parent->name, 0, cu);
8723     }
8724   else
8725     {
8726       /* FIXME drow/2004-04-01: What should we be doing with
8727          function-local names?  For partial symbols, we should probably be
8728          ignoring them.  */
8729       complaint (_("unhandled containing DIE tag %d for DIE at %s"),
8730                  parent->tag, sect_offset_str (pdi->sect_off));
8731       parent->scope = grandparent_scope;
8732     }
8733
8734   parent->scope_set = 1;
8735   return parent->scope;
8736 }
8737
8738 /* Return the fully scoped name associated with PDI, from compilation unit
8739    CU.  The result will be allocated with malloc.  */
8740
8741 static char *
8742 partial_die_full_name (struct partial_die_info *pdi,
8743                        struct dwarf2_cu *cu)
8744 {
8745   const char *parent_scope;
8746
8747   /* If this is a template instantiation, we can not work out the
8748      template arguments from partial DIEs.  So, unfortunately, we have
8749      to go through the full DIEs.  At least any work we do building
8750      types here will be reused if full symbols are loaded later.  */
8751   if (pdi->has_template_arguments)
8752     {
8753       pdi->fixup (cu);
8754
8755       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8756         {
8757           struct die_info *die;
8758           struct attribute attr;
8759           struct dwarf2_cu *ref_cu = cu;
8760
8761           /* DW_FORM_ref_addr is using section offset.  */
8762           attr.name = (enum dwarf_attribute) 0;
8763           attr.form = DW_FORM_ref_addr;
8764           attr.u.unsnd = to_underlying (pdi->sect_off);
8765           die = follow_die_ref (NULL, &attr, &ref_cu);
8766
8767           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8768         }
8769     }
8770
8771   parent_scope = partial_die_parent_scope (pdi, cu);
8772   if (parent_scope == NULL)
8773     return NULL;
8774   else
8775     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8776 }
8777
8778 static void
8779 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8780 {
8781   struct dwarf2_per_objfile *dwarf2_per_objfile
8782     = cu->per_cu->dwarf2_per_objfile;
8783   struct objfile *objfile = dwarf2_per_objfile->objfile;
8784   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8785   CORE_ADDR addr = 0;
8786   const char *actual_name = NULL;
8787   CORE_ADDR baseaddr;
8788   char *built_actual_name;
8789
8790   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8791
8792   built_actual_name = partial_die_full_name (pdi, cu);
8793   if (built_actual_name != NULL)
8794     actual_name = built_actual_name;
8795
8796   if (actual_name == NULL)
8797     actual_name = pdi->name;
8798
8799   switch (pdi->tag)
8800     {
8801     case DW_TAG_inlined_subroutine:
8802     case DW_TAG_subprogram:
8803       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
8804       if (pdi->is_external || cu->language == language_ada)
8805         {
8806           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8807              of the global scope.  But in Ada, we want to be able to access
8808              nested procedures globally.  So all Ada subprograms are stored
8809              in the global scope.  */
8810           add_psymbol_to_list (actual_name, strlen (actual_name),
8811                                built_actual_name != NULL,
8812                                VAR_DOMAIN, LOC_BLOCK,
8813                                &objfile->global_psymbols,
8814                                addr, cu->language, objfile);
8815         }
8816       else
8817         {
8818           add_psymbol_to_list (actual_name, strlen (actual_name),
8819                                built_actual_name != NULL,
8820                                VAR_DOMAIN, LOC_BLOCK,
8821                                &objfile->static_psymbols,
8822                                addr, cu->language, objfile);
8823         }
8824
8825       if (pdi->main_subprogram && actual_name != NULL)
8826         set_objfile_main_name (objfile, actual_name, cu->language);
8827       break;
8828     case DW_TAG_constant:
8829       {
8830         std::vector<partial_symbol *> *list;
8831
8832         if (pdi->is_external)
8833           list = &objfile->global_psymbols;
8834         else
8835           list = &objfile->static_psymbols;
8836         add_psymbol_to_list (actual_name, strlen (actual_name),
8837                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8838                              list, 0, cu->language, objfile);
8839       }
8840       break;
8841     case DW_TAG_variable:
8842       if (pdi->d.locdesc)
8843         addr = decode_locdesc (pdi->d.locdesc, cu);
8844
8845       if (pdi->d.locdesc
8846           && addr == 0
8847           && !dwarf2_per_objfile->has_section_at_zero)
8848         {
8849           /* A global or static variable may also have been stripped
8850              out by the linker if unused, in which case its address
8851              will be nullified; do not add such variables into partial
8852              symbol table then.  */
8853         }
8854       else if (pdi->is_external)
8855         {
8856           /* Global Variable.
8857              Don't enter into the minimal symbol tables as there is
8858              a minimal symbol table entry from the ELF symbols already.
8859              Enter into partial symbol table if it has a location
8860              descriptor or a type.
8861              If the location descriptor is missing, new_symbol will create
8862              a LOC_UNRESOLVED symbol, the address of the variable will then
8863              be determined from the minimal symbol table whenever the variable
8864              is referenced.
8865              The address for the partial symbol table entry is not
8866              used by GDB, but it comes in handy for debugging partial symbol
8867              table building.  */
8868
8869           if (pdi->d.locdesc || pdi->has_type)
8870             add_psymbol_to_list (actual_name, strlen (actual_name),
8871                                  built_actual_name != NULL,
8872                                  VAR_DOMAIN, LOC_STATIC,
8873                                  &objfile->global_psymbols,
8874                                  addr + baseaddr,
8875                                  cu->language, objfile);
8876         }
8877       else
8878         {
8879           int has_loc = pdi->d.locdesc != NULL;
8880
8881           /* Static Variable.  Skip symbols whose value we cannot know (those
8882              without location descriptors or constant values).  */
8883           if (!has_loc && !pdi->has_const_value)
8884             {
8885               xfree (built_actual_name);
8886               return;
8887             }
8888
8889           add_psymbol_to_list (actual_name, strlen (actual_name),
8890                                built_actual_name != NULL,
8891                                VAR_DOMAIN, LOC_STATIC,
8892                                &objfile->static_psymbols,
8893                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
8894                                cu->language, objfile);
8895         }
8896       break;
8897     case DW_TAG_typedef:
8898     case DW_TAG_base_type:
8899     case DW_TAG_subrange_type:
8900       add_psymbol_to_list (actual_name, strlen (actual_name),
8901                            built_actual_name != NULL,
8902                            VAR_DOMAIN, LOC_TYPEDEF,
8903                            &objfile->static_psymbols,
8904                            0, cu->language, objfile);
8905       break;
8906     case DW_TAG_imported_declaration:
8907     case DW_TAG_namespace:
8908       add_psymbol_to_list (actual_name, strlen (actual_name),
8909                            built_actual_name != NULL,
8910                            VAR_DOMAIN, LOC_TYPEDEF,
8911                            &objfile->global_psymbols,
8912                            0, cu->language, objfile);
8913       break;
8914     case DW_TAG_module:
8915       add_psymbol_to_list (actual_name, strlen (actual_name),
8916                            built_actual_name != NULL,
8917                            MODULE_DOMAIN, LOC_TYPEDEF,
8918                            &objfile->global_psymbols,
8919                            0, cu->language, objfile);
8920       break;
8921     case DW_TAG_class_type:
8922     case DW_TAG_interface_type:
8923     case DW_TAG_structure_type:
8924     case DW_TAG_union_type:
8925     case DW_TAG_enumeration_type:
8926       /* Skip external references.  The DWARF standard says in the section
8927          about "Structure, Union, and Class Type Entries": "An incomplete
8928          structure, union or class type is represented by a structure,
8929          union or class entry that does not have a byte size attribute
8930          and that has a DW_AT_declaration attribute."  */
8931       if (!pdi->has_byte_size && pdi->is_declaration)
8932         {
8933           xfree (built_actual_name);
8934           return;
8935         }
8936
8937       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8938          static vs. global.  */
8939       add_psymbol_to_list (actual_name, strlen (actual_name),
8940                            built_actual_name != NULL,
8941                            STRUCT_DOMAIN, LOC_TYPEDEF,
8942                            cu->language == language_cplus
8943                            ? &objfile->global_psymbols
8944                            : &objfile->static_psymbols,
8945                            0, cu->language, objfile);
8946
8947       break;
8948     case DW_TAG_enumerator:
8949       add_psymbol_to_list (actual_name, strlen (actual_name),
8950                            built_actual_name != NULL,
8951                            VAR_DOMAIN, LOC_CONST,
8952                            cu->language == language_cplus
8953                            ? &objfile->global_psymbols
8954                            : &objfile->static_psymbols,
8955                            0, cu->language, objfile);
8956       break;
8957     default:
8958       break;
8959     }
8960
8961   xfree (built_actual_name);
8962 }
8963
8964 /* Read a partial die corresponding to a namespace; also, add a symbol
8965    corresponding to that namespace to the symbol table.  NAMESPACE is
8966    the name of the enclosing namespace.  */
8967
8968 static void
8969 add_partial_namespace (struct partial_die_info *pdi,
8970                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8971                        int set_addrmap, struct dwarf2_cu *cu)
8972 {
8973   /* Add a symbol for the namespace.  */
8974
8975   add_partial_symbol (pdi, cu);
8976
8977   /* Now scan partial symbols in that namespace.  */
8978
8979   if (pdi->has_children)
8980     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8981 }
8982
8983 /* Read a partial die corresponding to a Fortran module.  */
8984
8985 static void
8986 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8987                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8988 {
8989   /* Add a symbol for the namespace.  */
8990
8991   add_partial_symbol (pdi, cu);
8992
8993   /* Now scan partial symbols in that module.  */
8994
8995   if (pdi->has_children)
8996     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8997 }
8998
8999 /* Read a partial die corresponding to a subprogram or an inlined
9000    subprogram and create a partial symbol for that subprogram.
9001    When the CU language allows it, this routine also defines a partial
9002    symbol for each nested subprogram that this subprogram contains.
9003    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9004    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9005
9006    PDI may also be a lexical block, in which case we simply search
9007    recursively for subprograms defined inside that lexical block.
9008    Again, this is only performed when the CU language allows this
9009    type of definitions.  */
9010
9011 static void
9012 add_partial_subprogram (struct partial_die_info *pdi,
9013                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9014                         int set_addrmap, struct dwarf2_cu *cu)
9015 {
9016   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9017     {
9018       if (pdi->has_pc_info)
9019         {
9020           if (pdi->lowpc < *lowpc)
9021             *lowpc = pdi->lowpc;
9022           if (pdi->highpc > *highpc)
9023             *highpc = pdi->highpc;
9024           if (set_addrmap)
9025             {
9026               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9027               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9028               CORE_ADDR baseaddr;
9029               CORE_ADDR highpc;
9030               CORE_ADDR lowpc;
9031
9032               baseaddr = ANOFFSET (objfile->section_offsets,
9033                                    SECT_OFF_TEXT (objfile));
9034               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9035                                                   pdi->lowpc + baseaddr);
9036               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9037                                                    pdi->highpc + baseaddr);
9038               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9039                                  cu->per_cu->v.psymtab);
9040             }
9041         }
9042
9043       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9044         {
9045           if (!pdi->is_declaration)
9046             /* Ignore subprogram DIEs that do not have a name, they are
9047                illegal.  Do not emit a complaint at this point, we will
9048                do so when we convert this psymtab into a symtab.  */
9049             if (pdi->name)
9050               add_partial_symbol (pdi, cu);
9051         }
9052     }
9053
9054   if (! pdi->has_children)
9055     return;
9056
9057   if (cu->language == language_ada)
9058     {
9059       pdi = pdi->die_child;
9060       while (pdi != NULL)
9061         {
9062           pdi->fixup (cu);
9063           if (pdi->tag == DW_TAG_subprogram
9064               || pdi->tag == DW_TAG_inlined_subroutine
9065               || pdi->tag == DW_TAG_lexical_block)
9066             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9067           pdi = pdi->die_sibling;
9068         }
9069     }
9070 }
9071
9072 /* Read a partial die corresponding to an enumeration type.  */
9073
9074 static void
9075 add_partial_enumeration (struct partial_die_info *enum_pdi,
9076                          struct dwarf2_cu *cu)
9077 {
9078   struct partial_die_info *pdi;
9079
9080   if (enum_pdi->name != NULL)
9081     add_partial_symbol (enum_pdi, cu);
9082
9083   pdi = enum_pdi->die_child;
9084   while (pdi)
9085     {
9086       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9087         complaint (_("malformed enumerator DIE ignored"));
9088       else
9089         add_partial_symbol (pdi, cu);
9090       pdi = pdi->die_sibling;
9091     }
9092 }
9093
9094 /* Return the initial uleb128 in the die at INFO_PTR.  */
9095
9096 static unsigned int
9097 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9098 {
9099   unsigned int bytes_read;
9100
9101   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9102 }
9103
9104 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9105    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9106
9107    Return the corresponding abbrev, or NULL if the number is zero (indicating
9108    an empty DIE).  In either case *BYTES_READ will be set to the length of
9109    the initial number.  */
9110
9111 static struct abbrev_info *
9112 peek_die_abbrev (const die_reader_specs &reader,
9113                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9114 {
9115   dwarf2_cu *cu = reader.cu;
9116   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9117   unsigned int abbrev_number
9118     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9119
9120   if (abbrev_number == 0)
9121     return NULL;
9122
9123   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9124   if (!abbrev)
9125     {
9126       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9127                " at offset %s [in module %s]"),
9128              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9129              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9130     }
9131
9132   return abbrev;
9133 }
9134
9135 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9136    Returns a pointer to the end of a series of DIEs, terminated by an empty
9137    DIE.  Any children of the skipped DIEs will also be skipped.  */
9138
9139 static const gdb_byte *
9140 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9141 {
9142   while (1)
9143     {
9144       unsigned int bytes_read;
9145       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9146
9147       if (abbrev == NULL)
9148         return info_ptr + bytes_read;
9149       else
9150         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9151     }
9152 }
9153
9154 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9155    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9156    abbrev corresponding to that skipped uleb128 should be passed in
9157    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9158    children.  */
9159
9160 static const gdb_byte *
9161 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9162               struct abbrev_info *abbrev)
9163 {
9164   unsigned int bytes_read;
9165   struct attribute attr;
9166   bfd *abfd = reader->abfd;
9167   struct dwarf2_cu *cu = reader->cu;
9168   const gdb_byte *buffer = reader->buffer;
9169   const gdb_byte *buffer_end = reader->buffer_end;
9170   unsigned int form, i;
9171
9172   for (i = 0; i < abbrev->num_attrs; i++)
9173     {
9174       /* The only abbrev we care about is DW_AT_sibling.  */
9175       if (abbrev->attrs[i].name == DW_AT_sibling)
9176         {
9177           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9178           if (attr.form == DW_FORM_ref_addr)
9179             complaint (_("ignoring absolute DW_AT_sibling"));
9180           else
9181             {
9182               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9183               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9184
9185               if (sibling_ptr < info_ptr)
9186                 complaint (_("DW_AT_sibling points backwards"));
9187               else if (sibling_ptr > reader->buffer_end)
9188                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9189               else
9190                 return sibling_ptr;
9191             }
9192         }
9193
9194       /* If it isn't DW_AT_sibling, skip this attribute.  */
9195       form = abbrev->attrs[i].form;
9196     skip_attribute:
9197       switch (form)
9198         {
9199         case DW_FORM_ref_addr:
9200           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9201              and later it is offset sized.  */
9202           if (cu->header.version == 2)
9203             info_ptr += cu->header.addr_size;
9204           else
9205             info_ptr += cu->header.offset_size;
9206           break;
9207         case DW_FORM_GNU_ref_alt:
9208           info_ptr += cu->header.offset_size;
9209           break;
9210         case DW_FORM_addr:
9211           info_ptr += cu->header.addr_size;
9212           break;
9213         case DW_FORM_data1:
9214         case DW_FORM_ref1:
9215         case DW_FORM_flag:
9216           info_ptr += 1;
9217           break;
9218         case DW_FORM_flag_present:
9219         case DW_FORM_implicit_const:
9220           break;
9221         case DW_FORM_data2:
9222         case DW_FORM_ref2:
9223           info_ptr += 2;
9224           break;
9225         case DW_FORM_data4:
9226         case DW_FORM_ref4:
9227           info_ptr += 4;
9228           break;
9229         case DW_FORM_data8:
9230         case DW_FORM_ref8:
9231         case DW_FORM_ref_sig8:
9232           info_ptr += 8;
9233           break;
9234         case DW_FORM_data16:
9235           info_ptr += 16;
9236           break;
9237         case DW_FORM_string:
9238           read_direct_string (abfd, info_ptr, &bytes_read);
9239           info_ptr += bytes_read;
9240           break;
9241         case DW_FORM_sec_offset:
9242         case DW_FORM_strp:
9243         case DW_FORM_GNU_strp_alt:
9244           info_ptr += cu->header.offset_size;
9245           break;
9246         case DW_FORM_exprloc:
9247         case DW_FORM_block:
9248           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9249           info_ptr += bytes_read;
9250           break;
9251         case DW_FORM_block1:
9252           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9253           break;
9254         case DW_FORM_block2:
9255           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9256           break;
9257         case DW_FORM_block4:
9258           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9259           break;
9260         case DW_FORM_sdata:
9261         case DW_FORM_udata:
9262         case DW_FORM_ref_udata:
9263         case DW_FORM_GNU_addr_index:
9264         case DW_FORM_GNU_str_index:
9265           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9266           break;
9267         case DW_FORM_indirect:
9268           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9269           info_ptr += bytes_read;
9270           /* We need to continue parsing from here, so just go back to
9271              the top.  */
9272           goto skip_attribute;
9273
9274         default:
9275           error (_("Dwarf Error: Cannot handle %s "
9276                    "in DWARF reader [in module %s]"),
9277                  dwarf_form_name (form),
9278                  bfd_get_filename (abfd));
9279         }
9280     }
9281
9282   if (abbrev->has_children)
9283     return skip_children (reader, info_ptr);
9284   else
9285     return info_ptr;
9286 }
9287
9288 /* Locate ORIG_PDI's sibling.
9289    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9290
9291 static const gdb_byte *
9292 locate_pdi_sibling (const struct die_reader_specs *reader,
9293                     struct partial_die_info *orig_pdi,
9294                     const gdb_byte *info_ptr)
9295 {
9296   /* Do we know the sibling already?  */
9297
9298   if (orig_pdi->sibling)
9299     return orig_pdi->sibling;
9300
9301   /* Are there any children to deal with?  */
9302
9303   if (!orig_pdi->has_children)
9304     return info_ptr;
9305
9306   /* Skip the children the long way.  */
9307
9308   return skip_children (reader, info_ptr);
9309 }
9310
9311 /* Expand this partial symbol table into a full symbol table.  SELF is
9312    not NULL.  */
9313
9314 static void
9315 dwarf2_read_symtab (struct partial_symtab *self,
9316                     struct objfile *objfile)
9317 {
9318   struct dwarf2_per_objfile *dwarf2_per_objfile
9319     = get_dwarf2_per_objfile (objfile);
9320
9321   if (self->readin)
9322     {
9323       warning (_("bug: psymtab for %s is already read in."),
9324                self->filename);
9325     }
9326   else
9327     {
9328       if (info_verbose)
9329         {
9330           printf_filtered (_("Reading in symbols for %s..."),
9331                            self->filename);
9332           gdb_flush (gdb_stdout);
9333         }
9334
9335       /* If this psymtab is constructed from a debug-only objfile, the
9336          has_section_at_zero flag will not necessarily be correct.  We
9337          can get the correct value for this flag by looking at the data
9338          associated with the (presumably stripped) associated objfile.  */
9339       if (objfile->separate_debug_objfile_backlink)
9340         {
9341           struct dwarf2_per_objfile *dpo_backlink
9342             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9343
9344           dwarf2_per_objfile->has_section_at_zero
9345             = dpo_backlink->has_section_at_zero;
9346         }
9347
9348       dwarf2_per_objfile->reading_partial_symbols = 0;
9349
9350       psymtab_to_symtab_1 (self);
9351
9352       /* Finish up the debug error message.  */
9353       if (info_verbose)
9354         printf_filtered (_("done.\n"));
9355     }
9356
9357   process_cu_includes (dwarf2_per_objfile);
9358 }
9359 \f
9360 /* Reading in full CUs.  */
9361
9362 /* Add PER_CU to the queue.  */
9363
9364 static void
9365 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9366                  enum language pretend_language)
9367 {
9368   struct dwarf2_queue_item *item;
9369
9370   per_cu->queued = 1;
9371   item = XNEW (struct dwarf2_queue_item);
9372   item->per_cu = per_cu;
9373   item->pretend_language = pretend_language;
9374   item->next = NULL;
9375
9376   if (dwarf2_queue == NULL)
9377     dwarf2_queue = item;
9378   else
9379     dwarf2_queue_tail->next = item;
9380
9381   dwarf2_queue_tail = item;
9382 }
9383
9384 /* If PER_CU is not yet queued, add it to the queue.
9385    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9386    dependency.
9387    The result is non-zero if PER_CU was queued, otherwise the result is zero
9388    meaning either PER_CU is already queued or it is already loaded.
9389
9390    N.B. There is an invariant here that if a CU is queued then it is loaded.
9391    The caller is required to load PER_CU if we return non-zero.  */
9392
9393 static int
9394 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9395                        struct dwarf2_per_cu_data *per_cu,
9396                        enum language pretend_language)
9397 {
9398   /* We may arrive here during partial symbol reading, if we need full
9399      DIEs to process an unusual case (e.g. template arguments).  Do
9400      not queue PER_CU, just tell our caller to load its DIEs.  */
9401   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9402     {
9403       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9404         return 1;
9405       return 0;
9406     }
9407
9408   /* Mark the dependence relation so that we don't flush PER_CU
9409      too early.  */
9410   if (dependent_cu != NULL)
9411     dwarf2_add_dependence (dependent_cu, per_cu);
9412
9413   /* If it's already on the queue, we have nothing to do.  */
9414   if (per_cu->queued)
9415     return 0;
9416
9417   /* If the compilation unit is already loaded, just mark it as
9418      used.  */
9419   if (per_cu->cu != NULL)
9420     {
9421       per_cu->cu->last_used = 0;
9422       return 0;
9423     }
9424
9425   /* Add it to the queue.  */
9426   queue_comp_unit (per_cu, pretend_language);
9427
9428   return 1;
9429 }
9430
9431 /* Process the queue.  */
9432
9433 static void
9434 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9435 {
9436   struct dwarf2_queue_item *item, *next_item;
9437
9438   if (dwarf_read_debug)
9439     {
9440       fprintf_unfiltered (gdb_stdlog,
9441                           "Expanding one or more symtabs of objfile %s ...\n",
9442                           objfile_name (dwarf2_per_objfile->objfile));
9443     }
9444
9445   /* The queue starts out with one item, but following a DIE reference
9446      may load a new CU, adding it to the end of the queue.  */
9447   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9448     {
9449       if ((dwarf2_per_objfile->using_index
9450            ? !item->per_cu->v.quick->compunit_symtab
9451            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9452           /* Skip dummy CUs.  */
9453           && item->per_cu->cu != NULL)
9454         {
9455           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9456           unsigned int debug_print_threshold;
9457           char buf[100];
9458
9459           if (per_cu->is_debug_types)
9460             {
9461               struct signatured_type *sig_type =
9462                 (struct signatured_type *) per_cu;
9463
9464               sprintf (buf, "TU %s at offset %s",
9465                        hex_string (sig_type->signature),
9466                        sect_offset_str (per_cu->sect_off));
9467               /* There can be 100s of TUs.
9468                  Only print them in verbose mode.  */
9469               debug_print_threshold = 2;
9470             }
9471           else
9472             {
9473               sprintf (buf, "CU at offset %s",
9474                        sect_offset_str (per_cu->sect_off));
9475               debug_print_threshold = 1;
9476             }
9477
9478           if (dwarf_read_debug >= debug_print_threshold)
9479             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9480
9481           if (per_cu->is_debug_types)
9482             process_full_type_unit (per_cu, item->pretend_language);
9483           else
9484             process_full_comp_unit (per_cu, item->pretend_language);
9485
9486           if (dwarf_read_debug >= debug_print_threshold)
9487             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9488         }
9489
9490       item->per_cu->queued = 0;
9491       next_item = item->next;
9492       xfree (item);
9493     }
9494
9495   dwarf2_queue_tail = NULL;
9496
9497   if (dwarf_read_debug)
9498     {
9499       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9500                           objfile_name (dwarf2_per_objfile->objfile));
9501     }
9502 }
9503
9504 /* Read in full symbols for PST, and anything it depends on.  */
9505
9506 static void
9507 psymtab_to_symtab_1 (struct partial_symtab *pst)
9508 {
9509   struct dwarf2_per_cu_data *per_cu;
9510   int i;
9511
9512   if (pst->readin)
9513     return;
9514
9515   for (i = 0; i < pst->number_of_dependencies; i++)
9516     if (!pst->dependencies[i]->readin
9517         && pst->dependencies[i]->user == NULL)
9518       {
9519         /* Inform about additional files that need to be read in.  */
9520         if (info_verbose)
9521           {
9522             /* FIXME: i18n: Need to make this a single string.  */
9523             fputs_filtered (" ", gdb_stdout);
9524             wrap_here ("");
9525             fputs_filtered ("and ", gdb_stdout);
9526             wrap_here ("");
9527             printf_filtered ("%s...", pst->dependencies[i]->filename);
9528             wrap_here ("");     /* Flush output.  */
9529             gdb_flush (gdb_stdout);
9530           }
9531         psymtab_to_symtab_1 (pst->dependencies[i]);
9532       }
9533
9534   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9535
9536   if (per_cu == NULL)
9537     {
9538       /* It's an include file, no symbols to read for it.
9539          Everything is in the parent symtab.  */
9540       pst->readin = 1;
9541       return;
9542     }
9543
9544   dw2_do_instantiate_symtab (per_cu, false);
9545 }
9546
9547 /* Trivial hash function for die_info: the hash value of a DIE
9548    is its offset in .debug_info for this objfile.  */
9549
9550 static hashval_t
9551 die_hash (const void *item)
9552 {
9553   const struct die_info *die = (const struct die_info *) item;
9554
9555   return to_underlying (die->sect_off);
9556 }
9557
9558 /* Trivial comparison function for die_info structures: two DIEs
9559    are equal if they have the same offset.  */
9560
9561 static int
9562 die_eq (const void *item_lhs, const void *item_rhs)
9563 {
9564   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9565   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9566
9567   return die_lhs->sect_off == die_rhs->sect_off;
9568 }
9569
9570 /* die_reader_func for load_full_comp_unit.
9571    This is identical to read_signatured_type_reader,
9572    but is kept separate for now.  */
9573
9574 static void
9575 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9576                             const gdb_byte *info_ptr,
9577                             struct die_info *comp_unit_die,
9578                             int has_children,
9579                             void *data)
9580 {
9581   struct dwarf2_cu *cu = reader->cu;
9582   enum language *language_ptr = (enum language *) data;
9583
9584   gdb_assert (cu->die_hash == NULL);
9585   cu->die_hash =
9586     htab_create_alloc_ex (cu->header.length / 12,
9587                           die_hash,
9588                           die_eq,
9589                           NULL,
9590                           &cu->comp_unit_obstack,
9591                           hashtab_obstack_allocate,
9592                           dummy_obstack_deallocate);
9593
9594   if (has_children)
9595     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9596                                                   &info_ptr, comp_unit_die);
9597   cu->dies = comp_unit_die;
9598   /* comp_unit_die is not stored in die_hash, no need.  */
9599
9600   /* We try not to read any attributes in this function, because not
9601      all CUs needed for references have been loaded yet, and symbol
9602      table processing isn't initialized.  But we have to set the CU language,
9603      or we won't be able to build types correctly.
9604      Similarly, if we do not read the producer, we can not apply
9605      producer-specific interpretation.  */
9606   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9607 }
9608
9609 /* Load the DIEs associated with PER_CU into memory.  */
9610
9611 static void
9612 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9613                      bool skip_partial,
9614                      enum language pretend_language)
9615 {
9616   gdb_assert (! this_cu->is_debug_types);
9617
9618   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9619                            load_full_comp_unit_reader, &pretend_language);
9620 }
9621
9622 /* Add a DIE to the delayed physname list.  */
9623
9624 static void
9625 add_to_method_list (struct type *type, int fnfield_index, int index,
9626                     const char *name, struct die_info *die,
9627                     struct dwarf2_cu *cu)
9628 {
9629   struct delayed_method_info mi;
9630   mi.type = type;
9631   mi.fnfield_index = fnfield_index;
9632   mi.index = index;
9633   mi.name = name;
9634   mi.die = die;
9635   cu->method_list.push_back (mi);
9636 }
9637
9638 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9639    "const" / "volatile".  If so, decrements LEN by the length of the
9640    modifier and return true.  Otherwise return false.  */
9641
9642 template<size_t N>
9643 static bool
9644 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9645 {
9646   size_t mod_len = sizeof (mod) - 1;
9647   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9648     {
9649       len -= mod_len;
9650       return true;
9651     }
9652   return false;
9653 }
9654
9655 /* Compute the physnames of any methods on the CU's method list.
9656
9657    The computation of method physnames is delayed in order to avoid the
9658    (bad) condition that one of the method's formal parameters is of an as yet
9659    incomplete type.  */
9660
9661 static void
9662 compute_delayed_physnames (struct dwarf2_cu *cu)
9663 {
9664   /* Only C++ delays computing physnames.  */
9665   if (cu->method_list.empty ())
9666     return;
9667   gdb_assert (cu->language == language_cplus);
9668
9669   for (const delayed_method_info &mi : cu->method_list)
9670     {
9671       const char *physname;
9672       struct fn_fieldlist *fn_flp
9673         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9674       physname = dwarf2_physname (mi.name, mi.die, cu);
9675       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9676         = physname ? physname : "";
9677
9678       /* Since there's no tag to indicate whether a method is a
9679          const/volatile overload, extract that information out of the
9680          demangled name.  */
9681       if (physname != NULL)
9682         {
9683           size_t len = strlen (physname);
9684
9685           while (1)
9686             {
9687               if (physname[len] == ')') /* shortcut */
9688                 break;
9689               else if (check_modifier (physname, len, " const"))
9690                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9691               else if (check_modifier (physname, len, " volatile"))
9692                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9693               else
9694                 break;
9695             }
9696         }
9697     }
9698
9699   /* The list is no longer needed.  */
9700   cu->method_list.clear ();
9701 }
9702
9703 /* A wrapper for add_symbol_to_list to ensure that SYMBOL's language is
9704    the same as all other symbols in LISTHEAD.  If a new symbol is added
9705    with a different language, this function asserts.  */
9706
9707 static inline void
9708 dw2_add_symbol_to_list (struct symbol *symbol, struct pending **listhead)
9709 {
9710   /* Only assert if LISTHEAD already contains symbols of a different
9711      language (dict_create_hashed/insert_symbol_hashed requires that all
9712      symbols in this list are of the same language).  */
9713   gdb_assert ((*listhead) == NULL
9714               || (SYMBOL_LANGUAGE ((*listhead)->symbol[0])
9715                   == SYMBOL_LANGUAGE (symbol)));
9716
9717   add_symbol_to_list (symbol, listhead);
9718 }
9719
9720 /* Go objects should be embedded in a DW_TAG_module DIE,
9721    and it's not clear if/how imported objects will appear.
9722    To keep Go support simple until that's worked out,
9723    go back through what we've read and create something usable.
9724    We could do this while processing each DIE, and feels kinda cleaner,
9725    but that way is more invasive.
9726    This is to, for example, allow the user to type "p var" or "b main"
9727    without having to specify the package name, and allow lookups
9728    of module.object to work in contexts that use the expression
9729    parser.  */
9730
9731 static void
9732 fixup_go_packaging (struct dwarf2_cu *cu)
9733 {
9734   char *package_name = NULL;
9735   struct pending *list;
9736   int i;
9737
9738   for (list = global_symbols; list != NULL; list = list->next)
9739     {
9740       for (i = 0; i < list->nsyms; ++i)
9741         {
9742           struct symbol *sym = list->symbol[i];
9743
9744           if (SYMBOL_LANGUAGE (sym) == language_go
9745               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9746             {
9747               char *this_package_name = go_symbol_package_name (sym);
9748
9749               if (this_package_name == NULL)
9750                 continue;
9751               if (package_name == NULL)
9752                 package_name = this_package_name;
9753               else
9754                 {
9755                   struct objfile *objfile
9756                     = cu->per_cu->dwarf2_per_objfile->objfile;
9757                   if (strcmp (package_name, this_package_name) != 0)
9758                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9759                                (symbol_symtab (sym) != NULL
9760                                 ? symtab_to_filename_for_display
9761                                     (symbol_symtab (sym))
9762                                 : objfile_name (objfile)),
9763                                this_package_name, package_name);
9764                   xfree (this_package_name);
9765                 }
9766             }
9767         }
9768     }
9769
9770   if (package_name != NULL)
9771     {
9772       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9773       const char *saved_package_name
9774         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9775                                         package_name,
9776                                         strlen (package_name));
9777       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9778                                      saved_package_name);
9779       struct symbol *sym;
9780
9781       sym = allocate_symbol (objfile);
9782       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9783       SYMBOL_SET_NAMES (sym, saved_package_name,
9784                         strlen (saved_package_name), 0, objfile);
9785       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9786          e.g., "main" finds the "main" module and not C's main().  */
9787       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9788       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9789       SYMBOL_TYPE (sym) = type;
9790
9791       dw2_add_symbol_to_list (sym, &global_symbols);
9792
9793       xfree (package_name);
9794     }
9795 }
9796
9797 /* Allocate a fully-qualified name consisting of the two parts on the
9798    obstack.  */
9799
9800 static const char *
9801 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9802 {
9803   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9804 }
9805
9806 /* A helper that allocates a struct discriminant_info to attach to a
9807    union type.  */
9808
9809 static struct discriminant_info *
9810 alloc_discriminant_info (struct type *type, int discriminant_index,
9811                          int default_index)
9812 {
9813   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9814   gdb_assert (discriminant_index == -1
9815               || (discriminant_index >= 0
9816                   && discriminant_index < TYPE_NFIELDS (type)));
9817   gdb_assert (default_index == -1
9818               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9819
9820   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9821
9822   struct discriminant_info *disc
9823     = ((struct discriminant_info *)
9824        TYPE_ZALLOC (type,
9825                     offsetof (struct discriminant_info, discriminants)
9826                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9827   disc->default_index = default_index;
9828   disc->discriminant_index = discriminant_index;
9829
9830   struct dynamic_prop prop;
9831   prop.kind = PROP_UNDEFINED;
9832   prop.data.baton = disc;
9833
9834   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9835
9836   return disc;
9837 }
9838
9839 /* Some versions of rustc emitted enums in an unusual way.
9840
9841    Ordinary enums were emitted as unions.  The first element of each
9842    structure in the union was named "RUST$ENUM$DISR".  This element
9843    held the discriminant.
9844
9845    These versions of Rust also implemented the "non-zero"
9846    optimization.  When the enum had two values, and one is empty and
9847    the other holds a pointer that cannot be zero, the pointer is used
9848    as the discriminant, with a zero value meaning the empty variant.
9849    Here, the union's first member is of the form
9850    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9851    where the fieldnos are the indices of the fields that should be
9852    traversed in order to find the field (which may be several fields deep)
9853    and the variantname is the name of the variant of the case when the
9854    field is zero.
9855
9856    This function recognizes whether TYPE is of one of these forms,
9857    and, if so, smashes it to be a variant type.  */
9858
9859 static void
9860 quirk_rust_enum (struct type *type, struct objfile *objfile)
9861 {
9862   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9863
9864   /* We don't need to deal with empty enums.  */
9865   if (TYPE_NFIELDS (type) == 0)
9866     return;
9867
9868 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9869   if (TYPE_NFIELDS (type) == 1
9870       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9871     {
9872       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9873
9874       /* Decode the field name to find the offset of the
9875          discriminant.  */
9876       ULONGEST bit_offset = 0;
9877       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9878       while (name[0] >= '0' && name[0] <= '9')
9879         {
9880           char *tail;
9881           unsigned long index = strtoul (name, &tail, 10);
9882           name = tail;
9883           if (*name != '$'
9884               || index >= TYPE_NFIELDS (field_type)
9885               || (TYPE_FIELD_LOC_KIND (field_type, index)
9886                   != FIELD_LOC_KIND_BITPOS))
9887             {
9888               complaint (_("Could not parse Rust enum encoding string \"%s\""
9889                            "[in module %s]"),
9890                          TYPE_FIELD_NAME (type, 0),
9891                          objfile_name (objfile));
9892               return;
9893             }
9894           ++name;
9895
9896           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9897           field_type = TYPE_FIELD_TYPE (field_type, index);
9898         }
9899
9900       /* Make a union to hold the variants.  */
9901       struct type *union_type = alloc_type (objfile);
9902       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9903       TYPE_NFIELDS (union_type) = 3;
9904       TYPE_FIELDS (union_type)
9905         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9906       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9907       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9908
9909       /* Put the discriminant must at index 0.  */
9910       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9911       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9912       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9913       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9914
9915       /* The order of fields doesn't really matter, so put the real
9916          field at index 1 and the data-less field at index 2.  */
9917       struct discriminant_info *disc
9918         = alloc_discriminant_info (union_type, 0, 1);
9919       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9920       TYPE_FIELD_NAME (union_type, 1)
9921         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9922       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9923         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9924                               TYPE_FIELD_NAME (union_type, 1));
9925
9926       const char *dataless_name
9927         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9928                               name);
9929       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9930                                               dataless_name);
9931       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9932       /* NAME points into the original discriminant name, which
9933          already has the correct lifetime.  */
9934       TYPE_FIELD_NAME (union_type, 2) = name;
9935       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9936       disc->discriminants[2] = 0;
9937
9938       /* Smash this type to be a structure type.  We have to do this
9939          because the type has already been recorded.  */
9940       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9941       TYPE_NFIELDS (type) = 1;
9942       TYPE_FIELDS (type)
9943         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9944
9945       /* Install the variant part.  */
9946       TYPE_FIELD_TYPE (type, 0) = union_type;
9947       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9948       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9949     }
9950   else if (TYPE_NFIELDS (type) == 1)
9951     {
9952       /* We assume that a union with a single field is a univariant
9953          enum.  */
9954       /* Smash this type to be a structure type.  We have to do this
9955          because the type has already been recorded.  */
9956       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9957
9958       /* Make a union to hold the variants.  */
9959       struct type *union_type = alloc_type (objfile);
9960       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9961       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
9962       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9963       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9964       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
9965
9966       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
9967       const char *variant_name
9968         = rust_last_path_segment (TYPE_NAME (field_type));
9969       TYPE_FIELD_NAME (union_type, 0) = variant_name;
9970       TYPE_NAME (field_type)
9971         = rust_fully_qualify (&objfile->objfile_obstack,
9972                               TYPE_NAME (type), variant_name);
9973
9974       /* Install the union in the outer struct type.  */
9975       TYPE_NFIELDS (type) = 1;
9976       TYPE_FIELDS (type)
9977         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
9978       TYPE_FIELD_TYPE (type, 0) = union_type;
9979       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9980       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9981
9982       alloc_discriminant_info (union_type, -1, 0);
9983     }
9984   else
9985     {
9986       struct type *disr_type = nullptr;
9987       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
9988         {
9989           disr_type = TYPE_FIELD_TYPE (type, i);
9990
9991           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
9992             {
9993               /* All fields of a true enum will be structs.  */
9994               return;
9995             }
9996           else if (TYPE_NFIELDS (disr_type) == 0)
9997             {
9998               /* Could be data-less variant, so keep going.  */
9999               disr_type = nullptr;
10000             }
10001           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10002                            "RUST$ENUM$DISR") != 0)
10003             {
10004               /* Not a Rust enum.  */
10005               return;
10006             }
10007           else
10008             {
10009               /* Found one.  */
10010               break;
10011             }
10012         }
10013
10014       /* If we got here without a discriminant, then it's probably
10015          just a union.  */
10016       if (disr_type == nullptr)
10017         return;
10018
10019       /* Smash this type to be a structure type.  We have to do this
10020          because the type has already been recorded.  */
10021       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10022
10023       /* Make a union to hold the variants.  */
10024       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10025       struct type *union_type = alloc_type (objfile);
10026       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10027       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10028       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10029       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10030       TYPE_FIELDS (union_type)
10031         = (struct field *) TYPE_ZALLOC (union_type,
10032                                         (TYPE_NFIELDS (union_type)
10033                                          * sizeof (struct field)));
10034
10035       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10036               TYPE_NFIELDS (type) * sizeof (struct field));
10037
10038       /* Install the discriminant at index 0 in the union.  */
10039       TYPE_FIELD (union_type, 0) = *disr_field;
10040       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10041       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10042
10043       /* Install the union in the outer struct type.  */
10044       TYPE_FIELD_TYPE (type, 0) = union_type;
10045       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10046       TYPE_NFIELDS (type) = 1;
10047
10048       /* Set the size and offset of the union type.  */
10049       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10050
10051       /* We need a way to find the correct discriminant given a
10052          variant name.  For convenience we build a map here.  */
10053       struct type *enum_type = FIELD_TYPE (*disr_field);
10054       std::unordered_map<std::string, ULONGEST> discriminant_map;
10055       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10056         {
10057           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10058             {
10059               const char *name
10060                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10061               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10062             }
10063         }
10064
10065       int n_fields = TYPE_NFIELDS (union_type);
10066       struct discriminant_info *disc
10067         = alloc_discriminant_info (union_type, 0, -1);
10068       /* Skip the discriminant here.  */
10069       for (int i = 1; i < n_fields; ++i)
10070         {
10071           /* Find the final word in the name of this variant's type.
10072              That name can be used to look up the correct
10073              discriminant.  */
10074           const char *variant_name
10075             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10076                                                                   i)));
10077
10078           auto iter = discriminant_map.find (variant_name);
10079           if (iter != discriminant_map.end ())
10080             disc->discriminants[i] = iter->second;
10081
10082           /* Remove the discriminant field, if it exists.  */
10083           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10084           if (TYPE_NFIELDS (sub_type) > 0)
10085             {
10086               --TYPE_NFIELDS (sub_type);
10087               ++TYPE_FIELDS (sub_type);
10088             }
10089           TYPE_FIELD_NAME (union_type, i) = variant_name;
10090           TYPE_NAME (sub_type)
10091             = rust_fully_qualify (&objfile->objfile_obstack,
10092                                   TYPE_NAME (type), variant_name);
10093         }
10094     }
10095 }
10096
10097 /* Rewrite some Rust unions to be structures with variants parts.  */
10098
10099 static void
10100 rust_union_quirks (struct dwarf2_cu *cu)
10101 {
10102   gdb_assert (cu->language == language_rust);
10103   for (type *type_ : cu->rust_unions)
10104     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10105   /* We don't need this any more.  */
10106   cu->rust_unions.clear ();
10107 }
10108
10109 /* Return the symtab for PER_CU.  This works properly regardless of
10110    whether we're using the index or psymtabs.  */
10111
10112 static struct compunit_symtab *
10113 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10114 {
10115   return (per_cu->dwarf2_per_objfile->using_index
10116           ? per_cu->v.quick->compunit_symtab
10117           : per_cu->v.psymtab->compunit_symtab);
10118 }
10119
10120 /* A helper function for computing the list of all symbol tables
10121    included by PER_CU.  */
10122
10123 static void
10124 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10125                                 htab_t all_children, htab_t all_type_symtabs,
10126                                 struct dwarf2_per_cu_data *per_cu,
10127                                 struct compunit_symtab *immediate_parent)
10128 {
10129   void **slot;
10130   int ix;
10131   struct compunit_symtab *cust;
10132   struct dwarf2_per_cu_data *iter;
10133
10134   slot = htab_find_slot (all_children, per_cu, INSERT);
10135   if (*slot != NULL)
10136     {
10137       /* This inclusion and its children have been processed.  */
10138       return;
10139     }
10140
10141   *slot = per_cu;
10142   /* Only add a CU if it has a symbol table.  */
10143   cust = get_compunit_symtab (per_cu);
10144   if (cust != NULL)
10145     {
10146       /* If this is a type unit only add its symbol table if we haven't
10147          seen it yet (type unit per_cu's can share symtabs).  */
10148       if (per_cu->is_debug_types)
10149         {
10150           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10151           if (*slot == NULL)
10152             {
10153               *slot = cust;
10154               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10155               if (cust->user == NULL)
10156                 cust->user = immediate_parent;
10157             }
10158         }
10159       else
10160         {
10161           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10162           if (cust->user == NULL)
10163             cust->user = immediate_parent;
10164         }
10165     }
10166
10167   for (ix = 0;
10168        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10169        ++ix)
10170     {
10171       recursively_compute_inclusions (result, all_children,
10172                                       all_type_symtabs, iter, cust);
10173     }
10174 }
10175
10176 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10177    PER_CU.  */
10178
10179 static void
10180 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10181 {
10182   gdb_assert (! per_cu->is_debug_types);
10183
10184   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10185     {
10186       int ix, len;
10187       struct dwarf2_per_cu_data *per_cu_iter;
10188       struct compunit_symtab *compunit_symtab_iter;
10189       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10190       htab_t all_children, all_type_symtabs;
10191       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10192
10193       /* If we don't have a symtab, we can just skip this case.  */
10194       if (cust == NULL)
10195         return;
10196
10197       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10198                                         NULL, xcalloc, xfree);
10199       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10200                                             NULL, xcalloc, xfree);
10201
10202       for (ix = 0;
10203            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10204                         ix, per_cu_iter);
10205            ++ix)
10206         {
10207           recursively_compute_inclusions (&result_symtabs, all_children,
10208                                           all_type_symtabs, per_cu_iter,
10209                                           cust);
10210         }
10211
10212       /* Now we have a transitive closure of all the included symtabs.  */
10213       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10214       cust->includes
10215         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10216                      struct compunit_symtab *, len + 1);
10217       for (ix = 0;
10218            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10219                         compunit_symtab_iter);
10220            ++ix)
10221         cust->includes[ix] = compunit_symtab_iter;
10222       cust->includes[len] = NULL;
10223
10224       VEC_free (compunit_symtab_ptr, result_symtabs);
10225       htab_delete (all_children);
10226       htab_delete (all_type_symtabs);
10227     }
10228 }
10229
10230 /* Compute the 'includes' field for the symtabs of all the CUs we just
10231    read.  */
10232
10233 static void
10234 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10235 {
10236   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10237     {
10238       if (! iter->is_debug_types)
10239         compute_compunit_symtab_includes (iter);
10240     }
10241
10242   dwarf2_per_objfile->just_read_cus.clear ();
10243 }
10244
10245 /* Generate full symbol information for PER_CU, whose DIEs have
10246    already been loaded into memory.  */
10247
10248 static void
10249 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10250                         enum language pretend_language)
10251 {
10252   struct dwarf2_cu *cu = per_cu->cu;
10253   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10254   struct objfile *objfile = dwarf2_per_objfile->objfile;
10255   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10256   CORE_ADDR lowpc, highpc;
10257   struct compunit_symtab *cust;
10258   CORE_ADDR baseaddr;
10259   struct block *static_block;
10260   CORE_ADDR addr;
10261
10262   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10263
10264   buildsym_init ();
10265   scoped_free_pendings free_pending;
10266
10267   /* Clear the list here in case something was left over.  */
10268   cu->method_list.clear ();
10269
10270   cu->list_in_scope = &file_symbols;
10271
10272   cu->language = pretend_language;
10273   cu->language_defn = language_def (cu->language);
10274
10275   /* Do line number decoding in read_file_scope () */
10276   process_die (cu->dies, cu);
10277
10278   /* For now fudge the Go package.  */
10279   if (cu->language == language_go)
10280     fixup_go_packaging (cu);
10281
10282   /* Now that we have processed all the DIEs in the CU, all the types 
10283      should be complete, and it should now be safe to compute all of the
10284      physnames.  */
10285   compute_delayed_physnames (cu);
10286
10287   if (cu->language == language_rust)
10288     rust_union_quirks (cu);
10289
10290   /* Some compilers don't define a DW_AT_high_pc attribute for the
10291      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10292      it, by scanning the DIE's below the compilation unit.  */
10293   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10294
10295   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10296   static_block = end_symtab_get_static_block (addr, 0, 1);
10297
10298   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10299      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10300      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10301      addrmap to help ensure it has an accurate map of pc values belonging to
10302      this comp unit.  */
10303   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10304
10305   cust = end_symtab_from_static_block (static_block,
10306                                        SECT_OFF_TEXT (objfile), 0);
10307
10308   if (cust != NULL)
10309     {
10310       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10311
10312       /* Set symtab language to language from DW_AT_language.  If the
10313          compilation is from a C file generated by language preprocessors, do
10314          not set the language if it was already deduced by start_subfile.  */
10315       if (!(cu->language == language_c
10316             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10317         COMPUNIT_FILETABS (cust)->language = cu->language;
10318
10319       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10320          produce DW_AT_location with location lists but it can be possibly
10321          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10322          there were bugs in prologue debug info, fixed later in GCC-4.5
10323          by "unwind info for epilogues" patch (which is not directly related).
10324
10325          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10326          needed, it would be wrong due to missing DW_AT_producer there.
10327
10328          Still one can confuse GDB by using non-standard GCC compilation
10329          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10330          */ 
10331       if (cu->has_loclist && gcc_4_minor >= 5)
10332         cust->locations_valid = 1;
10333
10334       if (gcc_4_minor >= 5)
10335         cust->epilogue_unwind_valid = 1;
10336
10337       cust->call_site_htab = cu->call_site_htab;
10338     }
10339
10340   if (dwarf2_per_objfile->using_index)
10341     per_cu->v.quick->compunit_symtab = cust;
10342   else
10343     {
10344       struct partial_symtab *pst = per_cu->v.psymtab;
10345       pst->compunit_symtab = cust;
10346       pst->readin = 1;
10347     }
10348
10349   /* Push it for inclusion processing later.  */
10350   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10351 }
10352
10353 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10354    already been loaded into memory.  */
10355
10356 static void
10357 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10358                         enum language pretend_language)
10359 {
10360   struct dwarf2_cu *cu = per_cu->cu;
10361   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10362   struct objfile *objfile = dwarf2_per_objfile->objfile;
10363   struct compunit_symtab *cust;
10364   struct signatured_type *sig_type;
10365
10366   gdb_assert (per_cu->is_debug_types);
10367   sig_type = (struct signatured_type *) per_cu;
10368
10369   buildsym_init ();
10370   scoped_free_pendings free_pending;
10371
10372   /* Clear the list here in case something was left over.  */
10373   cu->method_list.clear ();
10374
10375   cu->list_in_scope = &file_symbols;
10376
10377   cu->language = pretend_language;
10378   cu->language_defn = language_def (cu->language);
10379
10380   /* The symbol tables are set up in read_type_unit_scope.  */
10381   process_die (cu->dies, cu);
10382
10383   /* For now fudge the Go package.  */
10384   if (cu->language == language_go)
10385     fixup_go_packaging (cu);
10386
10387   /* Now that we have processed all the DIEs in the CU, all the types 
10388      should be complete, and it should now be safe to compute all of the
10389      physnames.  */
10390   compute_delayed_physnames (cu);
10391
10392   if (cu->language == language_rust)
10393     rust_union_quirks (cu);
10394
10395   /* TUs share symbol tables.
10396      If this is the first TU to use this symtab, complete the construction
10397      of it with end_expandable_symtab.  Otherwise, complete the addition of
10398      this TU's symbols to the existing symtab.  */
10399   if (sig_type->type_unit_group->compunit_symtab == NULL)
10400     {
10401       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10402       sig_type->type_unit_group->compunit_symtab = cust;
10403
10404       if (cust != NULL)
10405         {
10406           /* Set symtab language to language from DW_AT_language.  If the
10407              compilation is from a C file generated by language preprocessors,
10408              do not set the language if it was already deduced by
10409              start_subfile.  */
10410           if (!(cu->language == language_c
10411                 && COMPUNIT_FILETABS (cust)->language != language_c))
10412             COMPUNIT_FILETABS (cust)->language = cu->language;
10413         }
10414     }
10415   else
10416     {
10417       augment_type_symtab ();
10418       cust = sig_type->type_unit_group->compunit_symtab;
10419     }
10420
10421   if (dwarf2_per_objfile->using_index)
10422     per_cu->v.quick->compunit_symtab = cust;
10423   else
10424     {
10425       struct partial_symtab *pst = per_cu->v.psymtab;
10426       pst->compunit_symtab = cust;
10427       pst->readin = 1;
10428     }
10429 }
10430
10431 /* Process an imported unit DIE.  */
10432
10433 static void
10434 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10435 {
10436   struct attribute *attr;
10437
10438   /* For now we don't handle imported units in type units.  */
10439   if (cu->per_cu->is_debug_types)
10440     {
10441       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10442                " supported in type units [in module %s]"),
10443              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10444     }
10445
10446   attr = dwarf2_attr (die, DW_AT_import, cu);
10447   if (attr != NULL)
10448     {
10449       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10450       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10451       dwarf2_per_cu_data *per_cu
10452         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10453                                             cu->per_cu->dwarf2_per_objfile);
10454
10455       /* If necessary, add it to the queue and load its DIEs.  */
10456       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10457         load_full_comp_unit (per_cu, false, cu->language);
10458
10459       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10460                      per_cu);
10461     }
10462 }
10463
10464 /* RAII object that represents a process_die scope: i.e.,
10465    starts/finishes processing a DIE.  */
10466 class process_die_scope
10467 {
10468 public:
10469   process_die_scope (die_info *die, dwarf2_cu *cu)
10470     : m_die (die), m_cu (cu)
10471   {
10472     /* We should only be processing DIEs not already in process.  */
10473     gdb_assert (!m_die->in_process);
10474     m_die->in_process = true;
10475   }
10476
10477   ~process_die_scope ()
10478   {
10479     m_die->in_process = false;
10480
10481     /* If we're done processing the DIE for the CU that owns the line
10482        header, we don't need the line header anymore.  */
10483     if (m_cu->line_header_die_owner == m_die)
10484       {
10485         delete m_cu->line_header;
10486         m_cu->line_header = NULL;
10487         m_cu->line_header_die_owner = NULL;
10488       }
10489   }
10490
10491 private:
10492   die_info *m_die;
10493   dwarf2_cu *m_cu;
10494 };
10495
10496 /* Process a die and its children.  */
10497
10498 static void
10499 process_die (struct die_info *die, struct dwarf2_cu *cu)
10500 {
10501   process_die_scope scope (die, cu);
10502
10503   switch (die->tag)
10504     {
10505     case DW_TAG_padding:
10506       break;
10507     case DW_TAG_compile_unit:
10508     case DW_TAG_partial_unit:
10509       read_file_scope (die, cu);
10510       break;
10511     case DW_TAG_type_unit:
10512       read_type_unit_scope (die, cu);
10513       break;
10514     case DW_TAG_subprogram:
10515     case DW_TAG_inlined_subroutine:
10516       read_func_scope (die, cu);
10517       break;
10518     case DW_TAG_lexical_block:
10519     case DW_TAG_try_block:
10520     case DW_TAG_catch_block:
10521       read_lexical_block_scope (die, cu);
10522       break;
10523     case DW_TAG_call_site:
10524     case DW_TAG_GNU_call_site:
10525       read_call_site_scope (die, cu);
10526       break;
10527     case DW_TAG_class_type:
10528     case DW_TAG_interface_type:
10529     case DW_TAG_structure_type:
10530     case DW_TAG_union_type:
10531       process_structure_scope (die, cu);
10532       break;
10533     case DW_TAG_enumeration_type:
10534       process_enumeration_scope (die, cu);
10535       break;
10536
10537     /* These dies have a type, but processing them does not create
10538        a symbol or recurse to process the children.  Therefore we can
10539        read them on-demand through read_type_die.  */
10540     case DW_TAG_subroutine_type:
10541     case DW_TAG_set_type:
10542     case DW_TAG_array_type:
10543     case DW_TAG_pointer_type:
10544     case DW_TAG_ptr_to_member_type:
10545     case DW_TAG_reference_type:
10546     case DW_TAG_rvalue_reference_type:
10547     case DW_TAG_string_type:
10548       break;
10549
10550     case DW_TAG_base_type:
10551     case DW_TAG_subrange_type:
10552     case DW_TAG_typedef:
10553       /* Add a typedef symbol for the type definition, if it has a
10554          DW_AT_name.  */
10555       new_symbol (die, read_type_die (die, cu), cu);
10556       break;
10557     case DW_TAG_common_block:
10558       read_common_block (die, cu);
10559       break;
10560     case DW_TAG_common_inclusion:
10561       break;
10562     case DW_TAG_namespace:
10563       cu->processing_has_namespace_info = 1;
10564       read_namespace (die, cu);
10565       break;
10566     case DW_TAG_module:
10567       cu->processing_has_namespace_info = 1;
10568       read_module (die, cu);
10569       break;
10570     case DW_TAG_imported_declaration:
10571       cu->processing_has_namespace_info = 1;
10572       if (read_namespace_alias (die, cu))
10573         break;
10574       /* The declaration is not a global namespace alias.  */
10575       /* Fall through.  */
10576     case DW_TAG_imported_module:
10577       cu->processing_has_namespace_info = 1;
10578       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10579                                  || cu->language != language_fortran))
10580         complaint (_("Tag '%s' has unexpected children"),
10581                    dwarf_tag_name (die->tag));
10582       read_import_statement (die, cu);
10583       break;
10584
10585     case DW_TAG_imported_unit:
10586       process_imported_unit_die (die, cu);
10587       break;
10588
10589     case DW_TAG_variable:
10590       read_variable (die, cu);
10591       break;
10592
10593     default:
10594       new_symbol (die, NULL, cu);
10595       break;
10596     }
10597 }
10598 \f
10599 /* DWARF name computation.  */
10600
10601 /* A helper function for dwarf2_compute_name which determines whether DIE
10602    needs to have the name of the scope prepended to the name listed in the
10603    die.  */
10604
10605 static int
10606 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10607 {
10608   struct attribute *attr;
10609
10610   switch (die->tag)
10611     {
10612     case DW_TAG_namespace:
10613     case DW_TAG_typedef:
10614     case DW_TAG_class_type:
10615     case DW_TAG_interface_type:
10616     case DW_TAG_structure_type:
10617     case DW_TAG_union_type:
10618     case DW_TAG_enumeration_type:
10619     case DW_TAG_enumerator:
10620     case DW_TAG_subprogram:
10621     case DW_TAG_inlined_subroutine:
10622     case DW_TAG_member:
10623     case DW_TAG_imported_declaration:
10624       return 1;
10625
10626     case DW_TAG_variable:
10627     case DW_TAG_constant:
10628       /* We only need to prefix "globally" visible variables.  These include
10629          any variable marked with DW_AT_external or any variable that
10630          lives in a namespace.  [Variables in anonymous namespaces
10631          require prefixing, but they are not DW_AT_external.]  */
10632
10633       if (dwarf2_attr (die, DW_AT_specification, cu))
10634         {
10635           struct dwarf2_cu *spec_cu = cu;
10636
10637           return die_needs_namespace (die_specification (die, &spec_cu),
10638                                       spec_cu);
10639         }
10640
10641       attr = dwarf2_attr (die, DW_AT_external, cu);
10642       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10643           && die->parent->tag != DW_TAG_module)
10644         return 0;
10645       /* A variable in a lexical block of some kind does not need a
10646          namespace, even though in C++ such variables may be external
10647          and have a mangled name.  */
10648       if (die->parent->tag ==  DW_TAG_lexical_block
10649           || die->parent->tag ==  DW_TAG_try_block
10650           || die->parent->tag ==  DW_TAG_catch_block
10651           || die->parent->tag == DW_TAG_subprogram)
10652         return 0;
10653       return 1;
10654
10655     default:
10656       return 0;
10657     }
10658 }
10659
10660 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10661    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10662    defined for the given DIE.  */
10663
10664 static struct attribute *
10665 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10666 {
10667   struct attribute *attr;
10668
10669   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10670   if (attr == NULL)
10671     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10672
10673   return attr;
10674 }
10675
10676 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10677    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10678    defined for the given DIE.  */
10679
10680 static const char *
10681 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10682 {
10683   const char *linkage_name;
10684
10685   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10686   if (linkage_name == NULL)
10687     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10688
10689   return linkage_name;
10690 }
10691
10692 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10693    compute the physname for the object, which include a method's:
10694    - formal parameters (C++),
10695    - receiver type (Go),
10696
10697    The term "physname" is a bit confusing.
10698    For C++, for example, it is the demangled name.
10699    For Go, for example, it's the mangled name.
10700
10701    For Ada, return the DIE's linkage name rather than the fully qualified
10702    name.  PHYSNAME is ignored..
10703
10704    The result is allocated on the objfile_obstack and canonicalized.  */
10705
10706 static const char *
10707 dwarf2_compute_name (const char *name,
10708                      struct die_info *die, struct dwarf2_cu *cu,
10709                      int physname)
10710 {
10711   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10712
10713   if (name == NULL)
10714     name = dwarf2_name (die, cu);
10715
10716   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10717      but otherwise compute it by typename_concat inside GDB.
10718      FIXME: Actually this is not really true, or at least not always true.
10719      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10720      Fortran names because there is no mangling standard.  So new_symbol
10721      will set the demangled name to the result of dwarf2_full_name, and it is
10722      the demangled name that GDB uses if it exists.  */
10723   if (cu->language == language_ada
10724       || (cu->language == language_fortran && physname))
10725     {
10726       /* For Ada unit, we prefer the linkage name over the name, as
10727          the former contains the exported name, which the user expects
10728          to be able to reference.  Ideally, we want the user to be able
10729          to reference this entity using either natural or linkage name,
10730          but we haven't started looking at this enhancement yet.  */
10731       const char *linkage_name = dw2_linkage_name (die, cu);
10732
10733       if (linkage_name != NULL)
10734         return linkage_name;
10735     }
10736
10737   /* These are the only languages we know how to qualify names in.  */
10738   if (name != NULL
10739       && (cu->language == language_cplus
10740           || cu->language == language_fortran || cu->language == language_d
10741           || cu->language == language_rust))
10742     {
10743       if (die_needs_namespace (die, cu))
10744         {
10745           const char *prefix;
10746           const char *canonical_name = NULL;
10747
10748           string_file buf;
10749
10750           prefix = determine_prefix (die, cu);
10751           if (*prefix != '\0')
10752             {
10753               char *prefixed_name = typename_concat (NULL, prefix, name,
10754                                                      physname, cu);
10755
10756               buf.puts (prefixed_name);
10757               xfree (prefixed_name);
10758             }
10759           else
10760             buf.puts (name);
10761
10762           /* Template parameters may be specified in the DIE's DW_AT_name, or
10763              as children with DW_TAG_template_type_param or
10764              DW_TAG_value_type_param.  If the latter, add them to the name
10765              here.  If the name already has template parameters, then
10766              skip this step; some versions of GCC emit both, and
10767              it is more efficient to use the pre-computed name.
10768
10769              Something to keep in mind about this process: it is very
10770              unlikely, or in some cases downright impossible, to produce
10771              something that will match the mangled name of a function.
10772              If the definition of the function has the same debug info,
10773              we should be able to match up with it anyway.  But fallbacks
10774              using the minimal symbol, for instance to find a method
10775              implemented in a stripped copy of libstdc++, will not work.
10776              If we do not have debug info for the definition, we will have to
10777              match them up some other way.
10778
10779              When we do name matching there is a related problem with function
10780              templates; two instantiated function templates are allowed to
10781              differ only by their return types, which we do not add here.  */
10782
10783           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10784             {
10785               struct attribute *attr;
10786               struct die_info *child;
10787               int first = 1;
10788
10789               die->building_fullname = 1;
10790
10791               for (child = die->child; child != NULL; child = child->sibling)
10792                 {
10793                   struct type *type;
10794                   LONGEST value;
10795                   const gdb_byte *bytes;
10796                   struct dwarf2_locexpr_baton *baton;
10797                   struct value *v;
10798
10799                   if (child->tag != DW_TAG_template_type_param
10800                       && child->tag != DW_TAG_template_value_param)
10801                     continue;
10802
10803                   if (first)
10804                     {
10805                       buf.puts ("<");
10806                       first = 0;
10807                     }
10808                   else
10809                     buf.puts (", ");
10810
10811                   attr = dwarf2_attr (child, DW_AT_type, cu);
10812                   if (attr == NULL)
10813                     {
10814                       complaint (_("template parameter missing DW_AT_type"));
10815                       buf.puts ("UNKNOWN_TYPE");
10816                       continue;
10817                     }
10818                   type = die_type (child, cu);
10819
10820                   if (child->tag == DW_TAG_template_type_param)
10821                     {
10822                       c_print_type (type, "", &buf, -1, 0, cu->language,
10823                                     &type_print_raw_options);
10824                       continue;
10825                     }
10826
10827                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10828                   if (attr == NULL)
10829                     {
10830                       complaint (_("template parameter missing "
10831                                    "DW_AT_const_value"));
10832                       buf.puts ("UNKNOWN_VALUE");
10833                       continue;
10834                     }
10835
10836                   dwarf2_const_value_attr (attr, type, name,
10837                                            &cu->comp_unit_obstack, cu,
10838                                            &value, &bytes, &baton);
10839
10840                   if (TYPE_NOSIGN (type))
10841                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10842                        changed, this can use value_print instead.  */
10843                     c_printchar (value, type, &buf);
10844                   else
10845                     {
10846                       struct value_print_options opts;
10847
10848                       if (baton != NULL)
10849                         v = dwarf2_evaluate_loc_desc (type, NULL,
10850                                                       baton->data,
10851                                                       baton->size,
10852                                                       baton->per_cu);
10853                       else if (bytes != NULL)
10854                         {
10855                           v = allocate_value (type);
10856                           memcpy (value_contents_writeable (v), bytes,
10857                                   TYPE_LENGTH (type));
10858                         }
10859                       else
10860                         v = value_from_longest (type, value);
10861
10862                       /* Specify decimal so that we do not depend on
10863                          the radix.  */
10864                       get_formatted_print_options (&opts, 'd');
10865                       opts.raw = 1;
10866                       value_print (v, &buf, &opts);
10867                       release_value (v);
10868                     }
10869                 }
10870
10871               die->building_fullname = 0;
10872
10873               if (!first)
10874                 {
10875                   /* Close the argument list, with a space if necessary
10876                      (nested templates).  */
10877                   if (!buf.empty () && buf.string ().back () == '>')
10878                     buf.puts (" >");
10879                   else
10880                     buf.puts (">");
10881                 }
10882             }
10883
10884           /* For C++ methods, append formal parameter type
10885              information, if PHYSNAME.  */
10886
10887           if (physname && die->tag == DW_TAG_subprogram
10888               && cu->language == language_cplus)
10889             {
10890               struct type *type = read_type_die (die, cu);
10891
10892               c_type_print_args (type, &buf, 1, cu->language,
10893                                  &type_print_raw_options);
10894
10895               if (cu->language == language_cplus)
10896                 {
10897                   /* Assume that an artificial first parameter is
10898                      "this", but do not crash if it is not.  RealView
10899                      marks unnamed (and thus unused) parameters as
10900                      artificial; there is no way to differentiate
10901                      the two cases.  */
10902                   if (TYPE_NFIELDS (type) > 0
10903                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10904                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10905                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10906                                                                         0))))
10907                     buf.puts (" const");
10908                 }
10909             }
10910
10911           const std::string &intermediate_name = buf.string ();
10912
10913           if (cu->language == language_cplus)
10914             canonical_name
10915               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10916                                           &objfile->per_bfd->storage_obstack);
10917
10918           /* If we only computed INTERMEDIATE_NAME, or if
10919              INTERMEDIATE_NAME is already canonical, then we need to
10920              copy it to the appropriate obstack.  */
10921           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10922             name = ((const char *)
10923                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10924                                    intermediate_name.c_str (),
10925                                    intermediate_name.length ()));
10926           else
10927             name = canonical_name;
10928         }
10929     }
10930
10931   return name;
10932 }
10933
10934 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10935    If scope qualifiers are appropriate they will be added.  The result
10936    will be allocated on the storage_obstack, or NULL if the DIE does
10937    not have a name.  NAME may either be from a previous call to
10938    dwarf2_name or NULL.
10939
10940    The output string will be canonicalized (if C++).  */
10941
10942 static const char *
10943 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10944 {
10945   return dwarf2_compute_name (name, die, cu, 0);
10946 }
10947
10948 /* Construct a physname for the given DIE in CU.  NAME may either be
10949    from a previous call to dwarf2_name or NULL.  The result will be
10950    allocated on the objfile_objstack or NULL if the DIE does not have a
10951    name.
10952
10953    The output string will be canonicalized (if C++).  */
10954
10955 static const char *
10956 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10957 {
10958   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10959   const char *retval, *mangled = NULL, *canon = NULL;
10960   int need_copy = 1;
10961
10962   /* In this case dwarf2_compute_name is just a shortcut not building anything
10963      on its own.  */
10964   if (!die_needs_namespace (die, cu))
10965     return dwarf2_compute_name (name, die, cu, 1);
10966
10967   mangled = dw2_linkage_name (die, cu);
10968
10969   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10970      See https://github.com/rust-lang/rust/issues/32925.  */
10971   if (cu->language == language_rust && mangled != NULL
10972       && strchr (mangled, '{') != NULL)
10973     mangled = NULL;
10974
10975   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10976      has computed.  */
10977   gdb::unique_xmalloc_ptr<char> demangled;
10978   if (mangled != NULL)
10979     {
10980
10981       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
10982         {
10983           /* Do nothing (do not demangle the symbol name).  */
10984         }
10985       else if (cu->language == language_go)
10986         {
10987           /* This is a lie, but we already lie to the caller new_symbol.
10988              new_symbol assumes we return the mangled name.
10989              This just undoes that lie until things are cleaned up.  */
10990         }
10991       else
10992         {
10993           /* Use DMGL_RET_DROP for C++ template functions to suppress
10994              their return type.  It is easier for GDB users to search
10995              for such functions as `name(params)' than `long name(params)'.
10996              In such case the minimal symbol names do not match the full
10997              symbol names but for template functions there is never a need
10998              to look up their definition from their declaration so
10999              the only disadvantage remains the minimal symbol variant
11000              `long name(params)' does not have the proper inferior type.  */
11001           demangled.reset (gdb_demangle (mangled,
11002                                          (DMGL_PARAMS | DMGL_ANSI
11003                                           | DMGL_RET_DROP)));
11004         }
11005       if (demangled)
11006         canon = demangled.get ();
11007       else
11008         {
11009           canon = mangled;
11010           need_copy = 0;
11011         }
11012     }
11013
11014   if (canon == NULL || check_physname)
11015     {
11016       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11017
11018       if (canon != NULL && strcmp (physname, canon) != 0)
11019         {
11020           /* It may not mean a bug in GDB.  The compiler could also
11021              compute DW_AT_linkage_name incorrectly.  But in such case
11022              GDB would need to be bug-to-bug compatible.  */
11023
11024           complaint (_("Computed physname <%s> does not match demangled <%s> "
11025                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11026                      physname, canon, mangled, sect_offset_str (die->sect_off),
11027                      objfile_name (objfile));
11028
11029           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11030              is available here - over computed PHYSNAME.  It is safer
11031              against both buggy GDB and buggy compilers.  */
11032
11033           retval = canon;
11034         }
11035       else
11036         {
11037           retval = physname;
11038           need_copy = 0;
11039         }
11040     }
11041   else
11042     retval = canon;
11043
11044   if (need_copy)
11045     retval = ((const char *)
11046               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11047                              retval, strlen (retval)));
11048
11049   return retval;
11050 }
11051
11052 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11053    a new symbol for it.
11054
11055    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11056
11057 static int
11058 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11059 {
11060   struct attribute *attr;
11061
11062   /* If the die does not have a name, this is not a namespace
11063      alias.  */
11064   attr = dwarf2_attr (die, DW_AT_name, cu);
11065   if (attr != NULL)
11066     {
11067       int num;
11068       struct die_info *d = die;
11069       struct dwarf2_cu *imported_cu = cu;
11070
11071       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11072          keep inspecting DIEs until we hit the underlying import.  */
11073 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11074       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11075         {
11076           attr = dwarf2_attr (d, DW_AT_import, cu);
11077           if (attr == NULL)
11078             break;
11079
11080           d = follow_die_ref (d, attr, &imported_cu);
11081           if (d->tag != DW_TAG_imported_declaration)
11082             break;
11083         }
11084
11085       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11086         {
11087           complaint (_("DIE at %s has too many recursively imported "
11088                        "declarations"), sect_offset_str (d->sect_off));
11089           return 0;
11090         }
11091
11092       if (attr != NULL)
11093         {
11094           struct type *type;
11095           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11096
11097           type = get_die_type_at_offset (sect_off, cu->per_cu);
11098           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11099             {
11100               /* This declaration is a global namespace alias.  Add
11101                  a symbol for it whose type is the aliased namespace.  */
11102               new_symbol (die, type, cu);
11103               return 1;
11104             }
11105         }
11106     }
11107
11108   return 0;
11109 }
11110
11111 /* Return the using directives repository (global or local?) to use in the
11112    current context for LANGUAGE.
11113
11114    For Ada, imported declarations can materialize renamings, which *may* be
11115    global.  However it is impossible (for now?) in DWARF to distinguish
11116    "external" imported declarations and "static" ones.  As all imported
11117    declarations seem to be static in all other languages, make them all CU-wide
11118    global only in Ada.  */
11119
11120 static struct using_direct **
11121 using_directives (enum language language)
11122 {
11123   if (language == language_ada && context_stack_depth == 0)
11124     return &global_using_directives;
11125   else
11126     return &local_using_directives;
11127 }
11128
11129 /* Read the import statement specified by the given die and record it.  */
11130
11131 static void
11132 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11133 {
11134   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11135   struct attribute *import_attr;
11136   struct die_info *imported_die, *child_die;
11137   struct dwarf2_cu *imported_cu;
11138   const char *imported_name;
11139   const char *imported_name_prefix;
11140   const char *canonical_name;
11141   const char *import_alias;
11142   const char *imported_declaration = NULL;
11143   const char *import_prefix;
11144   std::vector<const char *> excludes;
11145
11146   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11147   if (import_attr == NULL)
11148     {
11149       complaint (_("Tag '%s' has no DW_AT_import"),
11150                  dwarf_tag_name (die->tag));
11151       return;
11152     }
11153
11154   imported_cu = cu;
11155   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11156   imported_name = dwarf2_name (imported_die, imported_cu);
11157   if (imported_name == NULL)
11158     {
11159       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11160
11161         The import in the following code:
11162         namespace A
11163           {
11164             typedef int B;
11165           }
11166
11167         int main ()
11168           {
11169             using A::B;
11170             B b;
11171             return b;
11172           }
11173
11174         ...
11175          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11176             <52>   DW_AT_decl_file   : 1
11177             <53>   DW_AT_decl_line   : 6
11178             <54>   DW_AT_import      : <0x75>
11179          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11180             <59>   DW_AT_name        : B
11181             <5b>   DW_AT_decl_file   : 1
11182             <5c>   DW_AT_decl_line   : 2
11183             <5d>   DW_AT_type        : <0x6e>
11184         ...
11185          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11186             <76>   DW_AT_byte_size   : 4
11187             <77>   DW_AT_encoding    : 5        (signed)
11188
11189         imports the wrong die ( 0x75 instead of 0x58 ).
11190         This case will be ignored until the gcc bug is fixed.  */
11191       return;
11192     }
11193
11194   /* Figure out the local name after import.  */
11195   import_alias = dwarf2_name (die, cu);
11196
11197   /* Figure out where the statement is being imported to.  */
11198   import_prefix = determine_prefix (die, cu);
11199
11200   /* Figure out what the scope of the imported die is and prepend it
11201      to the name of the imported die.  */
11202   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11203
11204   if (imported_die->tag != DW_TAG_namespace
11205       && imported_die->tag != DW_TAG_module)
11206     {
11207       imported_declaration = imported_name;
11208       canonical_name = imported_name_prefix;
11209     }
11210   else if (strlen (imported_name_prefix) > 0)
11211     canonical_name = obconcat (&objfile->objfile_obstack,
11212                                imported_name_prefix,
11213                                (cu->language == language_d ? "." : "::"),
11214                                imported_name, (char *) NULL);
11215   else
11216     canonical_name = imported_name;
11217
11218   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11219     for (child_die = die->child; child_die && child_die->tag;
11220          child_die = sibling_die (child_die))
11221       {
11222         /* DWARF-4: A Fortran use statement with a “rename list” may be
11223            represented by an imported module entry with an import attribute
11224            referring to the module and owned entries corresponding to those
11225            entities that are renamed as part of being imported.  */
11226
11227         if (child_die->tag != DW_TAG_imported_declaration)
11228           {
11229             complaint (_("child DW_TAG_imported_declaration expected "
11230                          "- DIE at %s [in module %s]"),
11231                        sect_offset_str (child_die->sect_off),
11232                        objfile_name (objfile));
11233             continue;
11234           }
11235
11236         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11237         if (import_attr == NULL)
11238           {
11239             complaint (_("Tag '%s' has no DW_AT_import"),
11240                        dwarf_tag_name (child_die->tag));
11241             continue;
11242           }
11243
11244         imported_cu = cu;
11245         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11246                                               &imported_cu);
11247         imported_name = dwarf2_name (imported_die, imported_cu);
11248         if (imported_name == NULL)
11249           {
11250             complaint (_("child DW_TAG_imported_declaration has unknown "
11251                          "imported name - DIE at %s [in module %s]"),
11252                        sect_offset_str (child_die->sect_off),
11253                        objfile_name (objfile));
11254             continue;
11255           }
11256
11257         excludes.push_back (imported_name);
11258
11259         process_die (child_die, cu);
11260       }
11261
11262   add_using_directive (using_directives (cu->language),
11263                        import_prefix,
11264                        canonical_name,
11265                        import_alias,
11266                        imported_declaration,
11267                        excludes,
11268                        0,
11269                        &objfile->objfile_obstack);
11270 }
11271
11272 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11273    types, but gives them a size of zero.  Starting with version 14,
11274    ICC is compatible with GCC.  */
11275
11276 static int
11277 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11278 {
11279   if (!cu->checked_producer)
11280     check_producer (cu);
11281
11282   return cu->producer_is_icc_lt_14;
11283 }
11284
11285 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11286    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11287    this, it was first present in GCC release 4.3.0.  */
11288
11289 static int
11290 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11291 {
11292   if (!cu->checked_producer)
11293     check_producer (cu);
11294
11295   return cu->producer_is_gcc_lt_4_3;
11296 }
11297
11298 static file_and_directory
11299 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11300 {
11301   file_and_directory res;
11302
11303   /* Find the filename.  Do not use dwarf2_name here, since the filename
11304      is not a source language identifier.  */
11305   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11306   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11307
11308   if (res.comp_dir == NULL
11309       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11310       && IS_ABSOLUTE_PATH (res.name))
11311     {
11312       res.comp_dir_storage = ldirname (res.name);
11313       if (!res.comp_dir_storage.empty ())
11314         res.comp_dir = res.comp_dir_storage.c_str ();
11315     }
11316   if (res.comp_dir != NULL)
11317     {
11318       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11319          directory, get rid of it.  */
11320       const char *cp = strchr (res.comp_dir, ':');
11321
11322       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11323         res.comp_dir = cp + 1;
11324     }
11325
11326   if (res.name == NULL)
11327     res.name = "<unknown>";
11328
11329   return res;
11330 }
11331
11332 /* Handle DW_AT_stmt_list for a compilation unit.
11333    DIE is the DW_TAG_compile_unit die for CU.
11334    COMP_DIR is the compilation directory.  LOWPC is passed to
11335    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11336
11337 static void
11338 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11339                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11340 {
11341   struct dwarf2_per_objfile *dwarf2_per_objfile
11342     = cu->per_cu->dwarf2_per_objfile;
11343   struct objfile *objfile = dwarf2_per_objfile->objfile;
11344   struct attribute *attr;
11345   struct line_header line_header_local;
11346   hashval_t line_header_local_hash;
11347   void **slot;
11348   int decode_mapping;
11349
11350   gdb_assert (! cu->per_cu->is_debug_types);
11351
11352   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11353   if (attr == NULL)
11354     return;
11355
11356   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11357
11358   /* The line header hash table is only created if needed (it exists to
11359      prevent redundant reading of the line table for partial_units).
11360      If we're given a partial_unit, we'll need it.  If we're given a
11361      compile_unit, then use the line header hash table if it's already
11362      created, but don't create one just yet.  */
11363
11364   if (dwarf2_per_objfile->line_header_hash == NULL
11365       && die->tag == DW_TAG_partial_unit)
11366     {
11367       dwarf2_per_objfile->line_header_hash
11368         = htab_create_alloc_ex (127, line_header_hash_voidp,
11369                                 line_header_eq_voidp,
11370                                 free_line_header_voidp,
11371                                 &objfile->objfile_obstack,
11372                                 hashtab_obstack_allocate,
11373                                 dummy_obstack_deallocate);
11374     }
11375
11376   line_header_local.sect_off = line_offset;
11377   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11378   line_header_local_hash = line_header_hash (&line_header_local);
11379   if (dwarf2_per_objfile->line_header_hash != NULL)
11380     {
11381       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11382                                        &line_header_local,
11383                                        line_header_local_hash, NO_INSERT);
11384
11385       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11386          is not present in *SLOT (since if there is something in *SLOT then
11387          it will be for a partial_unit).  */
11388       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11389         {
11390           gdb_assert (*slot != NULL);
11391           cu->line_header = (struct line_header *) *slot;
11392           return;
11393         }
11394     }
11395
11396   /* dwarf_decode_line_header does not yet provide sufficient information.
11397      We always have to call also dwarf_decode_lines for it.  */
11398   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11399   if (lh == NULL)
11400     return;
11401
11402   cu->line_header = lh.release ();
11403   cu->line_header_die_owner = die;
11404
11405   if (dwarf2_per_objfile->line_header_hash == NULL)
11406     slot = NULL;
11407   else
11408     {
11409       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11410                                        &line_header_local,
11411                                        line_header_local_hash, INSERT);
11412       gdb_assert (slot != NULL);
11413     }
11414   if (slot != NULL && *slot == NULL)
11415     {
11416       /* This newly decoded line number information unit will be owned
11417          by line_header_hash hash table.  */
11418       *slot = cu->line_header;
11419       cu->line_header_die_owner = NULL;
11420     }
11421   else
11422     {
11423       /* We cannot free any current entry in (*slot) as that struct line_header
11424          may be already used by multiple CUs.  Create only temporary decoded
11425          line_header for this CU - it may happen at most once for each line
11426          number information unit.  And if we're not using line_header_hash
11427          then this is what we want as well.  */
11428       gdb_assert (die->tag != DW_TAG_partial_unit);
11429     }
11430   decode_mapping = (die->tag != DW_TAG_partial_unit);
11431   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11432                       decode_mapping);
11433
11434 }
11435
11436 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11437
11438 static void
11439 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11440 {
11441   struct dwarf2_per_objfile *dwarf2_per_objfile
11442     = cu->per_cu->dwarf2_per_objfile;
11443   struct objfile *objfile = dwarf2_per_objfile->objfile;
11444   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11445   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11446   CORE_ADDR highpc = ((CORE_ADDR) 0);
11447   struct attribute *attr;
11448   struct die_info *child_die;
11449   CORE_ADDR baseaddr;
11450
11451   prepare_one_comp_unit (cu, die, cu->language);
11452   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11453
11454   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11455
11456   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11457      from finish_block.  */
11458   if (lowpc == ((CORE_ADDR) -1))
11459     lowpc = highpc;
11460   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11461
11462   file_and_directory fnd = find_file_and_directory (die, cu);
11463
11464   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11465      standardised yet.  As a workaround for the language detection we fall
11466      back to the DW_AT_producer string.  */
11467   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11468     cu->language = language_opencl;
11469
11470   /* Similar hack for Go.  */
11471   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11472     set_cu_language (DW_LANG_Go, cu);
11473
11474   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11475
11476   /* Decode line number information if present.  We do this before
11477      processing child DIEs, so that the line header table is available
11478      for DW_AT_decl_file.  */
11479   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11480
11481   /* Process all dies in compilation unit.  */
11482   if (die->child != NULL)
11483     {
11484       child_die = die->child;
11485       while (child_die && child_die->tag)
11486         {
11487           process_die (child_die, cu);
11488           child_die = sibling_die (child_die);
11489         }
11490     }
11491
11492   /* Decode macro information, if present.  Dwarf 2 macro information
11493      refers to information in the line number info statement program
11494      header, so we can only read it if we've read the header
11495      successfully.  */
11496   attr = dwarf2_attr (die, DW_AT_macros, cu);
11497   if (attr == NULL)
11498     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11499   if (attr && cu->line_header)
11500     {
11501       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11502         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11503
11504       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11505     }
11506   else
11507     {
11508       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11509       if (attr && cu->line_header)
11510         {
11511           unsigned int macro_offset = DW_UNSND (attr);
11512
11513           dwarf_decode_macros (cu, macro_offset, 0);
11514         }
11515     }
11516 }
11517
11518 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11519    Create the set of symtabs used by this TU, or if this TU is sharing
11520    symtabs with another TU and the symtabs have already been created
11521    then restore those symtabs in the line header.
11522    We don't need the pc/line-number mapping for type units.  */
11523
11524 static void
11525 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11526 {
11527   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11528   struct type_unit_group *tu_group;
11529   int first_time;
11530   struct attribute *attr;
11531   unsigned int i;
11532   struct signatured_type *sig_type;
11533
11534   gdb_assert (per_cu->is_debug_types);
11535   sig_type = (struct signatured_type *) per_cu;
11536
11537   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11538
11539   /* If we're using .gdb_index (includes -readnow) then
11540      per_cu->type_unit_group may not have been set up yet.  */
11541   if (sig_type->type_unit_group == NULL)
11542     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11543   tu_group = sig_type->type_unit_group;
11544
11545   /* If we've already processed this stmt_list there's no real need to
11546      do it again, we could fake it and just recreate the part we need
11547      (file name,index -> symtab mapping).  If data shows this optimization
11548      is useful we can do it then.  */
11549   first_time = tu_group->compunit_symtab == NULL;
11550
11551   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11552      debug info.  */
11553   line_header_up lh;
11554   if (attr != NULL)
11555     {
11556       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11557       lh = dwarf_decode_line_header (line_offset, cu);
11558     }
11559   if (lh == NULL)
11560     {
11561       if (first_time)
11562         dwarf2_start_symtab (cu, "", NULL, 0);
11563       else
11564         {
11565           gdb_assert (tu_group->symtabs == NULL);
11566           restart_symtab (tu_group->compunit_symtab, "", 0);
11567         }
11568       return;
11569     }
11570
11571   cu->line_header = lh.release ();
11572   cu->line_header_die_owner = die;
11573
11574   if (first_time)
11575     {
11576       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11577
11578       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11579          still initializing it, and our caller (a few levels up)
11580          process_full_type_unit still needs to know if this is the first
11581          time.  */
11582
11583       tu_group->num_symtabs = cu->line_header->file_names.size ();
11584       tu_group->symtabs = XNEWVEC (struct symtab *,
11585                                    cu->line_header->file_names.size ());
11586
11587       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11588         {
11589           file_entry &fe = cu->line_header->file_names[i];
11590
11591           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11592
11593           if (current_subfile->symtab == NULL)
11594             {
11595               /* NOTE: start_subfile will recognize when it's been
11596                  passed a file it has already seen.  So we can't
11597                  assume there's a simple mapping from
11598                  cu->line_header->file_names to subfiles, plus
11599                  cu->line_header->file_names may contain dups.  */
11600               current_subfile->symtab
11601                 = allocate_symtab (cust, current_subfile->name);
11602             }
11603
11604           fe.symtab = current_subfile->symtab;
11605           tu_group->symtabs[i] = fe.symtab;
11606         }
11607     }
11608   else
11609     {
11610       restart_symtab (tu_group->compunit_symtab, "", 0);
11611
11612       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11613         {
11614           file_entry &fe = cu->line_header->file_names[i];
11615
11616           fe.symtab = tu_group->symtabs[i];
11617         }
11618     }
11619
11620   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11621      so they don't have a "real" (so to speak) symtab anyway.
11622      There is later code that will assign the main symtab to all symbols
11623      that don't have one.  We need to handle the case of a symbol with a
11624      missing symtab (DW_AT_decl_file) anyway.  */
11625 }
11626
11627 /* Process DW_TAG_type_unit.
11628    For TUs we want to skip the first top level sibling if it's not the
11629    actual type being defined by this TU.  In this case the first top
11630    level sibling is there to provide context only.  */
11631
11632 static void
11633 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11634 {
11635   struct die_info *child_die;
11636
11637   prepare_one_comp_unit (cu, die, language_minimal);
11638
11639   /* Initialize (or reinitialize) the machinery for building symtabs.
11640      We do this before processing child DIEs, so that the line header table
11641      is available for DW_AT_decl_file.  */
11642   setup_type_unit_groups (die, cu);
11643
11644   if (die->child != NULL)
11645     {
11646       child_die = die->child;
11647       while (child_die && child_die->tag)
11648         {
11649           process_die (child_die, cu);
11650           child_die = sibling_die (child_die);
11651         }
11652     }
11653 }
11654 \f
11655 /* DWO/DWP files.
11656
11657    http://gcc.gnu.org/wiki/DebugFission
11658    http://gcc.gnu.org/wiki/DebugFissionDWP
11659
11660    To simplify handling of both DWO files ("object" files with the DWARF info)
11661    and DWP files (a file with the DWOs packaged up into one file), we treat
11662    DWP files as having a collection of virtual DWO files.  */
11663
11664 static hashval_t
11665 hash_dwo_file (const void *item)
11666 {
11667   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11668   hashval_t hash;
11669
11670   hash = htab_hash_string (dwo_file->dwo_name);
11671   if (dwo_file->comp_dir != NULL)
11672     hash += htab_hash_string (dwo_file->comp_dir);
11673   return hash;
11674 }
11675
11676 static int
11677 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11678 {
11679   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11680   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11681
11682   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11683     return 0;
11684   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11685     return lhs->comp_dir == rhs->comp_dir;
11686   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11687 }
11688
11689 /* Allocate a hash table for DWO files.  */
11690
11691 static htab_t
11692 allocate_dwo_file_hash_table (struct objfile *objfile)
11693 {
11694   return htab_create_alloc_ex (41,
11695                                hash_dwo_file,
11696                                eq_dwo_file,
11697                                NULL,
11698                                &objfile->objfile_obstack,
11699                                hashtab_obstack_allocate,
11700                                dummy_obstack_deallocate);
11701 }
11702
11703 /* Lookup DWO file DWO_NAME.  */
11704
11705 static void **
11706 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11707                       const char *dwo_name,
11708                       const char *comp_dir)
11709 {
11710   struct dwo_file find_entry;
11711   void **slot;
11712
11713   if (dwarf2_per_objfile->dwo_files == NULL)
11714     dwarf2_per_objfile->dwo_files
11715       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11716
11717   memset (&find_entry, 0, sizeof (find_entry));
11718   find_entry.dwo_name = dwo_name;
11719   find_entry.comp_dir = comp_dir;
11720   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11721
11722   return slot;
11723 }
11724
11725 static hashval_t
11726 hash_dwo_unit (const void *item)
11727 {
11728   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11729
11730   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11731   return dwo_unit->signature;
11732 }
11733
11734 static int
11735 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11736 {
11737   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11738   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11739
11740   /* The signature is assumed to be unique within the DWO file.
11741      So while object file CU dwo_id's always have the value zero,
11742      that's OK, assuming each object file DWO file has only one CU,
11743      and that's the rule for now.  */
11744   return lhs->signature == rhs->signature;
11745 }
11746
11747 /* Allocate a hash table for DWO CUs,TUs.
11748    There is one of these tables for each of CUs,TUs for each DWO file.  */
11749
11750 static htab_t
11751 allocate_dwo_unit_table (struct objfile *objfile)
11752 {
11753   /* Start out with a pretty small number.
11754      Generally DWO files contain only one CU and maybe some TUs.  */
11755   return htab_create_alloc_ex (3,
11756                                hash_dwo_unit,
11757                                eq_dwo_unit,
11758                                NULL,
11759                                &objfile->objfile_obstack,
11760                                hashtab_obstack_allocate,
11761                                dummy_obstack_deallocate);
11762 }
11763
11764 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11765
11766 struct create_dwo_cu_data
11767 {
11768   struct dwo_file *dwo_file;
11769   struct dwo_unit dwo_unit;
11770 };
11771
11772 /* die_reader_func for create_dwo_cu.  */
11773
11774 static void
11775 create_dwo_cu_reader (const struct die_reader_specs *reader,
11776                       const gdb_byte *info_ptr,
11777                       struct die_info *comp_unit_die,
11778                       int has_children,
11779                       void *datap)
11780 {
11781   struct dwarf2_cu *cu = reader->cu;
11782   sect_offset sect_off = cu->per_cu->sect_off;
11783   struct dwarf2_section_info *section = cu->per_cu->section;
11784   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11785   struct dwo_file *dwo_file = data->dwo_file;
11786   struct dwo_unit *dwo_unit = &data->dwo_unit;
11787   struct attribute *attr;
11788
11789   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11790   if (attr == NULL)
11791     {
11792       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11793                    " its dwo_id [in module %s]"),
11794                  sect_offset_str (sect_off), dwo_file->dwo_name);
11795       return;
11796     }
11797
11798   dwo_unit->dwo_file = dwo_file;
11799   dwo_unit->signature = DW_UNSND (attr);
11800   dwo_unit->section = section;
11801   dwo_unit->sect_off = sect_off;
11802   dwo_unit->length = cu->per_cu->length;
11803
11804   if (dwarf_read_debug)
11805     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11806                         sect_offset_str (sect_off),
11807                         hex_string (dwo_unit->signature));
11808 }
11809
11810 /* Create the dwo_units for the CUs in a DWO_FILE.
11811    Note: This function processes DWO files only, not DWP files.  */
11812
11813 static void
11814 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11815                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11816                        htab_t &cus_htab)
11817 {
11818   struct objfile *objfile = dwarf2_per_objfile->objfile;
11819   const gdb_byte *info_ptr, *end_ptr;
11820
11821   dwarf2_read_section (objfile, &section);
11822   info_ptr = section.buffer;
11823
11824   if (info_ptr == NULL)
11825     return;
11826
11827   if (dwarf_read_debug)
11828     {
11829       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11830                           get_section_name (&section),
11831                           get_section_file_name (&section));
11832     }
11833
11834   end_ptr = info_ptr + section.size;
11835   while (info_ptr < end_ptr)
11836     {
11837       struct dwarf2_per_cu_data per_cu;
11838       struct create_dwo_cu_data create_dwo_cu_data;
11839       struct dwo_unit *dwo_unit;
11840       void **slot;
11841       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11842
11843       memset (&create_dwo_cu_data.dwo_unit, 0,
11844               sizeof (create_dwo_cu_data.dwo_unit));
11845       memset (&per_cu, 0, sizeof (per_cu));
11846       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11847       per_cu.is_debug_types = 0;
11848       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11849       per_cu.section = &section;
11850       create_dwo_cu_data.dwo_file = &dwo_file;
11851
11852       init_cutu_and_read_dies_no_follow (
11853           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11854       info_ptr += per_cu.length;
11855
11856       // If the unit could not be parsed, skip it.
11857       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11858         continue;
11859
11860       if (cus_htab == NULL)
11861         cus_htab = allocate_dwo_unit_table (objfile);
11862
11863       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11864       *dwo_unit = create_dwo_cu_data.dwo_unit;
11865       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11866       gdb_assert (slot != NULL);
11867       if (*slot != NULL)
11868         {
11869           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11870           sect_offset dup_sect_off = dup_cu->sect_off;
11871
11872           complaint (_("debug cu entry at offset %s is duplicate to"
11873                        " the entry at offset %s, signature %s"),
11874                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11875                      hex_string (dwo_unit->signature));
11876         }
11877       *slot = (void *)dwo_unit;
11878     }
11879 }
11880
11881 /* DWP file .debug_{cu,tu}_index section format:
11882    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11883
11884    DWP Version 1:
11885
11886    Both index sections have the same format, and serve to map a 64-bit
11887    signature to a set of section numbers.  Each section begins with a header,
11888    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11889    indexes, and a pool of 32-bit section numbers.  The index sections will be
11890    aligned at 8-byte boundaries in the file.
11891
11892    The index section header consists of:
11893
11894     V, 32 bit version number
11895     -, 32 bits unused
11896     N, 32 bit number of compilation units or type units in the index
11897     M, 32 bit number of slots in the hash table
11898
11899    Numbers are recorded using the byte order of the application binary.
11900
11901    The hash table begins at offset 16 in the section, and consists of an array
11902    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11903    order of the application binary).  Unused slots in the hash table are 0.
11904    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11905
11906    The parallel table begins immediately after the hash table
11907    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11908    array of 32-bit indexes (using the byte order of the application binary),
11909    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11910    table contains a 32-bit index into the pool of section numbers.  For unused
11911    hash table slots, the corresponding entry in the parallel table will be 0.
11912
11913    The pool of section numbers begins immediately following the hash table
11914    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11915    section numbers consists of an array of 32-bit words (using the byte order
11916    of the application binary).  Each item in the array is indexed starting
11917    from 0.  The hash table entry provides the index of the first section
11918    number in the set.  Additional section numbers in the set follow, and the
11919    set is terminated by a 0 entry (section number 0 is not used in ELF).
11920
11921    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11922    section must be the first entry in the set, and the .debug_abbrev.dwo must
11923    be the second entry. Other members of the set may follow in any order.
11924
11925    ---
11926
11927    DWP Version 2:
11928
11929    DWP Version 2 combines all the .debug_info, etc. sections into one,
11930    and the entries in the index tables are now offsets into these sections.
11931    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11932    section.
11933
11934    Index Section Contents:
11935     Header
11936     Hash Table of Signatures   dwp_hash_table.hash_table
11937     Parallel Table of Indices  dwp_hash_table.unit_table
11938     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11939     Table of Section Sizes     dwp_hash_table.v2.sizes
11940
11941    The index section header consists of:
11942
11943     V, 32 bit version number
11944     L, 32 bit number of columns in the table of section offsets
11945     N, 32 bit number of compilation units or type units in the index
11946     M, 32 bit number of slots in the hash table
11947
11948    Numbers are recorded using the byte order of the application binary.
11949
11950    The hash table has the same format as version 1.
11951    The parallel table of indices has the same format as version 1,
11952    except that the entries are origin-1 indices into the table of sections
11953    offsets and the table of section sizes.
11954
11955    The table of offsets begins immediately following the parallel table
11956    (at offset 16 + 12 * M from the beginning of the section).  The table is
11957    a two-dimensional array of 32-bit words (using the byte order of the
11958    application binary), with L columns and N+1 rows, in row-major order.
11959    Each row in the array is indexed starting from 0.  The first row provides
11960    a key to the remaining rows: each column in this row provides an identifier
11961    for a debug section, and the offsets in the same column of subsequent rows
11962    refer to that section.  The section identifiers are:
11963
11964     DW_SECT_INFO         1  .debug_info.dwo
11965     DW_SECT_TYPES        2  .debug_types.dwo
11966     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11967     DW_SECT_LINE         4  .debug_line.dwo
11968     DW_SECT_LOC          5  .debug_loc.dwo
11969     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11970     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11971     DW_SECT_MACRO        8  .debug_macro.dwo
11972
11973    The offsets provided by the CU and TU index sections are the base offsets
11974    for the contributions made by each CU or TU to the corresponding section
11975    in the package file.  Each CU and TU header contains an abbrev_offset
11976    field, used to find the abbreviations table for that CU or TU within the
11977    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11978    be interpreted as relative to the base offset given in the index section.
11979    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11980    should be interpreted as relative to the base offset for .debug_line.dwo,
11981    and offsets into other debug sections obtained from DWARF attributes should
11982    also be interpreted as relative to the corresponding base offset.
11983
11984    The table of sizes begins immediately following the table of offsets.
11985    Like the table of offsets, it is a two-dimensional array of 32-bit words,
11986    with L columns and N rows, in row-major order.  Each row in the array is
11987    indexed starting from 1 (row 0 is shared by the two tables).
11988
11989    ---
11990
11991    Hash table lookup is handled the same in version 1 and 2:
11992
11993    We assume that N and M will not exceed 2^32 - 1.
11994    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
11995
11996    Given a 64-bit compilation unit signature or a type signature S, an entry
11997    in the hash table is located as follows:
11998
11999    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12000       the low-order k bits all set to 1.
12001
12002    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12003
12004    3) If the hash table entry at index H matches the signature, use that
12005       entry.  If the hash table entry at index H is unused (all zeroes),
12006       terminate the search: the signature is not present in the table.
12007
12008    4) Let H = (H + H') modulo M. Repeat at Step 3.
12009
12010    Because M > N and H' and M are relatively prime, the search is guaranteed
12011    to stop at an unused slot or find the match.  */
12012
12013 /* Create a hash table to map DWO IDs to their CU/TU entry in
12014    .debug_{info,types}.dwo in DWP_FILE.
12015    Returns NULL if there isn't one.
12016    Note: This function processes DWP files only, not DWO files.  */
12017
12018 static struct dwp_hash_table *
12019 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12020                        struct dwp_file *dwp_file, int is_debug_types)
12021 {
12022   struct objfile *objfile = dwarf2_per_objfile->objfile;
12023   bfd *dbfd = dwp_file->dbfd.get ();
12024   const gdb_byte *index_ptr, *index_end;
12025   struct dwarf2_section_info *index;
12026   uint32_t version, nr_columns, nr_units, nr_slots;
12027   struct dwp_hash_table *htab;
12028
12029   if (is_debug_types)
12030     index = &dwp_file->sections.tu_index;
12031   else
12032     index = &dwp_file->sections.cu_index;
12033
12034   if (dwarf2_section_empty_p (index))
12035     return NULL;
12036   dwarf2_read_section (objfile, index);
12037
12038   index_ptr = index->buffer;
12039   index_end = index_ptr + index->size;
12040
12041   version = read_4_bytes (dbfd, index_ptr);
12042   index_ptr += 4;
12043   if (version == 2)
12044     nr_columns = read_4_bytes (dbfd, index_ptr);
12045   else
12046     nr_columns = 0;
12047   index_ptr += 4;
12048   nr_units = read_4_bytes (dbfd, index_ptr);
12049   index_ptr += 4;
12050   nr_slots = read_4_bytes (dbfd, index_ptr);
12051   index_ptr += 4;
12052
12053   if (version != 1 && version != 2)
12054     {
12055       error (_("Dwarf Error: unsupported DWP file version (%s)"
12056                " [in module %s]"),
12057              pulongest (version), dwp_file->name);
12058     }
12059   if (nr_slots != (nr_slots & -nr_slots))
12060     {
12061       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12062                " is not power of 2 [in module %s]"),
12063              pulongest (nr_slots), dwp_file->name);
12064     }
12065
12066   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12067   htab->version = version;
12068   htab->nr_columns = nr_columns;
12069   htab->nr_units = nr_units;
12070   htab->nr_slots = nr_slots;
12071   htab->hash_table = index_ptr;
12072   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12073
12074   /* Exit early if the table is empty.  */
12075   if (nr_slots == 0 || nr_units == 0
12076       || (version == 2 && nr_columns == 0))
12077     {
12078       /* All must be zero.  */
12079       if (nr_slots != 0 || nr_units != 0
12080           || (version == 2 && nr_columns != 0))
12081         {
12082           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12083                        " all zero [in modules %s]"),
12084                      dwp_file->name);
12085         }
12086       return htab;
12087     }
12088
12089   if (version == 1)
12090     {
12091       htab->section_pool.v1.indices =
12092         htab->unit_table + sizeof (uint32_t) * nr_slots;
12093       /* It's harder to decide whether the section is too small in v1.
12094          V1 is deprecated anyway so we punt.  */
12095     }
12096   else
12097     {
12098       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12099       int *ids = htab->section_pool.v2.section_ids;
12100       /* Reverse map for error checking.  */
12101       int ids_seen[DW_SECT_MAX + 1];
12102       int i;
12103
12104       if (nr_columns < 2)
12105         {
12106           error (_("Dwarf Error: bad DWP hash table, too few columns"
12107                    " in section table [in module %s]"),
12108                  dwp_file->name);
12109         }
12110       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12111         {
12112           error (_("Dwarf Error: bad DWP hash table, too many columns"
12113                    " in section table [in module %s]"),
12114                  dwp_file->name);
12115         }
12116       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12117       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12118       for (i = 0; i < nr_columns; ++i)
12119         {
12120           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12121
12122           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12123             {
12124               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12125                        " in section table [in module %s]"),
12126                      id, dwp_file->name);
12127             }
12128           if (ids_seen[id] != -1)
12129             {
12130               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12131                        " id %d in section table [in module %s]"),
12132                      id, dwp_file->name);
12133             }
12134           ids_seen[id] = i;
12135           ids[i] = id;
12136         }
12137       /* Must have exactly one info or types section.  */
12138       if (((ids_seen[DW_SECT_INFO] != -1)
12139            + (ids_seen[DW_SECT_TYPES] != -1))
12140           != 1)
12141         {
12142           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12143                    " DWO info/types section [in module %s]"),
12144                  dwp_file->name);
12145         }
12146       /* Must have an abbrev section.  */
12147       if (ids_seen[DW_SECT_ABBREV] == -1)
12148         {
12149           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12150                    " section [in module %s]"),
12151                  dwp_file->name);
12152         }
12153       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12154       htab->section_pool.v2.sizes =
12155         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12156                                          * nr_units * nr_columns);
12157       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12158                                           * nr_units * nr_columns))
12159           > index_end)
12160         {
12161           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12162                    " [in module %s]"),
12163                  dwp_file->name);
12164         }
12165     }
12166
12167   return htab;
12168 }
12169
12170 /* Update SECTIONS with the data from SECTP.
12171
12172    This function is like the other "locate" section routines that are
12173    passed to bfd_map_over_sections, but in this context the sections to
12174    read comes from the DWP V1 hash table, not the full ELF section table.
12175
12176    The result is non-zero for success, or zero if an error was found.  */
12177
12178 static int
12179 locate_v1_virtual_dwo_sections (asection *sectp,
12180                                 struct virtual_v1_dwo_sections *sections)
12181 {
12182   const struct dwop_section_names *names = &dwop_section_names;
12183
12184   if (section_is_p (sectp->name, &names->abbrev_dwo))
12185     {
12186       /* There can be only one.  */
12187       if (sections->abbrev.s.section != NULL)
12188         return 0;
12189       sections->abbrev.s.section = sectp;
12190       sections->abbrev.size = bfd_get_section_size (sectp);
12191     }
12192   else if (section_is_p (sectp->name, &names->info_dwo)
12193            || section_is_p (sectp->name, &names->types_dwo))
12194     {
12195       /* There can be only one.  */
12196       if (sections->info_or_types.s.section != NULL)
12197         return 0;
12198       sections->info_or_types.s.section = sectp;
12199       sections->info_or_types.size = bfd_get_section_size (sectp);
12200     }
12201   else if (section_is_p (sectp->name, &names->line_dwo))
12202     {
12203       /* There can be only one.  */
12204       if (sections->line.s.section != NULL)
12205         return 0;
12206       sections->line.s.section = sectp;
12207       sections->line.size = bfd_get_section_size (sectp);
12208     }
12209   else if (section_is_p (sectp->name, &names->loc_dwo))
12210     {
12211       /* There can be only one.  */
12212       if (sections->loc.s.section != NULL)
12213         return 0;
12214       sections->loc.s.section = sectp;
12215       sections->loc.size = bfd_get_section_size (sectp);
12216     }
12217   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12218     {
12219       /* There can be only one.  */
12220       if (sections->macinfo.s.section != NULL)
12221         return 0;
12222       sections->macinfo.s.section = sectp;
12223       sections->macinfo.size = bfd_get_section_size (sectp);
12224     }
12225   else if (section_is_p (sectp->name, &names->macro_dwo))
12226     {
12227       /* There can be only one.  */
12228       if (sections->macro.s.section != NULL)
12229         return 0;
12230       sections->macro.s.section = sectp;
12231       sections->macro.size = bfd_get_section_size (sectp);
12232     }
12233   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12234     {
12235       /* There can be only one.  */
12236       if (sections->str_offsets.s.section != NULL)
12237         return 0;
12238       sections->str_offsets.s.section = sectp;
12239       sections->str_offsets.size = bfd_get_section_size (sectp);
12240     }
12241   else
12242     {
12243       /* No other kind of section is valid.  */
12244       return 0;
12245     }
12246
12247   return 1;
12248 }
12249
12250 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12251    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12252    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12253    This is for DWP version 1 files.  */
12254
12255 static struct dwo_unit *
12256 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12257                            struct dwp_file *dwp_file,
12258                            uint32_t unit_index,
12259                            const char *comp_dir,
12260                            ULONGEST signature, int is_debug_types)
12261 {
12262   struct objfile *objfile = dwarf2_per_objfile->objfile;
12263   const struct dwp_hash_table *dwp_htab =
12264     is_debug_types ? dwp_file->tus : dwp_file->cus;
12265   bfd *dbfd = dwp_file->dbfd.get ();
12266   const char *kind = is_debug_types ? "TU" : "CU";
12267   struct dwo_file *dwo_file;
12268   struct dwo_unit *dwo_unit;
12269   struct virtual_v1_dwo_sections sections;
12270   void **dwo_file_slot;
12271   int i;
12272
12273   gdb_assert (dwp_file->version == 1);
12274
12275   if (dwarf_read_debug)
12276     {
12277       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12278                           kind,
12279                           pulongest (unit_index), hex_string (signature),
12280                           dwp_file->name);
12281     }
12282
12283   /* Fetch the sections of this DWO unit.
12284      Put a limit on the number of sections we look for so that bad data
12285      doesn't cause us to loop forever.  */
12286
12287 #define MAX_NR_V1_DWO_SECTIONS \
12288   (1 /* .debug_info or .debug_types */ \
12289    + 1 /* .debug_abbrev */ \
12290    + 1 /* .debug_line */ \
12291    + 1 /* .debug_loc */ \
12292    + 1 /* .debug_str_offsets */ \
12293    + 1 /* .debug_macro or .debug_macinfo */ \
12294    + 1 /* trailing zero */)
12295
12296   memset (&sections, 0, sizeof (sections));
12297
12298   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12299     {
12300       asection *sectp;
12301       uint32_t section_nr =
12302         read_4_bytes (dbfd,
12303                       dwp_htab->section_pool.v1.indices
12304                       + (unit_index + i) * sizeof (uint32_t));
12305
12306       if (section_nr == 0)
12307         break;
12308       if (section_nr >= dwp_file->num_sections)
12309         {
12310           error (_("Dwarf Error: bad DWP hash table, section number too large"
12311                    " [in module %s]"),
12312                  dwp_file->name);
12313         }
12314
12315       sectp = dwp_file->elf_sections[section_nr];
12316       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12317         {
12318           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12319                    " [in module %s]"),
12320                  dwp_file->name);
12321         }
12322     }
12323
12324   if (i < 2
12325       || dwarf2_section_empty_p (&sections.info_or_types)
12326       || dwarf2_section_empty_p (&sections.abbrev))
12327     {
12328       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12329                " [in module %s]"),
12330              dwp_file->name);
12331     }
12332   if (i == MAX_NR_V1_DWO_SECTIONS)
12333     {
12334       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12335                " [in module %s]"),
12336              dwp_file->name);
12337     }
12338
12339   /* It's easier for the rest of the code if we fake a struct dwo_file and
12340      have dwo_unit "live" in that.  At least for now.
12341
12342      The DWP file can be made up of a random collection of CUs and TUs.
12343      However, for each CU + set of TUs that came from the same original DWO
12344      file, we can combine them back into a virtual DWO file to save space
12345      (fewer struct dwo_file objects to allocate).  Remember that for really
12346      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12347
12348   std::string virtual_dwo_name =
12349     string_printf ("virtual-dwo/%d-%d-%d-%d",
12350                    get_section_id (&sections.abbrev),
12351                    get_section_id (&sections.line),
12352                    get_section_id (&sections.loc),
12353                    get_section_id (&sections.str_offsets));
12354   /* Can we use an existing virtual DWO file?  */
12355   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12356                                         virtual_dwo_name.c_str (),
12357                                         comp_dir);
12358   /* Create one if necessary.  */
12359   if (*dwo_file_slot == NULL)
12360     {
12361       if (dwarf_read_debug)
12362         {
12363           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12364                               virtual_dwo_name.c_str ());
12365         }
12366       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12367       dwo_file->dwo_name
12368         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12369                                         virtual_dwo_name.c_str (),
12370                                         virtual_dwo_name.size ());
12371       dwo_file->comp_dir = comp_dir;
12372       dwo_file->sections.abbrev = sections.abbrev;
12373       dwo_file->sections.line = sections.line;
12374       dwo_file->sections.loc = sections.loc;
12375       dwo_file->sections.macinfo = sections.macinfo;
12376       dwo_file->sections.macro = sections.macro;
12377       dwo_file->sections.str_offsets = sections.str_offsets;
12378       /* The "str" section is global to the entire DWP file.  */
12379       dwo_file->sections.str = dwp_file->sections.str;
12380       /* The info or types section is assigned below to dwo_unit,
12381          there's no need to record it in dwo_file.
12382          Also, we can't simply record type sections in dwo_file because
12383          we record a pointer into the vector in dwo_unit.  As we collect more
12384          types we'll grow the vector and eventually have to reallocate space
12385          for it, invalidating all copies of pointers into the previous
12386          contents.  */
12387       *dwo_file_slot = dwo_file;
12388     }
12389   else
12390     {
12391       if (dwarf_read_debug)
12392         {
12393           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12394                               virtual_dwo_name.c_str ());
12395         }
12396       dwo_file = (struct dwo_file *) *dwo_file_slot;
12397     }
12398
12399   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12400   dwo_unit->dwo_file = dwo_file;
12401   dwo_unit->signature = signature;
12402   dwo_unit->section =
12403     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12404   *dwo_unit->section = sections.info_or_types;
12405   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12406
12407   return dwo_unit;
12408 }
12409
12410 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12411    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12412    piece within that section used by a TU/CU, return a virtual section
12413    of just that piece.  */
12414
12415 static struct dwarf2_section_info
12416 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12417                        struct dwarf2_section_info *section,
12418                        bfd_size_type offset, bfd_size_type size)
12419 {
12420   struct dwarf2_section_info result;
12421   asection *sectp;
12422
12423   gdb_assert (section != NULL);
12424   gdb_assert (!section->is_virtual);
12425
12426   memset (&result, 0, sizeof (result));
12427   result.s.containing_section = section;
12428   result.is_virtual = 1;
12429
12430   if (size == 0)
12431     return result;
12432
12433   sectp = get_section_bfd_section (section);
12434
12435   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12436      bounds of the real section.  This is a pretty-rare event, so just
12437      flag an error (easier) instead of a warning and trying to cope.  */
12438   if (sectp == NULL
12439       || offset + size > bfd_get_section_size (sectp))
12440     {
12441       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12442                " in section %s [in module %s]"),
12443              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12444              objfile_name (dwarf2_per_objfile->objfile));
12445     }
12446
12447   result.virtual_offset = offset;
12448   result.size = size;
12449   return result;
12450 }
12451
12452 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12453    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12454    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12455    This is for DWP version 2 files.  */
12456
12457 static struct dwo_unit *
12458 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12459                            struct dwp_file *dwp_file,
12460                            uint32_t unit_index,
12461                            const char *comp_dir,
12462                            ULONGEST signature, int is_debug_types)
12463 {
12464   struct objfile *objfile = dwarf2_per_objfile->objfile;
12465   const struct dwp_hash_table *dwp_htab =
12466     is_debug_types ? dwp_file->tus : dwp_file->cus;
12467   bfd *dbfd = dwp_file->dbfd.get ();
12468   const char *kind = is_debug_types ? "TU" : "CU";
12469   struct dwo_file *dwo_file;
12470   struct dwo_unit *dwo_unit;
12471   struct virtual_v2_dwo_sections sections;
12472   void **dwo_file_slot;
12473   int i;
12474
12475   gdb_assert (dwp_file->version == 2);
12476
12477   if (dwarf_read_debug)
12478     {
12479       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12480                           kind,
12481                           pulongest (unit_index), hex_string (signature),
12482                           dwp_file->name);
12483     }
12484
12485   /* Fetch the section offsets of this DWO unit.  */
12486
12487   memset (&sections, 0, sizeof (sections));
12488
12489   for (i = 0; i < dwp_htab->nr_columns; ++i)
12490     {
12491       uint32_t offset = read_4_bytes (dbfd,
12492                                       dwp_htab->section_pool.v2.offsets
12493                                       + (((unit_index - 1) * dwp_htab->nr_columns
12494                                           + i)
12495                                          * sizeof (uint32_t)));
12496       uint32_t size = read_4_bytes (dbfd,
12497                                     dwp_htab->section_pool.v2.sizes
12498                                     + (((unit_index - 1) * dwp_htab->nr_columns
12499                                         + i)
12500                                        * sizeof (uint32_t)));
12501
12502       switch (dwp_htab->section_pool.v2.section_ids[i])
12503         {
12504         case DW_SECT_INFO:
12505         case DW_SECT_TYPES:
12506           sections.info_or_types_offset = offset;
12507           sections.info_or_types_size = size;
12508           break;
12509         case DW_SECT_ABBREV:
12510           sections.abbrev_offset = offset;
12511           sections.abbrev_size = size;
12512           break;
12513         case DW_SECT_LINE:
12514           sections.line_offset = offset;
12515           sections.line_size = size;
12516           break;
12517         case DW_SECT_LOC:
12518           sections.loc_offset = offset;
12519           sections.loc_size = size;
12520           break;
12521         case DW_SECT_STR_OFFSETS:
12522           sections.str_offsets_offset = offset;
12523           sections.str_offsets_size = size;
12524           break;
12525         case DW_SECT_MACINFO:
12526           sections.macinfo_offset = offset;
12527           sections.macinfo_size = size;
12528           break;
12529         case DW_SECT_MACRO:
12530           sections.macro_offset = offset;
12531           sections.macro_size = size;
12532           break;
12533         }
12534     }
12535
12536   /* It's easier for the rest of the code if we fake a struct dwo_file and
12537      have dwo_unit "live" in that.  At least for now.
12538
12539      The DWP file can be made up of a random collection of CUs and TUs.
12540      However, for each CU + set of TUs that came from the same original DWO
12541      file, we can combine them back into a virtual DWO file to save space
12542      (fewer struct dwo_file objects to allocate).  Remember that for really
12543      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12544
12545   std::string virtual_dwo_name =
12546     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12547                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12548                    (long) (sections.line_size ? sections.line_offset : 0),
12549                    (long) (sections.loc_size ? sections.loc_offset : 0),
12550                    (long) (sections.str_offsets_size
12551                            ? sections.str_offsets_offset : 0));
12552   /* Can we use an existing virtual DWO file?  */
12553   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12554                                         virtual_dwo_name.c_str (),
12555                                         comp_dir);
12556   /* Create one if necessary.  */
12557   if (*dwo_file_slot == NULL)
12558     {
12559       if (dwarf_read_debug)
12560         {
12561           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12562                               virtual_dwo_name.c_str ());
12563         }
12564       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12565       dwo_file->dwo_name
12566         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12567                                         virtual_dwo_name.c_str (),
12568                                         virtual_dwo_name.size ());
12569       dwo_file->comp_dir = comp_dir;
12570       dwo_file->sections.abbrev =
12571         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12572                                sections.abbrev_offset, sections.abbrev_size);
12573       dwo_file->sections.line =
12574         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12575                                sections.line_offset, sections.line_size);
12576       dwo_file->sections.loc =
12577         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12578                                sections.loc_offset, sections.loc_size);
12579       dwo_file->sections.macinfo =
12580         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12581                                sections.macinfo_offset, sections.macinfo_size);
12582       dwo_file->sections.macro =
12583         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12584                                sections.macro_offset, sections.macro_size);
12585       dwo_file->sections.str_offsets =
12586         create_dwp_v2_section (dwarf2_per_objfile,
12587                                &dwp_file->sections.str_offsets,
12588                                sections.str_offsets_offset,
12589                                sections.str_offsets_size);
12590       /* The "str" section is global to the entire DWP file.  */
12591       dwo_file->sections.str = dwp_file->sections.str;
12592       /* The info or types section is assigned below to dwo_unit,
12593          there's no need to record it in dwo_file.
12594          Also, we can't simply record type sections in dwo_file because
12595          we record a pointer into the vector in dwo_unit.  As we collect more
12596          types we'll grow the vector and eventually have to reallocate space
12597          for it, invalidating all copies of pointers into the previous
12598          contents.  */
12599       *dwo_file_slot = dwo_file;
12600     }
12601   else
12602     {
12603       if (dwarf_read_debug)
12604         {
12605           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12606                               virtual_dwo_name.c_str ());
12607         }
12608       dwo_file = (struct dwo_file *) *dwo_file_slot;
12609     }
12610
12611   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12612   dwo_unit->dwo_file = dwo_file;
12613   dwo_unit->signature = signature;
12614   dwo_unit->section =
12615     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12616   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12617                                               is_debug_types
12618                                               ? &dwp_file->sections.types
12619                                               : &dwp_file->sections.info,
12620                                               sections.info_or_types_offset,
12621                                               sections.info_or_types_size);
12622   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12623
12624   return dwo_unit;
12625 }
12626
12627 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12628    Returns NULL if the signature isn't found.  */
12629
12630 static struct dwo_unit *
12631 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12632                         struct dwp_file *dwp_file, const char *comp_dir,
12633                         ULONGEST signature, int is_debug_types)
12634 {
12635   const struct dwp_hash_table *dwp_htab =
12636     is_debug_types ? dwp_file->tus : dwp_file->cus;
12637   bfd *dbfd = dwp_file->dbfd.get ();
12638   uint32_t mask = dwp_htab->nr_slots - 1;
12639   uint32_t hash = signature & mask;
12640   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12641   unsigned int i;
12642   void **slot;
12643   struct dwo_unit find_dwo_cu;
12644
12645   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12646   find_dwo_cu.signature = signature;
12647   slot = htab_find_slot (is_debug_types
12648                          ? dwp_file->loaded_tus
12649                          : dwp_file->loaded_cus,
12650                          &find_dwo_cu, INSERT);
12651
12652   if (*slot != NULL)
12653     return (struct dwo_unit *) *slot;
12654
12655   /* Use a for loop so that we don't loop forever on bad debug info.  */
12656   for (i = 0; i < dwp_htab->nr_slots; ++i)
12657     {
12658       ULONGEST signature_in_table;
12659
12660       signature_in_table =
12661         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12662       if (signature_in_table == signature)
12663         {
12664           uint32_t unit_index =
12665             read_4_bytes (dbfd,
12666                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12667
12668           if (dwp_file->version == 1)
12669             {
12670               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12671                                                  dwp_file, unit_index,
12672                                                  comp_dir, signature,
12673                                                  is_debug_types);
12674             }
12675           else
12676             {
12677               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12678                                                  dwp_file, unit_index,
12679                                                  comp_dir, signature,
12680                                                  is_debug_types);
12681             }
12682           return (struct dwo_unit *) *slot;
12683         }
12684       if (signature_in_table == 0)
12685         return NULL;
12686       hash = (hash + hash2) & mask;
12687     }
12688
12689   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12690            " [in module %s]"),
12691          dwp_file->name);
12692 }
12693
12694 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12695    Open the file specified by FILE_NAME and hand it off to BFD for
12696    preliminary analysis.  Return a newly initialized bfd *, which
12697    includes a canonicalized copy of FILE_NAME.
12698    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12699    SEARCH_CWD is true if the current directory is to be searched.
12700    It will be searched before debug-file-directory.
12701    If successful, the file is added to the bfd include table of the
12702    objfile's bfd (see gdb_bfd_record_inclusion).
12703    If unable to find/open the file, return NULL.
12704    NOTE: This function is derived from symfile_bfd_open.  */
12705
12706 static gdb_bfd_ref_ptr
12707 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12708                     const char *file_name, int is_dwp, int search_cwd)
12709 {
12710   int desc;
12711   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12712      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12713      to debug_file_directory.  */
12714   const char *search_path;
12715   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12716
12717   gdb::unique_xmalloc_ptr<char> search_path_holder;
12718   if (search_cwd)
12719     {
12720       if (*debug_file_directory != '\0')
12721         {
12722           search_path_holder.reset (concat (".", dirname_separator_string,
12723                                             debug_file_directory,
12724                                             (char *) NULL));
12725           search_path = search_path_holder.get ();
12726         }
12727       else
12728         search_path = ".";
12729     }
12730   else
12731     search_path = debug_file_directory;
12732
12733   openp_flags flags = OPF_RETURN_REALPATH;
12734   if (is_dwp)
12735     flags |= OPF_SEARCH_IN_PATH;
12736
12737   gdb::unique_xmalloc_ptr<char> absolute_name;
12738   desc = openp (search_path, flags, file_name,
12739                 O_RDONLY | O_BINARY, &absolute_name);
12740   if (desc < 0)
12741     return NULL;
12742
12743   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12744                                          gnutarget, desc));
12745   if (sym_bfd == NULL)
12746     return NULL;
12747   bfd_set_cacheable (sym_bfd.get (), 1);
12748
12749   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12750     return NULL;
12751
12752   /* Success.  Record the bfd as having been included by the objfile's bfd.
12753      This is important because things like demangled_names_hash lives in the
12754      objfile's per_bfd space and may have references to things like symbol
12755      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12756   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12757
12758   return sym_bfd;
12759 }
12760
12761 /* Try to open DWO file FILE_NAME.
12762    COMP_DIR is the DW_AT_comp_dir attribute.
12763    The result is the bfd handle of the file.
12764    If there is a problem finding or opening the file, return NULL.
12765    Upon success, the canonicalized path of the file is stored in the bfd,
12766    same as symfile_bfd_open.  */
12767
12768 static gdb_bfd_ref_ptr
12769 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12770                const char *file_name, const char *comp_dir)
12771 {
12772   if (IS_ABSOLUTE_PATH (file_name))
12773     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12774                                0 /*is_dwp*/, 0 /*search_cwd*/);
12775
12776   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12777
12778   if (comp_dir != NULL)
12779     {
12780       char *path_to_try = concat (comp_dir, SLASH_STRING,
12781                                   file_name, (char *) NULL);
12782
12783       /* NOTE: If comp_dir is a relative path, this will also try the
12784          search path, which seems useful.  */
12785       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12786                                                 path_to_try,
12787                                                 0 /*is_dwp*/,
12788                                                 1 /*search_cwd*/));
12789       xfree (path_to_try);
12790       if (abfd != NULL)
12791         return abfd;
12792     }
12793
12794   /* That didn't work, try debug-file-directory, which, despite its name,
12795      is a list of paths.  */
12796
12797   if (*debug_file_directory == '\0')
12798     return NULL;
12799
12800   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12801                              0 /*is_dwp*/, 1 /*search_cwd*/);
12802 }
12803
12804 /* This function is mapped across the sections and remembers the offset and
12805    size of each of the DWO debugging sections we are interested in.  */
12806
12807 static void
12808 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12809 {
12810   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12811   const struct dwop_section_names *names = &dwop_section_names;
12812
12813   if (section_is_p (sectp->name, &names->abbrev_dwo))
12814     {
12815       dwo_sections->abbrev.s.section = sectp;
12816       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12817     }
12818   else if (section_is_p (sectp->name, &names->info_dwo))
12819     {
12820       dwo_sections->info.s.section = sectp;
12821       dwo_sections->info.size = bfd_get_section_size (sectp);
12822     }
12823   else if (section_is_p (sectp->name, &names->line_dwo))
12824     {
12825       dwo_sections->line.s.section = sectp;
12826       dwo_sections->line.size = bfd_get_section_size (sectp);
12827     }
12828   else if (section_is_p (sectp->name, &names->loc_dwo))
12829     {
12830       dwo_sections->loc.s.section = sectp;
12831       dwo_sections->loc.size = bfd_get_section_size (sectp);
12832     }
12833   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12834     {
12835       dwo_sections->macinfo.s.section = sectp;
12836       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12837     }
12838   else if (section_is_p (sectp->name, &names->macro_dwo))
12839     {
12840       dwo_sections->macro.s.section = sectp;
12841       dwo_sections->macro.size = bfd_get_section_size (sectp);
12842     }
12843   else if (section_is_p (sectp->name, &names->str_dwo))
12844     {
12845       dwo_sections->str.s.section = sectp;
12846       dwo_sections->str.size = bfd_get_section_size (sectp);
12847     }
12848   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12849     {
12850       dwo_sections->str_offsets.s.section = sectp;
12851       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12852     }
12853   else if (section_is_p (sectp->name, &names->types_dwo))
12854     {
12855       struct dwarf2_section_info type_section;
12856
12857       memset (&type_section, 0, sizeof (type_section));
12858       type_section.s.section = sectp;
12859       type_section.size = bfd_get_section_size (sectp);
12860       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12861                      &type_section);
12862     }
12863 }
12864
12865 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12866    by PER_CU.  This is for the non-DWP case.
12867    The result is NULL if DWO_NAME can't be found.  */
12868
12869 static struct dwo_file *
12870 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12871                         const char *dwo_name, const char *comp_dir)
12872 {
12873   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12874   struct objfile *objfile = dwarf2_per_objfile->objfile;
12875
12876   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12877   if (dbfd == NULL)
12878     {
12879       if (dwarf_read_debug)
12880         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12881       return NULL;
12882     }
12883
12884   /* We use a unique pointer here, despite the obstack allocation,
12885      because a dwo_file needs some cleanup if it is abandoned.  */
12886   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12887                                         struct dwo_file));
12888   dwo_file->dwo_name = dwo_name;
12889   dwo_file->comp_dir = comp_dir;
12890   dwo_file->dbfd = dbfd.release ();
12891
12892   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12893                          &dwo_file->sections);
12894
12895   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12896                          dwo_file->cus);
12897
12898   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12899                                  dwo_file->sections.types, dwo_file->tus);
12900
12901   if (dwarf_read_debug)
12902     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12903
12904   return dwo_file.release ();
12905 }
12906
12907 /* This function is mapped across the sections and remembers the offset and
12908    size of each of the DWP debugging sections common to version 1 and 2 that
12909    we are interested in.  */
12910
12911 static void
12912 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12913                                    void *dwp_file_ptr)
12914 {
12915   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12916   const struct dwop_section_names *names = &dwop_section_names;
12917   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12918
12919   /* Record the ELF section number for later lookup: this is what the
12920      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12921   gdb_assert (elf_section_nr < dwp_file->num_sections);
12922   dwp_file->elf_sections[elf_section_nr] = sectp;
12923
12924   /* Look for specific sections that we need.  */
12925   if (section_is_p (sectp->name, &names->str_dwo))
12926     {
12927       dwp_file->sections.str.s.section = sectp;
12928       dwp_file->sections.str.size = bfd_get_section_size (sectp);
12929     }
12930   else if (section_is_p (sectp->name, &names->cu_index))
12931     {
12932       dwp_file->sections.cu_index.s.section = sectp;
12933       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
12934     }
12935   else if (section_is_p (sectp->name, &names->tu_index))
12936     {
12937       dwp_file->sections.tu_index.s.section = sectp;
12938       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
12939     }
12940 }
12941
12942 /* This function is mapped across the sections and remembers the offset and
12943    size of each of the DWP version 2 debugging sections that we are interested
12944    in.  This is split into a separate function because we don't know if we
12945    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12946
12947 static void
12948 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12949 {
12950   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12951   const struct dwop_section_names *names = &dwop_section_names;
12952   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12953
12954   /* Record the ELF section number for later lookup: this is what the
12955      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12956   gdb_assert (elf_section_nr < dwp_file->num_sections);
12957   dwp_file->elf_sections[elf_section_nr] = sectp;
12958
12959   /* Look for specific sections that we need.  */
12960   if (section_is_p (sectp->name, &names->abbrev_dwo))
12961     {
12962       dwp_file->sections.abbrev.s.section = sectp;
12963       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
12964     }
12965   else if (section_is_p (sectp->name, &names->info_dwo))
12966     {
12967       dwp_file->sections.info.s.section = sectp;
12968       dwp_file->sections.info.size = bfd_get_section_size (sectp);
12969     }
12970   else if (section_is_p (sectp->name, &names->line_dwo))
12971     {
12972       dwp_file->sections.line.s.section = sectp;
12973       dwp_file->sections.line.size = bfd_get_section_size (sectp);
12974     }
12975   else if (section_is_p (sectp->name, &names->loc_dwo))
12976     {
12977       dwp_file->sections.loc.s.section = sectp;
12978       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
12979     }
12980   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12981     {
12982       dwp_file->sections.macinfo.s.section = sectp;
12983       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
12984     }
12985   else if (section_is_p (sectp->name, &names->macro_dwo))
12986     {
12987       dwp_file->sections.macro.s.section = sectp;
12988       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
12989     }
12990   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12991     {
12992       dwp_file->sections.str_offsets.s.section = sectp;
12993       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
12994     }
12995   else if (section_is_p (sectp->name, &names->types_dwo))
12996     {
12997       dwp_file->sections.types.s.section = sectp;
12998       dwp_file->sections.types.size = bfd_get_section_size (sectp);
12999     }
13000 }
13001
13002 /* Hash function for dwp_file loaded CUs/TUs.  */
13003
13004 static hashval_t
13005 hash_dwp_loaded_cutus (const void *item)
13006 {
13007   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13008
13009   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13010   return dwo_unit->signature;
13011 }
13012
13013 /* Equality function for dwp_file loaded CUs/TUs.  */
13014
13015 static int
13016 eq_dwp_loaded_cutus (const void *a, const void *b)
13017 {
13018   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13019   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13020
13021   return dua->signature == dub->signature;
13022 }
13023
13024 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13025
13026 static htab_t
13027 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13028 {
13029   return htab_create_alloc_ex (3,
13030                                hash_dwp_loaded_cutus,
13031                                eq_dwp_loaded_cutus,
13032                                NULL,
13033                                &objfile->objfile_obstack,
13034                                hashtab_obstack_allocate,
13035                                dummy_obstack_deallocate);
13036 }
13037
13038 /* Try to open DWP file FILE_NAME.
13039    The result is the bfd handle of the file.
13040    If there is a problem finding or opening the file, return NULL.
13041    Upon success, the canonicalized path of the file is stored in the bfd,
13042    same as symfile_bfd_open.  */
13043
13044 static gdb_bfd_ref_ptr
13045 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13046                const char *file_name)
13047 {
13048   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13049                                             1 /*is_dwp*/,
13050                                             1 /*search_cwd*/));
13051   if (abfd != NULL)
13052     return abfd;
13053
13054   /* Work around upstream bug 15652.
13055      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13056      [Whether that's a "bug" is debatable, but it is getting in our way.]
13057      We have no real idea where the dwp file is, because gdb's realpath-ing
13058      of the executable's path may have discarded the needed info.
13059      [IWBN if the dwp file name was recorded in the executable, akin to
13060      .gnu_debuglink, but that doesn't exist yet.]
13061      Strip the directory from FILE_NAME and search again.  */
13062   if (*debug_file_directory != '\0')
13063     {
13064       /* Don't implicitly search the current directory here.
13065          If the user wants to search "." to handle this case,
13066          it must be added to debug-file-directory.  */
13067       return try_open_dwop_file (dwarf2_per_objfile,
13068                                  lbasename (file_name), 1 /*is_dwp*/,
13069                                  0 /*search_cwd*/);
13070     }
13071
13072   return NULL;
13073 }
13074
13075 /* Initialize the use of the DWP file for the current objfile.
13076    By convention the name of the DWP file is ${objfile}.dwp.
13077    The result is NULL if it can't be found.  */
13078
13079 static std::unique_ptr<struct dwp_file>
13080 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13081 {
13082   struct objfile *objfile = dwarf2_per_objfile->objfile;
13083
13084   /* Try to find first .dwp for the binary file before any symbolic links
13085      resolving.  */
13086
13087   /* If the objfile is a debug file, find the name of the real binary
13088      file and get the name of dwp file from there.  */
13089   std::string dwp_name;
13090   if (objfile->separate_debug_objfile_backlink != NULL)
13091     {
13092       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13093       const char *backlink_basename = lbasename (backlink->original_name);
13094
13095       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13096     }
13097   else
13098     dwp_name = objfile->original_name;
13099
13100   dwp_name += ".dwp";
13101
13102   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13103   if (dbfd == NULL
13104       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13105     {
13106       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13107       dwp_name = objfile_name (objfile);
13108       dwp_name += ".dwp";
13109       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13110     }
13111
13112   if (dbfd == NULL)
13113     {
13114       if (dwarf_read_debug)
13115         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13116       return std::unique_ptr<dwp_file> ();
13117     }
13118
13119   const char *name = bfd_get_filename (dbfd.get ());
13120   std::unique_ptr<struct dwp_file> dwp_file
13121     (new struct dwp_file (name, std::move (dbfd)));
13122
13123   /* +1: section 0 is unused */
13124   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13125   dwp_file->elf_sections =
13126     OBSTACK_CALLOC (&objfile->objfile_obstack,
13127                     dwp_file->num_sections, asection *);
13128
13129   bfd_map_over_sections (dwp_file->dbfd.get (),
13130                          dwarf2_locate_common_dwp_sections,
13131                          dwp_file.get ());
13132
13133   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13134                                          0);
13135
13136   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13137                                          1);
13138
13139   /* The DWP file version is stored in the hash table.  Oh well.  */
13140   if (dwp_file->cus && dwp_file->tus
13141       && dwp_file->cus->version != dwp_file->tus->version)
13142     {
13143       /* Technically speaking, we should try to limp along, but this is
13144          pretty bizarre.  We use pulongest here because that's the established
13145          portability solution (e.g, we cannot use %u for uint32_t).  */
13146       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13147                " TU version %s [in DWP file %s]"),
13148              pulongest (dwp_file->cus->version),
13149              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13150     }
13151
13152   if (dwp_file->cus)
13153     dwp_file->version = dwp_file->cus->version;
13154   else if (dwp_file->tus)
13155     dwp_file->version = dwp_file->tus->version;
13156   else
13157     dwp_file->version = 2;
13158
13159   if (dwp_file->version == 2)
13160     bfd_map_over_sections (dwp_file->dbfd.get (),
13161                            dwarf2_locate_v2_dwp_sections,
13162                            dwp_file.get ());
13163
13164   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13165   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13166
13167   if (dwarf_read_debug)
13168     {
13169       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13170       fprintf_unfiltered (gdb_stdlog,
13171                           "    %s CUs, %s TUs\n",
13172                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13173                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13174     }
13175
13176   return dwp_file;
13177 }
13178
13179 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13180
13181 static struct dwp_file *
13182 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13183 {
13184   if (! dwarf2_per_objfile->dwp_checked)
13185     {
13186       dwarf2_per_objfile->dwp_file
13187         = open_and_init_dwp_file (dwarf2_per_objfile);
13188       dwarf2_per_objfile->dwp_checked = 1;
13189     }
13190   return dwarf2_per_objfile->dwp_file.get ();
13191 }
13192
13193 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13194    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13195    or in the DWP file for the objfile, referenced by THIS_UNIT.
13196    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13197    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13198
13199    This is called, for example, when wanting to read a variable with a
13200    complex location.  Therefore we don't want to do file i/o for every call.
13201    Therefore we don't want to look for a DWO file on every call.
13202    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13203    then we check if we've already seen DWO_NAME, and only THEN do we check
13204    for a DWO file.
13205
13206    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13207    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13208
13209 static struct dwo_unit *
13210 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13211                  const char *dwo_name, const char *comp_dir,
13212                  ULONGEST signature, int is_debug_types)
13213 {
13214   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13215   struct objfile *objfile = dwarf2_per_objfile->objfile;
13216   const char *kind = is_debug_types ? "TU" : "CU";
13217   void **dwo_file_slot;
13218   struct dwo_file *dwo_file;
13219   struct dwp_file *dwp_file;
13220
13221   /* First see if there's a DWP file.
13222      If we have a DWP file but didn't find the DWO inside it, don't
13223      look for the original DWO file.  It makes gdb behave differently
13224      depending on whether one is debugging in the build tree.  */
13225
13226   dwp_file = get_dwp_file (dwarf2_per_objfile);
13227   if (dwp_file != NULL)
13228     {
13229       const struct dwp_hash_table *dwp_htab =
13230         is_debug_types ? dwp_file->tus : dwp_file->cus;
13231
13232       if (dwp_htab != NULL)
13233         {
13234           struct dwo_unit *dwo_cutu =
13235             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13236                                     signature, is_debug_types);
13237
13238           if (dwo_cutu != NULL)
13239             {
13240               if (dwarf_read_debug)
13241                 {
13242                   fprintf_unfiltered (gdb_stdlog,
13243                                       "Virtual DWO %s %s found: @%s\n",
13244                                       kind, hex_string (signature),
13245                                       host_address_to_string (dwo_cutu));
13246                 }
13247               return dwo_cutu;
13248             }
13249         }
13250     }
13251   else
13252     {
13253       /* No DWP file, look for the DWO file.  */
13254
13255       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13256                                             dwo_name, comp_dir);
13257       if (*dwo_file_slot == NULL)
13258         {
13259           /* Read in the file and build a table of the CUs/TUs it contains.  */
13260           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13261         }
13262       /* NOTE: This will be NULL if unable to open the file.  */
13263       dwo_file = (struct dwo_file *) *dwo_file_slot;
13264
13265       if (dwo_file != NULL)
13266         {
13267           struct dwo_unit *dwo_cutu = NULL;
13268
13269           if (is_debug_types && dwo_file->tus)
13270             {
13271               struct dwo_unit find_dwo_cutu;
13272
13273               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13274               find_dwo_cutu.signature = signature;
13275               dwo_cutu
13276                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13277             }
13278           else if (!is_debug_types && dwo_file->cus)
13279             {
13280               struct dwo_unit find_dwo_cutu;
13281
13282               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13283               find_dwo_cutu.signature = signature;
13284               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13285                                                        &find_dwo_cutu);
13286             }
13287
13288           if (dwo_cutu != NULL)
13289             {
13290               if (dwarf_read_debug)
13291                 {
13292                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13293                                       kind, dwo_name, hex_string (signature),
13294                                       host_address_to_string (dwo_cutu));
13295                 }
13296               return dwo_cutu;
13297             }
13298         }
13299     }
13300
13301   /* We didn't find it.  This could mean a dwo_id mismatch, or
13302      someone deleted the DWO/DWP file, or the search path isn't set up
13303      correctly to find the file.  */
13304
13305   if (dwarf_read_debug)
13306     {
13307       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13308                           kind, dwo_name, hex_string (signature));
13309     }
13310
13311   /* This is a warning and not a complaint because it can be caused by
13312      pilot error (e.g., user accidentally deleting the DWO).  */
13313   {
13314     /* Print the name of the DWP file if we looked there, helps the user
13315        better diagnose the problem.  */
13316     std::string dwp_text;
13317
13318     if (dwp_file != NULL)
13319       dwp_text = string_printf (" [in DWP file %s]",
13320                                 lbasename (dwp_file->name));
13321
13322     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13323                " [in module %s]"),
13324              kind, dwo_name, hex_string (signature),
13325              dwp_text.c_str (),
13326              this_unit->is_debug_types ? "TU" : "CU",
13327              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13328   }
13329   return NULL;
13330 }
13331
13332 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13333    See lookup_dwo_cutu_unit for details.  */
13334
13335 static struct dwo_unit *
13336 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13337                       const char *dwo_name, const char *comp_dir,
13338                       ULONGEST signature)
13339 {
13340   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13341 }
13342
13343 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13344    See lookup_dwo_cutu_unit for details.  */
13345
13346 static struct dwo_unit *
13347 lookup_dwo_type_unit (struct signatured_type *this_tu,
13348                       const char *dwo_name, const char *comp_dir)
13349 {
13350   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13351 }
13352
13353 /* Traversal function for queue_and_load_all_dwo_tus.  */
13354
13355 static int
13356 queue_and_load_dwo_tu (void **slot, void *info)
13357 {
13358   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13359   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13360   ULONGEST signature = dwo_unit->signature;
13361   struct signatured_type *sig_type =
13362     lookup_dwo_signatured_type (per_cu->cu, signature);
13363
13364   if (sig_type != NULL)
13365     {
13366       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13367
13368       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13369          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13370          while processing PER_CU.  */
13371       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13372         load_full_type_unit (sig_cu);
13373       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13374     }
13375
13376   return 1;
13377 }
13378
13379 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13380    The DWO may have the only definition of the type, though it may not be
13381    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13382    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13383
13384 static void
13385 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13386 {
13387   struct dwo_unit *dwo_unit;
13388   struct dwo_file *dwo_file;
13389
13390   gdb_assert (!per_cu->is_debug_types);
13391   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13392   gdb_assert (per_cu->cu != NULL);
13393
13394   dwo_unit = per_cu->cu->dwo_unit;
13395   gdb_assert (dwo_unit != NULL);
13396
13397   dwo_file = dwo_unit->dwo_file;
13398   if (dwo_file->tus != NULL)
13399     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13400 }
13401
13402 /* Free all resources associated with DWO_FILE.
13403    Close the DWO file and munmap the sections.  */
13404
13405 static void
13406 free_dwo_file (struct dwo_file *dwo_file)
13407 {
13408   /* Note: dbfd is NULL for virtual DWO files.  */
13409   gdb_bfd_unref (dwo_file->dbfd);
13410
13411   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13412 }
13413
13414 /* Traversal function for free_dwo_files.  */
13415
13416 static int
13417 free_dwo_file_from_slot (void **slot, void *info)
13418 {
13419   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13420
13421   free_dwo_file (dwo_file);
13422
13423   return 1;
13424 }
13425
13426 /* Free all resources associated with DWO_FILES.  */
13427
13428 static void
13429 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13430 {
13431   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13432 }
13433 \f
13434 /* Read in various DIEs.  */
13435
13436 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13437    Inherit only the children of the DW_AT_abstract_origin DIE not being
13438    already referenced by DW_AT_abstract_origin from the children of the
13439    current DIE.  */
13440
13441 static void
13442 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13443 {
13444   struct die_info *child_die;
13445   sect_offset *offsetp;
13446   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13447   struct die_info *origin_die;
13448   /* Iterator of the ORIGIN_DIE children.  */
13449   struct die_info *origin_child_die;
13450   struct attribute *attr;
13451   struct dwarf2_cu *origin_cu;
13452   struct pending **origin_previous_list_in_scope;
13453
13454   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13455   if (!attr)
13456     return;
13457
13458   /* Note that following die references may follow to a die in a
13459      different cu.  */
13460
13461   origin_cu = cu;
13462   origin_die = follow_die_ref (die, attr, &origin_cu);
13463
13464   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13465      symbols in.  */
13466   origin_previous_list_in_scope = origin_cu->list_in_scope;
13467   origin_cu->list_in_scope = cu->list_in_scope;
13468
13469   if (die->tag != origin_die->tag
13470       && !(die->tag == DW_TAG_inlined_subroutine
13471            && origin_die->tag == DW_TAG_subprogram))
13472     complaint (_("DIE %s and its abstract origin %s have different tags"),
13473                sect_offset_str (die->sect_off),
13474                sect_offset_str (origin_die->sect_off));
13475
13476   std::vector<sect_offset> offsets;
13477
13478   for (child_die = die->child;
13479        child_die && child_die->tag;
13480        child_die = sibling_die (child_die))
13481     {
13482       struct die_info *child_origin_die;
13483       struct dwarf2_cu *child_origin_cu;
13484
13485       /* We are trying to process concrete instance entries:
13486          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13487          it's not relevant to our analysis here. i.e. detecting DIEs that are
13488          present in the abstract instance but not referenced in the concrete
13489          one.  */
13490       if (child_die->tag == DW_TAG_call_site
13491           || child_die->tag == DW_TAG_GNU_call_site)
13492         continue;
13493
13494       /* For each CHILD_DIE, find the corresponding child of
13495          ORIGIN_DIE.  If there is more than one layer of
13496          DW_AT_abstract_origin, follow them all; there shouldn't be,
13497          but GCC versions at least through 4.4 generate this (GCC PR
13498          40573).  */
13499       child_origin_die = child_die;
13500       child_origin_cu = cu;
13501       while (1)
13502         {
13503           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13504                               child_origin_cu);
13505           if (attr == NULL)
13506             break;
13507           child_origin_die = follow_die_ref (child_origin_die, attr,
13508                                              &child_origin_cu);
13509         }
13510
13511       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13512          counterpart may exist.  */
13513       if (child_origin_die != child_die)
13514         {
13515           if (child_die->tag != child_origin_die->tag
13516               && !(child_die->tag == DW_TAG_inlined_subroutine
13517                    && child_origin_die->tag == DW_TAG_subprogram))
13518             complaint (_("Child DIE %s and its abstract origin %s have "
13519                          "different tags"),
13520                        sect_offset_str (child_die->sect_off),
13521                        sect_offset_str (child_origin_die->sect_off));
13522           if (child_origin_die->parent != origin_die)
13523             complaint (_("Child DIE %s and its abstract origin %s have "
13524                          "different parents"),
13525                        sect_offset_str (child_die->sect_off),
13526                        sect_offset_str (child_origin_die->sect_off));
13527           else
13528             offsets.push_back (child_origin_die->sect_off);
13529         }
13530     }
13531   std::sort (offsets.begin (), offsets.end ());
13532   sect_offset *offsets_end = offsets.data () + offsets.size ();
13533   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13534     if (offsetp[-1] == *offsetp)
13535       complaint (_("Multiple children of DIE %s refer "
13536                    "to DIE %s as their abstract origin"),
13537                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13538
13539   offsetp = offsets.data ();
13540   origin_child_die = origin_die->child;
13541   while (origin_child_die && origin_child_die->tag)
13542     {
13543       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13544       while (offsetp < offsets_end
13545              && *offsetp < origin_child_die->sect_off)
13546         offsetp++;
13547       if (offsetp >= offsets_end
13548           || *offsetp > origin_child_die->sect_off)
13549         {
13550           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13551              Check whether we're already processing ORIGIN_CHILD_DIE.
13552              This can happen with mutually referenced abstract_origins.
13553              PR 16581.  */
13554           if (!origin_child_die->in_process)
13555             process_die (origin_child_die, origin_cu);
13556         }
13557       origin_child_die = sibling_die (origin_child_die);
13558     }
13559   origin_cu->list_in_scope = origin_previous_list_in_scope;
13560 }
13561
13562 static void
13563 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13564 {
13565   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13566   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13567   struct context_stack *newobj;
13568   CORE_ADDR lowpc;
13569   CORE_ADDR highpc;
13570   struct die_info *child_die;
13571   struct attribute *attr, *call_line, *call_file;
13572   const char *name;
13573   CORE_ADDR baseaddr;
13574   struct block *block;
13575   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13576   std::vector<struct symbol *> template_args;
13577   struct template_symbol *templ_func = NULL;
13578
13579   if (inlined_func)
13580     {
13581       /* If we do not have call site information, we can't show the
13582          caller of this inlined function.  That's too confusing, so
13583          only use the scope for local variables.  */
13584       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13585       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13586       if (call_line == NULL || call_file == NULL)
13587         {
13588           read_lexical_block_scope (die, cu);
13589           return;
13590         }
13591     }
13592
13593   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13594
13595   name = dwarf2_name (die, cu);
13596
13597   /* Ignore functions with missing or empty names.  These are actually
13598      illegal according to the DWARF standard.  */
13599   if (name == NULL)
13600     {
13601       complaint (_("missing name for subprogram DIE at %s"),
13602                  sect_offset_str (die->sect_off));
13603       return;
13604     }
13605
13606   /* Ignore functions with missing or invalid low and high pc attributes.  */
13607   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13608       <= PC_BOUNDS_INVALID)
13609     {
13610       attr = dwarf2_attr (die, DW_AT_external, cu);
13611       if (!attr || !DW_UNSND (attr))
13612         complaint (_("cannot get low and high bounds "
13613                      "for subprogram DIE at %s"),
13614                    sect_offset_str (die->sect_off));
13615       return;
13616     }
13617
13618   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13619   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13620
13621   /* If we have any template arguments, then we must allocate a
13622      different sort of symbol.  */
13623   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13624     {
13625       if (child_die->tag == DW_TAG_template_type_param
13626           || child_die->tag == DW_TAG_template_value_param)
13627         {
13628           templ_func = allocate_template_symbol (objfile);
13629           templ_func->subclass = SYMBOL_TEMPLATE;
13630           break;
13631         }
13632     }
13633
13634   newobj = push_context (0, lowpc);
13635   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13636                              (struct symbol *) templ_func);
13637
13638   /* If there is a location expression for DW_AT_frame_base, record
13639      it.  */
13640   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13641   if (attr)
13642     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13643
13644   /* If there is a location for the static link, record it.  */
13645   newobj->static_link = NULL;
13646   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13647   if (attr)
13648     {
13649       newobj->static_link
13650         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13651       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13652     }
13653
13654   cu->list_in_scope = &local_symbols;
13655
13656   if (die->child != NULL)
13657     {
13658       child_die = die->child;
13659       while (child_die && child_die->tag)
13660         {
13661           if (child_die->tag == DW_TAG_template_type_param
13662               || child_die->tag == DW_TAG_template_value_param)
13663             {
13664               struct symbol *arg = new_symbol (child_die, NULL, cu);
13665
13666               if (arg != NULL)
13667                 template_args.push_back (arg);
13668             }
13669           else
13670             process_die (child_die, cu);
13671           child_die = sibling_die (child_die);
13672         }
13673     }
13674
13675   inherit_abstract_dies (die, cu);
13676
13677   /* If we have a DW_AT_specification, we might need to import using
13678      directives from the context of the specification DIE.  See the
13679      comment in determine_prefix.  */
13680   if (cu->language == language_cplus
13681       && dwarf2_attr (die, DW_AT_specification, cu))
13682     {
13683       struct dwarf2_cu *spec_cu = cu;
13684       struct die_info *spec_die = die_specification (die, &spec_cu);
13685
13686       while (spec_die)
13687         {
13688           child_die = spec_die->child;
13689           while (child_die && child_die->tag)
13690             {
13691               if (child_die->tag == DW_TAG_imported_module)
13692                 process_die (child_die, spec_cu);
13693               child_die = sibling_die (child_die);
13694             }
13695
13696           /* In some cases, GCC generates specification DIEs that
13697              themselves contain DW_AT_specification attributes.  */
13698           spec_die = die_specification (spec_die, &spec_cu);
13699         }
13700     }
13701
13702   newobj = pop_context ();
13703   /* Make a block for the local symbols within.  */
13704   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13705                         newobj->static_link, lowpc, highpc);
13706
13707   /* For C++, set the block's scope.  */
13708   if ((cu->language == language_cplus
13709        || cu->language == language_fortran
13710        || cu->language == language_d
13711        || cu->language == language_rust)
13712       && cu->processing_has_namespace_info)
13713     block_set_scope (block, determine_prefix (die, cu),
13714                      &objfile->objfile_obstack);
13715
13716   /* If we have address ranges, record them.  */
13717   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13718
13719   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13720
13721   /* Attach template arguments to function.  */
13722   if (!template_args.empty ())
13723     {
13724       gdb_assert (templ_func != NULL);
13725
13726       templ_func->n_template_arguments = template_args.size ();
13727       templ_func->template_arguments
13728         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13729                      templ_func->n_template_arguments);
13730       memcpy (templ_func->template_arguments,
13731               template_args.data (),
13732               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13733     }
13734
13735   /* In C++, we can have functions nested inside functions (e.g., when
13736      a function declares a class that has methods).  This means that
13737      when we finish processing a function scope, we may need to go
13738      back to building a containing block's symbol lists.  */
13739   local_symbols = newobj->locals;
13740   local_using_directives = newobj->local_using_directives;
13741
13742   /* If we've finished processing a top-level function, subsequent
13743      symbols go in the file symbol list.  */
13744   if (outermost_context_p ())
13745     cu->list_in_scope = &file_symbols;
13746 }
13747
13748 /* Process all the DIES contained within a lexical block scope.  Start
13749    a new scope, process the dies, and then close the scope.  */
13750
13751 static void
13752 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13753 {
13754   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13755   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13756   struct context_stack *newobj;
13757   CORE_ADDR lowpc, highpc;
13758   struct die_info *child_die;
13759   CORE_ADDR baseaddr;
13760
13761   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13762
13763   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13764   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13765      as multiple lexical blocks?  Handling children in a sane way would
13766      be nasty.  Might be easier to properly extend generic blocks to
13767      describe ranges.  */
13768   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13769     {
13770     case PC_BOUNDS_NOT_PRESENT:
13771       /* DW_TAG_lexical_block has no attributes, process its children as if
13772          there was no wrapping by that DW_TAG_lexical_block.
13773          GCC does no longer produces such DWARF since GCC r224161.  */
13774       for (child_die = die->child;
13775            child_die != NULL && child_die->tag;
13776            child_die = sibling_die (child_die))
13777         process_die (child_die, cu);
13778       return;
13779     case PC_BOUNDS_INVALID:
13780       return;
13781     }
13782   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13783   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13784
13785   push_context (0, lowpc);
13786   if (die->child != NULL)
13787     {
13788       child_die = die->child;
13789       while (child_die && child_die->tag)
13790         {
13791           process_die (child_die, cu);
13792           child_die = sibling_die (child_die);
13793         }
13794     }
13795   inherit_abstract_dies (die, cu);
13796   newobj = pop_context ();
13797
13798   if (local_symbols != NULL || local_using_directives != NULL)
13799     {
13800       struct block *block
13801         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13802                         newobj->start_addr, highpc);
13803
13804       /* Note that recording ranges after traversing children, as we
13805          do here, means that recording a parent's ranges entails
13806          walking across all its children's ranges as they appear in
13807          the address map, which is quadratic behavior.
13808
13809          It would be nicer to record the parent's ranges before
13810          traversing its children, simply overriding whatever you find
13811          there.  But since we don't even decide whether to create a
13812          block until after we've traversed its children, that's hard
13813          to do.  */
13814       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13815     }
13816   local_symbols = newobj->locals;
13817   local_using_directives = newobj->local_using_directives;
13818 }
13819
13820 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13821
13822 static void
13823 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13824 {
13825   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13826   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13827   CORE_ADDR pc, baseaddr;
13828   struct attribute *attr;
13829   struct call_site *call_site, call_site_local;
13830   void **slot;
13831   int nparams;
13832   struct die_info *child_die;
13833
13834   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13835
13836   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13837   if (attr == NULL)
13838     {
13839       /* This was a pre-DWARF-5 GNU extension alias
13840          for DW_AT_call_return_pc.  */
13841       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13842     }
13843   if (!attr)
13844     {
13845       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13846                    "DIE %s [in module %s]"),
13847                  sect_offset_str (die->sect_off), objfile_name (objfile));
13848       return;
13849     }
13850   pc = attr_value_as_address (attr) + baseaddr;
13851   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13852
13853   if (cu->call_site_htab == NULL)
13854     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13855                                                NULL, &objfile->objfile_obstack,
13856                                                hashtab_obstack_allocate, NULL);
13857   call_site_local.pc = pc;
13858   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13859   if (*slot != NULL)
13860     {
13861       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13862                    "DIE %s [in module %s]"),
13863                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13864                  objfile_name (objfile));
13865       return;
13866     }
13867
13868   /* Count parameters at the caller.  */
13869
13870   nparams = 0;
13871   for (child_die = die->child; child_die && child_die->tag;
13872        child_die = sibling_die (child_die))
13873     {
13874       if (child_die->tag != DW_TAG_call_site_parameter
13875           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13876         {
13877           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13878                        "DW_TAG_call_site child DIE %s [in module %s]"),
13879                      child_die->tag, sect_offset_str (child_die->sect_off),
13880                      objfile_name (objfile));
13881           continue;
13882         }
13883
13884       nparams++;
13885     }
13886
13887   call_site
13888     = ((struct call_site *)
13889        obstack_alloc (&objfile->objfile_obstack,
13890                       sizeof (*call_site)
13891                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13892   *slot = call_site;
13893   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13894   call_site->pc = pc;
13895
13896   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13897       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13898     {
13899       struct die_info *func_die;
13900
13901       /* Skip also over DW_TAG_inlined_subroutine.  */
13902       for (func_die = die->parent;
13903            func_die && func_die->tag != DW_TAG_subprogram
13904            && func_die->tag != DW_TAG_subroutine_type;
13905            func_die = func_die->parent);
13906
13907       /* DW_AT_call_all_calls is a superset
13908          of DW_AT_call_all_tail_calls.  */
13909       if (func_die
13910           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13911           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13912           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13913           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13914         {
13915           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13916              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13917              both the initial caller containing the real return address PC and
13918              the final callee containing the current PC of a chain of tail
13919              calls do not need to have the tail call list complete.  But any
13920              function candidate for a virtual tail call frame searched via
13921              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13922              determined unambiguously.  */
13923         }
13924       else
13925         {
13926           struct type *func_type = NULL;
13927
13928           if (func_die)
13929             func_type = get_die_type (func_die, cu);
13930           if (func_type != NULL)
13931             {
13932               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13933
13934               /* Enlist this call site to the function.  */
13935               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13936               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13937             }
13938           else
13939             complaint (_("Cannot find function owning DW_TAG_call_site "
13940                          "DIE %s [in module %s]"),
13941                        sect_offset_str (die->sect_off), objfile_name (objfile));
13942         }
13943     }
13944
13945   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13946   if (attr == NULL)
13947     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13948   if (attr == NULL)
13949     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13950   if (attr == NULL)
13951     {
13952       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13953       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13954     }
13955   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13956   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
13957     /* Keep NULL DWARF_BLOCK.  */;
13958   else if (attr_form_is_block (attr))
13959     {
13960       struct dwarf2_locexpr_baton *dlbaton;
13961
13962       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13963       dlbaton->data = DW_BLOCK (attr)->data;
13964       dlbaton->size = DW_BLOCK (attr)->size;
13965       dlbaton->per_cu = cu->per_cu;
13966
13967       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13968     }
13969   else if (attr_form_is_ref (attr))
13970     {
13971       struct dwarf2_cu *target_cu = cu;
13972       struct die_info *target_die;
13973
13974       target_die = follow_die_ref (die, attr, &target_cu);
13975       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
13976       if (die_is_declaration (target_die, target_cu))
13977         {
13978           const char *target_physname;
13979
13980           /* Prefer the mangled name; otherwise compute the demangled one.  */
13981           target_physname = dw2_linkage_name (target_die, target_cu);
13982           if (target_physname == NULL)
13983             target_physname = dwarf2_physname (NULL, target_die, target_cu);
13984           if (target_physname == NULL)
13985             complaint (_("DW_AT_call_target target DIE has invalid "
13986                          "physname, for referencing DIE %s [in module %s]"),
13987                        sect_offset_str (die->sect_off), objfile_name (objfile));
13988           else
13989             SET_FIELD_PHYSNAME (call_site->target, target_physname);
13990         }
13991       else
13992         {
13993           CORE_ADDR lowpc;
13994
13995           /* DW_AT_entry_pc should be preferred.  */
13996           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
13997               <= PC_BOUNDS_INVALID)
13998             complaint (_("DW_AT_call_target target DIE has invalid "
13999                          "low pc, for referencing DIE %s [in module %s]"),
14000                        sect_offset_str (die->sect_off), objfile_name (objfile));
14001           else
14002             {
14003               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14004               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14005             }
14006         }
14007     }
14008   else
14009     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
14010                  "block nor reference, for DIE %s [in module %s]"),
14011                sect_offset_str (die->sect_off), objfile_name (objfile));
14012
14013   call_site->per_cu = cu->per_cu;
14014
14015   for (child_die = die->child;
14016        child_die && child_die->tag;
14017        child_die = sibling_die (child_die))
14018     {
14019       struct call_site_parameter *parameter;
14020       struct attribute *loc, *origin;
14021
14022       if (child_die->tag != DW_TAG_call_site_parameter
14023           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14024         {
14025           /* Already printed the complaint above.  */
14026           continue;
14027         }
14028
14029       gdb_assert (call_site->parameter_count < nparams);
14030       parameter = &call_site->parameter[call_site->parameter_count];
14031
14032       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14033          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14034          register is contained in DW_AT_call_value.  */
14035
14036       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14037       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14038       if (origin == NULL)
14039         {
14040           /* This was a pre-DWARF-5 GNU extension alias
14041              for DW_AT_call_parameter.  */
14042           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14043         }
14044       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14045         {
14046           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14047
14048           sect_offset sect_off
14049             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14050           if (!offset_in_cu_p (&cu->header, sect_off))
14051             {
14052               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14053                  binding can be done only inside one CU.  Such referenced DIE
14054                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14055               complaint (_("DW_AT_call_parameter offset is not in CU for "
14056                            "DW_TAG_call_site child DIE %s [in module %s]"),
14057                          sect_offset_str (child_die->sect_off),
14058                          objfile_name (objfile));
14059               continue;
14060             }
14061           parameter->u.param_cu_off
14062             = (cu_offset) (sect_off - cu->header.sect_off);
14063         }
14064       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14065         {
14066           complaint (_("No DW_FORM_block* DW_AT_location for "
14067                        "DW_TAG_call_site child DIE %s [in module %s]"),
14068                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14069           continue;
14070         }
14071       else
14072         {
14073           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14074             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14075           if (parameter->u.dwarf_reg != -1)
14076             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14077           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14078                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14079                                              &parameter->u.fb_offset))
14080             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14081           else
14082             {
14083               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14084                            "for DW_FORM_block* DW_AT_location is supported for "
14085                            "DW_TAG_call_site child DIE %s "
14086                            "[in module %s]"),
14087                          sect_offset_str (child_die->sect_off),
14088                          objfile_name (objfile));
14089               continue;
14090             }
14091         }
14092
14093       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14094       if (attr == NULL)
14095         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14096       if (!attr_form_is_block (attr))
14097         {
14098           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14099                        "DW_TAG_call_site child DIE %s [in module %s]"),
14100                      sect_offset_str (child_die->sect_off),
14101                      objfile_name (objfile));
14102           continue;
14103         }
14104       parameter->value = DW_BLOCK (attr)->data;
14105       parameter->value_size = DW_BLOCK (attr)->size;
14106
14107       /* Parameters are not pre-cleared by memset above.  */
14108       parameter->data_value = NULL;
14109       parameter->data_value_size = 0;
14110       call_site->parameter_count++;
14111
14112       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14113       if (attr == NULL)
14114         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14115       if (attr)
14116         {
14117           if (!attr_form_is_block (attr))
14118             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14119                          "DW_TAG_call_site child DIE %s [in module %s]"),
14120                        sect_offset_str (child_die->sect_off),
14121                        objfile_name (objfile));
14122           else
14123             {
14124               parameter->data_value = DW_BLOCK (attr)->data;
14125               parameter->data_value_size = DW_BLOCK (attr)->size;
14126             }
14127         }
14128     }
14129 }
14130
14131 /* Helper function for read_variable.  If DIE represents a virtual
14132    table, then return the type of the concrete object that is
14133    associated with the virtual table.  Otherwise, return NULL.  */
14134
14135 static struct type *
14136 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14137 {
14138   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14139   if (attr == NULL)
14140     return NULL;
14141
14142   /* Find the type DIE.  */
14143   struct die_info *type_die = NULL;
14144   struct dwarf2_cu *type_cu = cu;
14145
14146   if (attr_form_is_ref (attr))
14147     type_die = follow_die_ref (die, attr, &type_cu);
14148   if (type_die == NULL)
14149     return NULL;
14150
14151   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14152     return NULL;
14153   return die_containing_type (type_die, type_cu);
14154 }
14155
14156 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14157
14158 static void
14159 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14160 {
14161   struct rust_vtable_symbol *storage = NULL;
14162
14163   if (cu->language == language_rust)
14164     {
14165       struct type *containing_type = rust_containing_type (die, cu);
14166
14167       if (containing_type != NULL)
14168         {
14169           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14170
14171           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14172                                     struct rust_vtable_symbol);
14173           initialize_objfile_symbol (storage);
14174           storage->concrete_type = containing_type;
14175           storage->subclass = SYMBOL_RUST_VTABLE;
14176         }
14177     }
14178
14179   new_symbol (die, NULL, cu, storage);
14180 }
14181
14182 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14183    reading .debug_rnglists.
14184    Callback's type should be:
14185     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14186    Return true if the attributes are present and valid, otherwise,
14187    return false.  */
14188
14189 template <typename Callback>
14190 static bool
14191 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14192                          Callback &&callback)
14193 {
14194   struct dwarf2_per_objfile *dwarf2_per_objfile
14195     = cu->per_cu->dwarf2_per_objfile;
14196   struct objfile *objfile = dwarf2_per_objfile->objfile;
14197   bfd *obfd = objfile->obfd;
14198   /* Base address selection entry.  */
14199   CORE_ADDR base;
14200   int found_base;
14201   const gdb_byte *buffer;
14202   CORE_ADDR baseaddr;
14203   bool overflow = false;
14204
14205   found_base = cu->base_known;
14206   base = cu->base_address;
14207
14208   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14209   if (offset >= dwarf2_per_objfile->rnglists.size)
14210     {
14211       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14212                  offset);
14213       return false;
14214     }
14215   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14216
14217   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14218
14219   while (1)
14220     {
14221       /* Initialize it due to a false compiler warning.  */
14222       CORE_ADDR range_beginning = 0, range_end = 0;
14223       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14224                                  + dwarf2_per_objfile->rnglists.size);
14225       unsigned int bytes_read;
14226
14227       if (buffer == buf_end)
14228         {
14229           overflow = true;
14230           break;
14231         }
14232       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14233       switch (rlet)
14234         {
14235         case DW_RLE_end_of_list:
14236           break;
14237         case DW_RLE_base_address:
14238           if (buffer + cu->header.addr_size > buf_end)
14239             {
14240               overflow = true;
14241               break;
14242             }
14243           base = read_address (obfd, buffer, cu, &bytes_read);
14244           found_base = 1;
14245           buffer += bytes_read;
14246           break;
14247         case DW_RLE_start_length:
14248           if (buffer + cu->header.addr_size > buf_end)
14249             {
14250               overflow = true;
14251               break;
14252             }
14253           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14254           buffer += bytes_read;
14255           range_end = (range_beginning
14256                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14257           buffer += bytes_read;
14258           if (buffer > buf_end)
14259             {
14260               overflow = true;
14261               break;
14262             }
14263           break;
14264         case DW_RLE_offset_pair:
14265           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14266           buffer += bytes_read;
14267           if (buffer > buf_end)
14268             {
14269               overflow = true;
14270               break;
14271             }
14272           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14273           buffer += bytes_read;
14274           if (buffer > buf_end)
14275             {
14276               overflow = true;
14277               break;
14278             }
14279           break;
14280         case DW_RLE_start_end:
14281           if (buffer + 2 * cu->header.addr_size > buf_end)
14282             {
14283               overflow = true;
14284               break;
14285             }
14286           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14287           buffer += bytes_read;
14288           range_end = read_address (obfd, buffer, cu, &bytes_read);
14289           buffer += bytes_read;
14290           break;
14291         default:
14292           complaint (_("Invalid .debug_rnglists data (no base address)"));
14293           return false;
14294         }
14295       if (rlet == DW_RLE_end_of_list || overflow)
14296         break;
14297       if (rlet == DW_RLE_base_address)
14298         continue;
14299
14300       if (!found_base)
14301         {
14302           /* We have no valid base address for the ranges
14303              data.  */
14304           complaint (_("Invalid .debug_rnglists data (no base address)"));
14305           return false;
14306         }
14307
14308       if (range_beginning > range_end)
14309         {
14310           /* Inverted range entries are invalid.  */
14311           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14312           return false;
14313         }
14314
14315       /* Empty range entries have no effect.  */
14316       if (range_beginning == range_end)
14317         continue;
14318
14319       range_beginning += base;
14320       range_end += base;
14321
14322       /* A not-uncommon case of bad debug info.
14323          Don't pollute the addrmap with bad data.  */
14324       if (range_beginning + baseaddr == 0
14325           && !dwarf2_per_objfile->has_section_at_zero)
14326         {
14327           complaint (_(".debug_rnglists entry has start address of zero"
14328                        " [in module %s]"), objfile_name (objfile));
14329           continue;
14330         }
14331
14332       callback (range_beginning, range_end);
14333     }
14334
14335   if (overflow)
14336     {
14337       complaint (_("Offset %d is not terminated "
14338                    "for DW_AT_ranges attribute"),
14339                  offset);
14340       return false;
14341     }
14342
14343   return true;
14344 }
14345
14346 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14347    Callback's type should be:
14348     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14349    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14350
14351 template <typename Callback>
14352 static int
14353 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14354                        Callback &&callback)
14355 {
14356   struct dwarf2_per_objfile *dwarf2_per_objfile
14357       = cu->per_cu->dwarf2_per_objfile;
14358   struct objfile *objfile = dwarf2_per_objfile->objfile;
14359   struct comp_unit_head *cu_header = &cu->header;
14360   bfd *obfd = objfile->obfd;
14361   unsigned int addr_size = cu_header->addr_size;
14362   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14363   /* Base address selection entry.  */
14364   CORE_ADDR base;
14365   int found_base;
14366   unsigned int dummy;
14367   const gdb_byte *buffer;
14368   CORE_ADDR baseaddr;
14369
14370   if (cu_header->version >= 5)
14371     return dwarf2_rnglists_process (offset, cu, callback);
14372
14373   found_base = cu->base_known;
14374   base = cu->base_address;
14375
14376   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14377   if (offset >= dwarf2_per_objfile->ranges.size)
14378     {
14379       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14380                  offset);
14381       return 0;
14382     }
14383   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14384
14385   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14386
14387   while (1)
14388     {
14389       CORE_ADDR range_beginning, range_end;
14390
14391       range_beginning = read_address (obfd, buffer, cu, &dummy);
14392       buffer += addr_size;
14393       range_end = read_address (obfd, buffer, cu, &dummy);
14394       buffer += addr_size;
14395       offset += 2 * addr_size;
14396
14397       /* An end of list marker is a pair of zero addresses.  */
14398       if (range_beginning == 0 && range_end == 0)
14399         /* Found the end of list entry.  */
14400         break;
14401
14402       /* Each base address selection entry is a pair of 2 values.
14403          The first is the largest possible address, the second is
14404          the base address.  Check for a base address here.  */
14405       if ((range_beginning & mask) == mask)
14406         {
14407           /* If we found the largest possible address, then we already
14408              have the base address in range_end.  */
14409           base = range_end;
14410           found_base = 1;
14411           continue;
14412         }
14413
14414       if (!found_base)
14415         {
14416           /* We have no valid base address for the ranges
14417              data.  */
14418           complaint (_("Invalid .debug_ranges data (no base address)"));
14419           return 0;
14420         }
14421
14422       if (range_beginning > range_end)
14423         {
14424           /* Inverted range entries are invalid.  */
14425           complaint (_("Invalid .debug_ranges data (inverted range)"));
14426           return 0;
14427         }
14428
14429       /* Empty range entries have no effect.  */
14430       if (range_beginning == range_end)
14431         continue;
14432
14433       range_beginning += base;
14434       range_end += base;
14435
14436       /* A not-uncommon case of bad debug info.
14437          Don't pollute the addrmap with bad data.  */
14438       if (range_beginning + baseaddr == 0
14439           && !dwarf2_per_objfile->has_section_at_zero)
14440         {
14441           complaint (_(".debug_ranges entry has start address of zero"
14442                        " [in module %s]"), objfile_name (objfile));
14443           continue;
14444         }
14445
14446       callback (range_beginning, range_end);
14447     }
14448
14449   return 1;
14450 }
14451
14452 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14453    Return 1 if the attributes are present and valid, otherwise, return 0.
14454    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14455
14456 static int
14457 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14458                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14459                     struct partial_symtab *ranges_pst)
14460 {
14461   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14462   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14463   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14464                                        SECT_OFF_TEXT (objfile));
14465   int low_set = 0;
14466   CORE_ADDR low = 0;
14467   CORE_ADDR high = 0;
14468   int retval;
14469
14470   retval = dwarf2_ranges_process (offset, cu,
14471     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14472     {
14473       if (ranges_pst != NULL)
14474         {
14475           CORE_ADDR lowpc;
14476           CORE_ADDR highpc;
14477
14478           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14479                                               range_beginning + baseaddr);
14480           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14481                                                range_end + baseaddr);
14482           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14483                              ranges_pst);
14484         }
14485
14486       /* FIXME: This is recording everything as a low-high
14487          segment of consecutive addresses.  We should have a
14488          data structure for discontiguous block ranges
14489          instead.  */
14490       if (! low_set)
14491         {
14492           low = range_beginning;
14493           high = range_end;
14494           low_set = 1;
14495         }
14496       else
14497         {
14498           if (range_beginning < low)
14499             low = range_beginning;
14500           if (range_end > high)
14501             high = range_end;
14502         }
14503     });
14504   if (!retval)
14505     return 0;
14506
14507   if (! low_set)
14508     /* If the first entry is an end-of-list marker, the range
14509        describes an empty scope, i.e. no instructions.  */
14510     return 0;
14511
14512   if (low_return)
14513     *low_return = low;
14514   if (high_return)
14515     *high_return = high;
14516   return 1;
14517 }
14518
14519 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14520    definition for the return value.  *LOWPC and *HIGHPC are set iff
14521    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14522
14523 static enum pc_bounds_kind
14524 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14525                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14526                       struct partial_symtab *pst)
14527 {
14528   struct dwarf2_per_objfile *dwarf2_per_objfile
14529     = cu->per_cu->dwarf2_per_objfile;
14530   struct attribute *attr;
14531   struct attribute *attr_high;
14532   CORE_ADDR low = 0;
14533   CORE_ADDR high = 0;
14534   enum pc_bounds_kind ret;
14535
14536   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14537   if (attr_high)
14538     {
14539       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14540       if (attr)
14541         {
14542           low = attr_value_as_address (attr);
14543           high = attr_value_as_address (attr_high);
14544           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14545             high += low;
14546         }
14547       else
14548         /* Found high w/o low attribute.  */
14549         return PC_BOUNDS_INVALID;
14550
14551       /* Found consecutive range of addresses.  */
14552       ret = PC_BOUNDS_HIGH_LOW;
14553     }
14554   else
14555     {
14556       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14557       if (attr != NULL)
14558         {
14559           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14560              We take advantage of the fact that DW_AT_ranges does not appear
14561              in DW_TAG_compile_unit of DWO files.  */
14562           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14563           unsigned int ranges_offset = (DW_UNSND (attr)
14564                                         + (need_ranges_base
14565                                            ? cu->ranges_base
14566                                            : 0));
14567
14568           /* Value of the DW_AT_ranges attribute is the offset in the
14569              .debug_ranges section.  */
14570           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14571             return PC_BOUNDS_INVALID;
14572           /* Found discontinuous range of addresses.  */
14573           ret = PC_BOUNDS_RANGES;
14574         }
14575       else
14576         return PC_BOUNDS_NOT_PRESENT;
14577     }
14578
14579   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14580   if (high <= low)
14581     return PC_BOUNDS_INVALID;
14582
14583   /* When using the GNU linker, .gnu.linkonce. sections are used to
14584      eliminate duplicate copies of functions and vtables and such.
14585      The linker will arbitrarily choose one and discard the others.
14586      The AT_*_pc values for such functions refer to local labels in
14587      these sections.  If the section from that file was discarded, the
14588      labels are not in the output, so the relocs get a value of 0.
14589      If this is a discarded function, mark the pc bounds as invalid,
14590      so that GDB will ignore it.  */
14591   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14592     return PC_BOUNDS_INVALID;
14593
14594   *lowpc = low;
14595   if (highpc)
14596     *highpc = high;
14597   return ret;
14598 }
14599
14600 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14601    its low and high PC addresses.  Do nothing if these addresses could not
14602    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14603    and HIGHPC to the high address if greater than HIGHPC.  */
14604
14605 static void
14606 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14607                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14608                                  struct dwarf2_cu *cu)
14609 {
14610   CORE_ADDR low, high;
14611   struct die_info *child = die->child;
14612
14613   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14614     {
14615       *lowpc = std::min (*lowpc, low);
14616       *highpc = std::max (*highpc, high);
14617     }
14618
14619   /* If the language does not allow nested subprograms (either inside
14620      subprograms or lexical blocks), we're done.  */
14621   if (cu->language != language_ada)
14622     return;
14623
14624   /* Check all the children of the given DIE.  If it contains nested
14625      subprograms, then check their pc bounds.  Likewise, we need to
14626      check lexical blocks as well, as they may also contain subprogram
14627      definitions.  */
14628   while (child && child->tag)
14629     {
14630       if (child->tag == DW_TAG_subprogram
14631           || child->tag == DW_TAG_lexical_block)
14632         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14633       child = sibling_die (child);
14634     }
14635 }
14636
14637 /* Get the low and high pc's represented by the scope DIE, and store
14638    them in *LOWPC and *HIGHPC.  If the correct values can't be
14639    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14640
14641 static void
14642 get_scope_pc_bounds (struct die_info *die,
14643                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14644                      struct dwarf2_cu *cu)
14645 {
14646   CORE_ADDR best_low = (CORE_ADDR) -1;
14647   CORE_ADDR best_high = (CORE_ADDR) 0;
14648   CORE_ADDR current_low, current_high;
14649
14650   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14651       >= PC_BOUNDS_RANGES)
14652     {
14653       best_low = current_low;
14654       best_high = current_high;
14655     }
14656   else
14657     {
14658       struct die_info *child = die->child;
14659
14660       while (child && child->tag)
14661         {
14662           switch (child->tag) {
14663           case DW_TAG_subprogram:
14664             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14665             break;
14666           case DW_TAG_namespace:
14667           case DW_TAG_module:
14668             /* FIXME: carlton/2004-01-16: Should we do this for
14669                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14670                that current GCC's always emit the DIEs corresponding
14671                to definitions of methods of classes as children of a
14672                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14673                the DIEs giving the declarations, which could be
14674                anywhere).  But I don't see any reason why the
14675                standards says that they have to be there.  */
14676             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14677
14678             if (current_low != ((CORE_ADDR) -1))
14679               {
14680                 best_low = std::min (best_low, current_low);
14681                 best_high = std::max (best_high, current_high);
14682               }
14683             break;
14684           default:
14685             /* Ignore.  */
14686             break;
14687           }
14688
14689           child = sibling_die (child);
14690         }
14691     }
14692
14693   *lowpc = best_low;
14694   *highpc = best_high;
14695 }
14696
14697 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14698    in DIE.  */
14699
14700 static void
14701 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14702                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14703 {
14704   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14705   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14706   struct attribute *attr;
14707   struct attribute *attr_high;
14708
14709   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14710   if (attr_high)
14711     {
14712       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14713       if (attr)
14714         {
14715           CORE_ADDR low = attr_value_as_address (attr);
14716           CORE_ADDR high = attr_value_as_address (attr_high);
14717
14718           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14719             high += low;
14720
14721           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14722           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14723           record_block_range (block, low, high - 1);
14724         }
14725     }
14726
14727   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14728   if (attr)
14729     {
14730       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14731          We take advantage of the fact that DW_AT_ranges does not appear
14732          in DW_TAG_compile_unit of DWO files.  */
14733       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14734
14735       /* The value of the DW_AT_ranges attribute is the offset of the
14736          address range list in the .debug_ranges section.  */
14737       unsigned long offset = (DW_UNSND (attr)
14738                               + (need_ranges_base ? cu->ranges_base : 0));
14739
14740       std::vector<blockrange> blockvec;
14741       dwarf2_ranges_process (offset, cu,
14742         [&] (CORE_ADDR start, CORE_ADDR end)
14743         {
14744           start += baseaddr;
14745           end += baseaddr;
14746           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14747           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14748           record_block_range (block, start, end - 1);
14749           blockvec.emplace_back (start, end);
14750         });
14751
14752       BLOCK_RANGES(block) = make_blockranges (objfile, blockvec);
14753     }
14754 }
14755
14756 /* Check whether the producer field indicates either of GCC < 4.6, or the
14757    Intel C/C++ compiler, and cache the result in CU.  */
14758
14759 static void
14760 check_producer (struct dwarf2_cu *cu)
14761 {
14762   int major, minor;
14763
14764   if (cu->producer == NULL)
14765     {
14766       /* For unknown compilers expect their behavior is DWARF version
14767          compliant.
14768
14769          GCC started to support .debug_types sections by -gdwarf-4 since
14770          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14771          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14772          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14773          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14774     }
14775   else if (producer_is_gcc (cu->producer, &major, &minor))
14776     {
14777       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14778       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14779     }
14780   else if (producer_is_icc (cu->producer, &major, &minor))
14781     cu->producer_is_icc_lt_14 = major < 14;
14782   else
14783     {
14784       /* For other non-GCC compilers, expect their behavior is DWARF version
14785          compliant.  */
14786     }
14787
14788   cu->checked_producer = 1;
14789 }
14790
14791 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14792    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14793    during 4.6.0 experimental.  */
14794
14795 static int
14796 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14797 {
14798   if (!cu->checked_producer)
14799     check_producer (cu);
14800
14801   return cu->producer_is_gxx_lt_4_6;
14802 }
14803
14804 /* Return the default accessibility type if it is not overriden by
14805    DW_AT_accessibility.  */
14806
14807 static enum dwarf_access_attribute
14808 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14809 {
14810   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14811     {
14812       /* The default DWARF 2 accessibility for members is public, the default
14813          accessibility for inheritance is private.  */
14814
14815       if (die->tag != DW_TAG_inheritance)
14816         return DW_ACCESS_public;
14817       else
14818         return DW_ACCESS_private;
14819     }
14820   else
14821     {
14822       /* DWARF 3+ defines the default accessibility a different way.  The same
14823          rules apply now for DW_TAG_inheritance as for the members and it only
14824          depends on the container kind.  */
14825
14826       if (die->parent->tag == DW_TAG_class_type)
14827         return DW_ACCESS_private;
14828       else
14829         return DW_ACCESS_public;
14830     }
14831 }
14832
14833 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14834    offset.  If the attribute was not found return 0, otherwise return
14835    1.  If it was found but could not properly be handled, set *OFFSET
14836    to 0.  */
14837
14838 static int
14839 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14840                              LONGEST *offset)
14841 {
14842   struct attribute *attr;
14843
14844   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14845   if (attr != NULL)
14846     {
14847       *offset = 0;
14848
14849       /* Note that we do not check for a section offset first here.
14850          This is because DW_AT_data_member_location is new in DWARF 4,
14851          so if we see it, we can assume that a constant form is really
14852          a constant and not a section offset.  */
14853       if (attr_form_is_constant (attr))
14854         *offset = dwarf2_get_attr_constant_value (attr, 0);
14855       else if (attr_form_is_section_offset (attr))
14856         dwarf2_complex_location_expr_complaint ();
14857       else if (attr_form_is_block (attr))
14858         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14859       else
14860         dwarf2_complex_location_expr_complaint ();
14861
14862       return 1;
14863     }
14864
14865   return 0;
14866 }
14867
14868 /* Add an aggregate field to the field list.  */
14869
14870 static void
14871 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14872                   struct dwarf2_cu *cu)
14873 {
14874   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14875   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14876   struct nextfield *new_field;
14877   struct attribute *attr;
14878   struct field *fp;
14879   const char *fieldname = "";
14880
14881   if (die->tag == DW_TAG_inheritance)
14882     {
14883       fip->baseclasses.emplace_back ();
14884       new_field = &fip->baseclasses.back ();
14885     }
14886   else
14887     {
14888       fip->fields.emplace_back ();
14889       new_field = &fip->fields.back ();
14890     }
14891
14892   fip->nfields++;
14893
14894   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14895   if (attr)
14896     new_field->accessibility = DW_UNSND (attr);
14897   else
14898     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14899   if (new_field->accessibility != DW_ACCESS_public)
14900     fip->non_public_fields = 1;
14901
14902   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14903   if (attr)
14904     new_field->virtuality = DW_UNSND (attr);
14905   else
14906     new_field->virtuality = DW_VIRTUALITY_none;
14907
14908   fp = &new_field->field;
14909
14910   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14911     {
14912       LONGEST offset;
14913
14914       /* Data member other than a C++ static data member.  */
14915
14916       /* Get type of field.  */
14917       fp->type = die_type (die, cu);
14918
14919       SET_FIELD_BITPOS (*fp, 0);
14920
14921       /* Get bit size of field (zero if none).  */
14922       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14923       if (attr)
14924         {
14925           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14926         }
14927       else
14928         {
14929           FIELD_BITSIZE (*fp) = 0;
14930         }
14931
14932       /* Get bit offset of field.  */
14933       if (handle_data_member_location (die, cu, &offset))
14934         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14935       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14936       if (attr)
14937         {
14938           if (gdbarch_bits_big_endian (gdbarch))
14939             {
14940               /* For big endian bits, the DW_AT_bit_offset gives the
14941                  additional bit offset from the MSB of the containing
14942                  anonymous object to the MSB of the field.  We don't
14943                  have to do anything special since we don't need to
14944                  know the size of the anonymous object.  */
14945               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
14946             }
14947           else
14948             {
14949               /* For little endian bits, compute the bit offset to the
14950                  MSB of the anonymous object, subtract off the number of
14951                  bits from the MSB of the field to the MSB of the
14952                  object, and then subtract off the number of bits of
14953                  the field itself.  The result is the bit offset of
14954                  the LSB of the field.  */
14955               int anonymous_size;
14956               int bit_offset = DW_UNSND (attr);
14957
14958               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14959               if (attr)
14960                 {
14961                   /* The size of the anonymous object containing
14962                      the bit field is explicit, so use the
14963                      indicated size (in bytes).  */
14964                   anonymous_size = DW_UNSND (attr);
14965                 }
14966               else
14967                 {
14968                   /* The size of the anonymous object containing
14969                      the bit field must be inferred from the type
14970                      attribute of the data member containing the
14971                      bit field.  */
14972                   anonymous_size = TYPE_LENGTH (fp->type);
14973                 }
14974               SET_FIELD_BITPOS (*fp,
14975                                 (FIELD_BITPOS (*fp)
14976                                  + anonymous_size * bits_per_byte
14977                                  - bit_offset - FIELD_BITSIZE (*fp)));
14978             }
14979         }
14980       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
14981       if (attr != NULL)
14982         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14983                                 + dwarf2_get_attr_constant_value (attr, 0)));
14984
14985       /* Get name of field.  */
14986       fieldname = dwarf2_name (die, cu);
14987       if (fieldname == NULL)
14988         fieldname = "";
14989
14990       /* The name is already allocated along with this objfile, so we don't
14991          need to duplicate it for the type.  */
14992       fp->name = fieldname;
14993
14994       /* Change accessibility for artificial fields (e.g. virtual table
14995          pointer or virtual base class pointer) to private.  */
14996       if (dwarf2_attr (die, DW_AT_artificial, cu))
14997         {
14998           FIELD_ARTIFICIAL (*fp) = 1;
14999           new_field->accessibility = DW_ACCESS_private;
15000           fip->non_public_fields = 1;
15001         }
15002     }
15003   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15004     {
15005       /* C++ static member.  */
15006
15007       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15008          is a declaration, but all versions of G++ as of this writing
15009          (so through at least 3.2.1) incorrectly generate
15010          DW_TAG_variable tags.  */
15011
15012       const char *physname;
15013
15014       /* Get name of field.  */
15015       fieldname = dwarf2_name (die, cu);
15016       if (fieldname == NULL)
15017         return;
15018
15019       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15020       if (attr
15021           /* Only create a symbol if this is an external value.
15022              new_symbol checks this and puts the value in the global symbol
15023              table, which we want.  If it is not external, new_symbol
15024              will try to put the value in cu->list_in_scope which is wrong.  */
15025           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15026         {
15027           /* A static const member, not much different than an enum as far as
15028              we're concerned, except that we can support more types.  */
15029           new_symbol (die, NULL, cu);
15030         }
15031
15032       /* Get physical name.  */
15033       physname = dwarf2_physname (fieldname, die, cu);
15034
15035       /* The name is already allocated along with this objfile, so we don't
15036          need to duplicate it for the type.  */
15037       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15038       FIELD_TYPE (*fp) = die_type (die, cu);
15039       FIELD_NAME (*fp) = fieldname;
15040     }
15041   else if (die->tag == DW_TAG_inheritance)
15042     {
15043       LONGEST offset;
15044
15045       /* C++ base class field.  */
15046       if (handle_data_member_location (die, cu, &offset))
15047         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15048       FIELD_BITSIZE (*fp) = 0;
15049       FIELD_TYPE (*fp) = die_type (die, cu);
15050       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15051     }
15052   else if (die->tag == DW_TAG_variant_part)
15053     {
15054       /* process_structure_scope will treat this DIE as a union.  */
15055       process_structure_scope (die, cu);
15056
15057       /* The variant part is relative to the start of the enclosing
15058          structure.  */
15059       SET_FIELD_BITPOS (*fp, 0);
15060       fp->type = get_die_type (die, cu);
15061       fp->artificial = 1;
15062       fp->name = "<<variant>>";
15063
15064       /* Normally a DW_TAG_variant_part won't have a size, but our
15065          representation requires one, so set it to the maximum of the
15066          child sizes.  */
15067       if (TYPE_LENGTH (fp->type) == 0)
15068         {
15069           unsigned max = 0;
15070           for (int i = 0; i < TYPE_NFIELDS (fp->type); ++i)
15071             if (TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i)) > max)
15072               max = TYPE_LENGTH (TYPE_FIELD_TYPE (fp->type, i));
15073           TYPE_LENGTH (fp->type) = max;
15074         }
15075     }
15076   else
15077     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15078 }
15079
15080 /* Can the type given by DIE define another type?  */
15081
15082 static bool
15083 type_can_define_types (const struct die_info *die)
15084 {
15085   switch (die->tag)
15086     {
15087     case DW_TAG_typedef:
15088     case DW_TAG_class_type:
15089     case DW_TAG_structure_type:
15090     case DW_TAG_union_type:
15091     case DW_TAG_enumeration_type:
15092       return true;
15093
15094     default:
15095       return false;
15096     }
15097 }
15098
15099 /* Add a type definition defined in the scope of the FIP's class.  */
15100
15101 static void
15102 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15103                       struct dwarf2_cu *cu)
15104 {
15105   struct decl_field fp;
15106   memset (&fp, 0, sizeof (fp));
15107
15108   gdb_assert (type_can_define_types (die));
15109
15110   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15111   fp.name = dwarf2_name (die, cu);
15112   fp.type = read_type_die (die, cu);
15113
15114   /* Save accessibility.  */
15115   enum dwarf_access_attribute accessibility;
15116   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15117   if (attr != NULL)
15118     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15119   else
15120     accessibility = dwarf2_default_access_attribute (die, cu);
15121   switch (accessibility)
15122     {
15123     case DW_ACCESS_public:
15124       /* The assumed value if neither private nor protected.  */
15125       break;
15126     case DW_ACCESS_private:
15127       fp.is_private = 1;
15128       break;
15129     case DW_ACCESS_protected:
15130       fp.is_protected = 1;
15131       break;
15132     default:
15133       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15134     }
15135
15136   if (die->tag == DW_TAG_typedef)
15137     fip->typedef_field_list.push_back (fp);
15138   else
15139     fip->nested_types_list.push_back (fp);
15140 }
15141
15142 /* Create the vector of fields, and attach it to the type.  */
15143
15144 static void
15145 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15146                               struct dwarf2_cu *cu)
15147 {
15148   int nfields = fip->nfields;
15149
15150   /* Record the field count, allocate space for the array of fields,
15151      and create blank accessibility bitfields if necessary.  */
15152   TYPE_NFIELDS (type) = nfields;
15153   TYPE_FIELDS (type) = (struct field *)
15154     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15155
15156   if (fip->non_public_fields && cu->language != language_ada)
15157     {
15158       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15159
15160       TYPE_FIELD_PRIVATE_BITS (type) =
15161         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15162       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15163
15164       TYPE_FIELD_PROTECTED_BITS (type) =
15165         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15166       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15167
15168       TYPE_FIELD_IGNORE_BITS (type) =
15169         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15170       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15171     }
15172
15173   /* If the type has baseclasses, allocate and clear a bit vector for
15174      TYPE_FIELD_VIRTUAL_BITS.  */
15175   if (!fip->baseclasses.empty () && cu->language != language_ada)
15176     {
15177       int num_bytes = B_BYTES (fip->baseclasses.size ());
15178       unsigned char *pointer;
15179
15180       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15181       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15182       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15183       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15184       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15185     }
15186
15187   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15188     {
15189       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15190
15191       for (int index = 0; index < nfields; ++index)
15192         {
15193           struct nextfield &field = fip->fields[index];
15194
15195           if (field.variant.is_discriminant)
15196             di->discriminant_index = index;
15197           else if (field.variant.default_branch)
15198             di->default_index = index;
15199           else
15200             di->discriminants[index] = field.variant.discriminant_value;
15201         }
15202     }
15203
15204   /* Copy the saved-up fields into the field vector.  */
15205   for (int i = 0; i < nfields; ++i)
15206     {
15207       struct nextfield &field
15208         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15209            : fip->fields[i - fip->baseclasses.size ()]);
15210
15211       TYPE_FIELD (type, i) = field.field;
15212       switch (field.accessibility)
15213         {
15214         case DW_ACCESS_private:
15215           if (cu->language != language_ada)
15216             SET_TYPE_FIELD_PRIVATE (type, i);
15217           break;
15218
15219         case DW_ACCESS_protected:
15220           if (cu->language != language_ada)
15221             SET_TYPE_FIELD_PROTECTED (type, i);
15222           break;
15223
15224         case DW_ACCESS_public:
15225           break;
15226
15227         default:
15228           /* Unknown accessibility.  Complain and treat it as public.  */
15229           {
15230             complaint (_("unsupported accessibility %d"),
15231                        field.accessibility);
15232           }
15233           break;
15234         }
15235       if (i < fip->baseclasses.size ())
15236         {
15237           switch (field.virtuality)
15238             {
15239             case DW_VIRTUALITY_virtual:
15240             case DW_VIRTUALITY_pure_virtual:
15241               if (cu->language == language_ada)
15242                 error (_("unexpected virtuality in component of Ada type"));
15243               SET_TYPE_FIELD_VIRTUAL (type, i);
15244               break;
15245             }
15246         }
15247     }
15248 }
15249
15250 /* Return true if this member function is a constructor, false
15251    otherwise.  */
15252
15253 static int
15254 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15255 {
15256   const char *fieldname;
15257   const char *type_name;
15258   int len;
15259
15260   if (die->parent == NULL)
15261     return 0;
15262
15263   if (die->parent->tag != DW_TAG_structure_type
15264       && die->parent->tag != DW_TAG_union_type
15265       && die->parent->tag != DW_TAG_class_type)
15266     return 0;
15267
15268   fieldname = dwarf2_name (die, cu);
15269   type_name = dwarf2_name (die->parent, cu);
15270   if (fieldname == NULL || type_name == NULL)
15271     return 0;
15272
15273   len = strlen (fieldname);
15274   return (strncmp (fieldname, type_name, len) == 0
15275           && (type_name[len] == '\0' || type_name[len] == '<'));
15276 }
15277
15278 /* Add a member function to the proper fieldlist.  */
15279
15280 static void
15281 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15282                       struct type *type, struct dwarf2_cu *cu)
15283 {
15284   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15285   struct attribute *attr;
15286   int i;
15287   struct fnfieldlist *flp = nullptr;
15288   struct fn_field *fnp;
15289   const char *fieldname;
15290   struct type *this_type;
15291   enum dwarf_access_attribute accessibility;
15292
15293   if (cu->language == language_ada)
15294     error (_("unexpected member function in Ada type"));
15295
15296   /* Get name of member function.  */
15297   fieldname = dwarf2_name (die, cu);
15298   if (fieldname == NULL)
15299     return;
15300
15301   /* Look up member function name in fieldlist.  */
15302   for (i = 0; i < fip->fnfieldlists.size (); i++)
15303     {
15304       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15305         {
15306           flp = &fip->fnfieldlists[i];
15307           break;
15308         }
15309     }
15310
15311   /* Create a new fnfieldlist if necessary.  */
15312   if (flp == nullptr)
15313     {
15314       fip->fnfieldlists.emplace_back ();
15315       flp = &fip->fnfieldlists.back ();
15316       flp->name = fieldname;
15317       i = fip->fnfieldlists.size () - 1;
15318     }
15319
15320   /* Create a new member function field and add it to the vector of
15321      fnfieldlists.  */
15322   flp->fnfields.emplace_back ();
15323   fnp = &flp->fnfields.back ();
15324
15325   /* Delay processing of the physname until later.  */
15326   if (cu->language == language_cplus)
15327     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15328                         die, cu);
15329   else
15330     {
15331       const char *physname = dwarf2_physname (fieldname, die, cu);
15332       fnp->physname = physname ? physname : "";
15333     }
15334
15335   fnp->type = alloc_type (objfile);
15336   this_type = read_type_die (die, cu);
15337   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15338     {
15339       int nparams = TYPE_NFIELDS (this_type);
15340
15341       /* TYPE is the domain of this method, and THIS_TYPE is the type
15342            of the method itself (TYPE_CODE_METHOD).  */
15343       smash_to_method_type (fnp->type, type,
15344                             TYPE_TARGET_TYPE (this_type),
15345                             TYPE_FIELDS (this_type),
15346                             TYPE_NFIELDS (this_type),
15347                             TYPE_VARARGS (this_type));
15348
15349       /* Handle static member functions.
15350          Dwarf2 has no clean way to discern C++ static and non-static
15351          member functions.  G++ helps GDB by marking the first
15352          parameter for non-static member functions (which is the this
15353          pointer) as artificial.  We obtain this information from
15354          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15355       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15356         fnp->voffset = VOFFSET_STATIC;
15357     }
15358   else
15359     complaint (_("member function type missing for '%s'"),
15360                dwarf2_full_name (fieldname, die, cu));
15361
15362   /* Get fcontext from DW_AT_containing_type if present.  */
15363   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15364     fnp->fcontext = die_containing_type (die, cu);
15365
15366   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15367      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15368
15369   /* Get accessibility.  */
15370   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15371   if (attr)
15372     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15373   else
15374     accessibility = dwarf2_default_access_attribute (die, cu);
15375   switch (accessibility)
15376     {
15377     case DW_ACCESS_private:
15378       fnp->is_private = 1;
15379       break;
15380     case DW_ACCESS_protected:
15381       fnp->is_protected = 1;
15382       break;
15383     }
15384
15385   /* Check for artificial methods.  */
15386   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15387   if (attr && DW_UNSND (attr) != 0)
15388     fnp->is_artificial = 1;
15389
15390   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15391
15392   /* Get index in virtual function table if it is a virtual member
15393      function.  For older versions of GCC, this is an offset in the
15394      appropriate virtual table, as specified by DW_AT_containing_type.
15395      For everyone else, it is an expression to be evaluated relative
15396      to the object address.  */
15397
15398   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15399   if (attr)
15400     {
15401       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15402         {
15403           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15404             {
15405               /* Old-style GCC.  */
15406               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15407             }
15408           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15409                    || (DW_BLOCK (attr)->size > 1
15410                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15411                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15412             {
15413               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15414               if ((fnp->voffset % cu->header.addr_size) != 0)
15415                 dwarf2_complex_location_expr_complaint ();
15416               else
15417                 fnp->voffset /= cu->header.addr_size;
15418               fnp->voffset += 2;
15419             }
15420           else
15421             dwarf2_complex_location_expr_complaint ();
15422
15423           if (!fnp->fcontext)
15424             {
15425               /* If there is no `this' field and no DW_AT_containing_type,
15426                  we cannot actually find a base class context for the
15427                  vtable!  */
15428               if (TYPE_NFIELDS (this_type) == 0
15429                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15430                 {
15431                   complaint (_("cannot determine context for virtual member "
15432                                "function \"%s\" (offset %s)"),
15433                              fieldname, sect_offset_str (die->sect_off));
15434                 }
15435               else
15436                 {
15437                   fnp->fcontext
15438                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15439                 }
15440             }
15441         }
15442       else if (attr_form_is_section_offset (attr))
15443         {
15444           dwarf2_complex_location_expr_complaint ();
15445         }
15446       else
15447         {
15448           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15449                                                  fieldname);
15450         }
15451     }
15452   else
15453     {
15454       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15455       if (attr && DW_UNSND (attr))
15456         {
15457           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15458           complaint (_("Member function \"%s\" (offset %s) is virtual "
15459                        "but the vtable offset is not specified"),
15460                      fieldname, sect_offset_str (die->sect_off));
15461           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15462           TYPE_CPLUS_DYNAMIC (type) = 1;
15463         }
15464     }
15465 }
15466
15467 /* Create the vector of member function fields, and attach it to the type.  */
15468
15469 static void
15470 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15471                                  struct dwarf2_cu *cu)
15472 {
15473   if (cu->language == language_ada)
15474     error (_("unexpected member functions in Ada type"));
15475
15476   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15477   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15478     TYPE_ALLOC (type,
15479                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15480
15481   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15482     {
15483       struct fnfieldlist &nf = fip->fnfieldlists[i];
15484       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15485
15486       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15487       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15488       fn_flp->fn_fields = (struct fn_field *)
15489         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15490
15491       for (int k = 0; k < nf.fnfields.size (); ++k)
15492         fn_flp->fn_fields[k] = nf.fnfields[k];
15493     }
15494
15495   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15496 }
15497
15498 /* Returns non-zero if NAME is the name of a vtable member in CU's
15499    language, zero otherwise.  */
15500 static int
15501 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15502 {
15503   static const char vptr[] = "_vptr";
15504
15505   /* Look for the C++ form of the vtable.  */
15506   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15507     return 1;
15508
15509   return 0;
15510 }
15511
15512 /* GCC outputs unnamed structures that are really pointers to member
15513    functions, with the ABI-specified layout.  If TYPE describes
15514    such a structure, smash it into a member function type.
15515
15516    GCC shouldn't do this; it should just output pointer to member DIEs.
15517    This is GCC PR debug/28767.  */
15518
15519 static void
15520 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15521 {
15522   struct type *pfn_type, *self_type, *new_type;
15523
15524   /* Check for a structure with no name and two children.  */
15525   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15526     return;
15527
15528   /* Check for __pfn and __delta members.  */
15529   if (TYPE_FIELD_NAME (type, 0) == NULL
15530       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15531       || TYPE_FIELD_NAME (type, 1) == NULL
15532       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15533     return;
15534
15535   /* Find the type of the method.  */
15536   pfn_type = TYPE_FIELD_TYPE (type, 0);
15537   if (pfn_type == NULL
15538       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15539       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15540     return;
15541
15542   /* Look for the "this" argument.  */
15543   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15544   if (TYPE_NFIELDS (pfn_type) == 0
15545       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15546       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15547     return;
15548
15549   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15550   new_type = alloc_type (objfile);
15551   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15552                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15553                         TYPE_VARARGS (pfn_type));
15554   smash_to_methodptr_type (type, new_type);
15555 }
15556
15557 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15558    appropriate error checking and issuing complaints if there is a
15559    problem.  */
15560
15561 static ULONGEST
15562 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15563 {
15564   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15565
15566   if (attr == nullptr)
15567     return 0;
15568
15569   if (!attr_form_is_constant (attr))
15570     {
15571       complaint (_("DW_AT_alignment must have constant form"
15572                    " - DIE at %s [in module %s]"),
15573                  sect_offset_str (die->sect_off),
15574                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15575       return 0;
15576     }
15577
15578   ULONGEST align;
15579   if (attr->form == DW_FORM_sdata)
15580     {
15581       LONGEST val = DW_SND (attr);
15582       if (val < 0)
15583         {
15584           complaint (_("DW_AT_alignment value must not be negative"
15585                        " - DIE at %s [in module %s]"),
15586                      sect_offset_str (die->sect_off),
15587                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15588           return 0;
15589         }
15590       align = val;
15591     }
15592   else
15593     align = DW_UNSND (attr);
15594
15595   if (align == 0)
15596     {
15597       complaint (_("DW_AT_alignment value must not be zero"
15598                    " - DIE at %s [in module %s]"),
15599                  sect_offset_str (die->sect_off),
15600                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15601       return 0;
15602     }
15603   if ((align & (align - 1)) != 0)
15604     {
15605       complaint (_("DW_AT_alignment value must be a power of 2"
15606                    " - DIE at %s [in module %s]"),
15607                  sect_offset_str (die->sect_off),
15608                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15609       return 0;
15610     }
15611
15612   return align;
15613 }
15614
15615 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15616    the alignment for TYPE.  */
15617
15618 static void
15619 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15620                      struct type *type)
15621 {
15622   if (!set_type_align (type, get_alignment (cu, die)))
15623     complaint (_("DW_AT_alignment value too large"
15624                  " - DIE at %s [in module %s]"),
15625                sect_offset_str (die->sect_off),
15626                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15627 }
15628
15629 /* Called when we find the DIE that starts a structure or union scope
15630    (definition) to create a type for the structure or union.  Fill in
15631    the type's name and general properties; the members will not be
15632    processed until process_structure_scope.  A symbol table entry for
15633    the type will also not be done until process_structure_scope (assuming
15634    the type has a name).
15635
15636    NOTE: we need to call these functions regardless of whether or not the
15637    DIE has a DW_AT_name attribute, since it might be an anonymous
15638    structure or union.  This gets the type entered into our set of
15639    user defined types.  */
15640
15641 static struct type *
15642 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15643 {
15644   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15645   struct type *type;
15646   struct attribute *attr;
15647   const char *name;
15648
15649   /* If the definition of this type lives in .debug_types, read that type.
15650      Don't follow DW_AT_specification though, that will take us back up
15651      the chain and we want to go down.  */
15652   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15653   if (attr)
15654     {
15655       type = get_DW_AT_signature_type (die, attr, cu);
15656
15657       /* The type's CU may not be the same as CU.
15658          Ensure TYPE is recorded with CU in die_type_hash.  */
15659       return set_die_type (die, type, cu);
15660     }
15661
15662   type = alloc_type (objfile);
15663   INIT_CPLUS_SPECIFIC (type);
15664
15665   name = dwarf2_name (die, cu);
15666   if (name != NULL)
15667     {
15668       if (cu->language == language_cplus
15669           || cu->language == language_d
15670           || cu->language == language_rust)
15671         {
15672           const char *full_name = dwarf2_full_name (name, die, cu);
15673
15674           /* dwarf2_full_name might have already finished building the DIE's
15675              type.  If so, there is no need to continue.  */
15676           if (get_die_type (die, cu) != NULL)
15677             return get_die_type (die, cu);
15678
15679           TYPE_NAME (type) = full_name;
15680         }
15681       else
15682         {
15683           /* The name is already allocated along with this objfile, so
15684              we don't need to duplicate it for the type.  */
15685           TYPE_NAME (type) = name;
15686         }
15687     }
15688
15689   if (die->tag == DW_TAG_structure_type)
15690     {
15691       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15692     }
15693   else if (die->tag == DW_TAG_union_type)
15694     {
15695       TYPE_CODE (type) = TYPE_CODE_UNION;
15696     }
15697   else if (die->tag == DW_TAG_variant_part)
15698     {
15699       TYPE_CODE (type) = TYPE_CODE_UNION;
15700       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15701     }
15702   else
15703     {
15704       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15705     }
15706
15707   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15708     TYPE_DECLARED_CLASS (type) = 1;
15709
15710   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15711   if (attr)
15712     {
15713       if (attr_form_is_constant (attr))
15714         TYPE_LENGTH (type) = DW_UNSND (attr);
15715       else
15716         {
15717           /* For the moment, dynamic type sizes are not supported
15718              by GDB's struct type.  The actual size is determined
15719              on-demand when resolving the type of a given object,
15720              so set the type's length to zero for now.  Otherwise,
15721              we record an expression as the length, and that expression
15722              could lead to a very large value, which could eventually
15723              lead to us trying to allocate that much memory when creating
15724              a value of that type.  */
15725           TYPE_LENGTH (type) = 0;
15726         }
15727     }
15728   else
15729     {
15730       TYPE_LENGTH (type) = 0;
15731     }
15732
15733   maybe_set_alignment (cu, die, type);
15734
15735   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15736     {
15737       /* ICC<14 does not output the required DW_AT_declaration on
15738          incomplete types, but gives them a size of zero.  */
15739       TYPE_STUB (type) = 1;
15740     }
15741   else
15742     TYPE_STUB_SUPPORTED (type) = 1;
15743
15744   if (die_is_declaration (die, cu))
15745     TYPE_STUB (type) = 1;
15746   else if (attr == NULL && die->child == NULL
15747            && producer_is_realview (cu->producer))
15748     /* RealView does not output the required DW_AT_declaration
15749        on incomplete types.  */
15750     TYPE_STUB (type) = 1;
15751
15752   /* We need to add the type field to the die immediately so we don't
15753      infinitely recurse when dealing with pointers to the structure
15754      type within the structure itself.  */
15755   set_die_type (die, type, cu);
15756
15757   /* set_die_type should be already done.  */
15758   set_descriptive_type (type, die, cu);
15759
15760   return type;
15761 }
15762
15763 /* A helper for process_structure_scope that handles a single member
15764    DIE.  */
15765
15766 static void
15767 handle_struct_member_die (struct die_info *child_die, struct type *type,
15768                           struct field_info *fi,
15769                           std::vector<struct symbol *> *template_args,
15770                           struct dwarf2_cu *cu)
15771 {
15772   if (child_die->tag == DW_TAG_member
15773       || child_die->tag == DW_TAG_variable
15774       || child_die->tag == DW_TAG_variant_part)
15775     {
15776       /* NOTE: carlton/2002-11-05: A C++ static data member
15777          should be a DW_TAG_member that is a declaration, but
15778          all versions of G++ as of this writing (so through at
15779          least 3.2.1) incorrectly generate DW_TAG_variable
15780          tags for them instead.  */
15781       dwarf2_add_field (fi, child_die, cu);
15782     }
15783   else if (child_die->tag == DW_TAG_subprogram)
15784     {
15785       /* Rust doesn't have member functions in the C++ sense.
15786          However, it does emit ordinary functions as children
15787          of a struct DIE.  */
15788       if (cu->language == language_rust)
15789         read_func_scope (child_die, cu);
15790       else
15791         {
15792           /* C++ member function.  */
15793           dwarf2_add_member_fn (fi, child_die, type, cu);
15794         }
15795     }
15796   else if (child_die->tag == DW_TAG_inheritance)
15797     {
15798       /* C++ base class field.  */
15799       dwarf2_add_field (fi, child_die, cu);
15800     }
15801   else if (type_can_define_types (child_die))
15802     dwarf2_add_type_defn (fi, child_die, cu);
15803   else if (child_die->tag == DW_TAG_template_type_param
15804            || child_die->tag == DW_TAG_template_value_param)
15805     {
15806       struct symbol *arg = new_symbol (child_die, NULL, cu);
15807
15808       if (arg != NULL)
15809         template_args->push_back (arg);
15810     }
15811   else if (child_die->tag == DW_TAG_variant)
15812     {
15813       /* In a variant we want to get the discriminant and also add a
15814          field for our sole member child.  */
15815       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15816
15817       for (struct die_info *variant_child = child_die->child;
15818            variant_child != NULL;
15819            variant_child = sibling_die (variant_child))
15820         {
15821           if (variant_child->tag == DW_TAG_member)
15822             {
15823               handle_struct_member_die (variant_child, type, fi,
15824                                         template_args, cu);
15825               /* Only handle the one.  */
15826               break;
15827             }
15828         }
15829
15830       /* We don't handle this but we might as well report it if we see
15831          it.  */
15832       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15833           complaint (_("DW_AT_discr_list is not supported yet"
15834                        " - DIE at %s [in module %s]"),
15835                      sect_offset_str (child_die->sect_off),
15836                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15837
15838       /* The first field was just added, so we can stash the
15839          discriminant there.  */
15840       gdb_assert (!fi->fields.empty ());
15841       if (discr == NULL)
15842         fi->fields.back ().variant.default_branch = true;
15843       else
15844         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15845     }
15846 }
15847
15848 /* Finish creating a structure or union type, including filling in
15849    its members and creating a symbol for it.  */
15850
15851 static void
15852 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15853 {
15854   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15855   struct die_info *child_die;
15856   struct type *type;
15857
15858   type = get_die_type (die, cu);
15859   if (type == NULL)
15860     type = read_structure_type (die, cu);
15861
15862   /* When reading a DW_TAG_variant_part, we need to notice when we
15863      read the discriminant member, so we can record it later in the
15864      discriminant_info.  */
15865   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15866   sect_offset discr_offset;
15867
15868   if (is_variant_part)
15869     {
15870       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15871       if (discr == NULL)
15872         {
15873           /* Maybe it's a univariant form, an extension we support.
15874              In this case arrange not to check the offset.  */
15875           is_variant_part = false;
15876         }
15877       else if (attr_form_is_ref (discr))
15878         {
15879           struct dwarf2_cu *target_cu = cu;
15880           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15881
15882           discr_offset = target_die->sect_off;
15883         }
15884       else
15885         {
15886           complaint (_("DW_AT_discr does not have DIE reference form"
15887                        " - DIE at %s [in module %s]"),
15888                      sect_offset_str (die->sect_off),
15889                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15890           is_variant_part = false;
15891         }
15892     }
15893
15894   if (die->child != NULL && ! die_is_declaration (die, cu))
15895     {
15896       struct field_info fi;
15897       std::vector<struct symbol *> template_args;
15898
15899       child_die = die->child;
15900
15901       while (child_die && child_die->tag)
15902         {
15903           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15904
15905           if (is_variant_part && discr_offset == child_die->sect_off)
15906             fi.fields.back ().variant.is_discriminant = true;
15907
15908           child_die = sibling_die (child_die);
15909         }
15910
15911       /* Attach template arguments to type.  */
15912       if (!template_args.empty ())
15913         {
15914           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15915           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15916           TYPE_TEMPLATE_ARGUMENTS (type)
15917             = XOBNEWVEC (&objfile->objfile_obstack,
15918                          struct symbol *,
15919                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15920           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15921                   template_args.data (),
15922                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15923                    * sizeof (struct symbol *)));
15924         }
15925
15926       /* Attach fields and member functions to the type.  */
15927       if (fi.nfields)
15928         dwarf2_attach_fields_to_type (&fi, type, cu);
15929       if (!fi.fnfieldlists.empty ())
15930         {
15931           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15932
15933           /* Get the type which refers to the base class (possibly this
15934              class itself) which contains the vtable pointer for the current
15935              class from the DW_AT_containing_type attribute.  This use of
15936              DW_AT_containing_type is a GNU extension.  */
15937
15938           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15939             {
15940               struct type *t = die_containing_type (die, cu);
15941
15942               set_type_vptr_basetype (type, t);
15943               if (type == t)
15944                 {
15945                   int i;
15946
15947                   /* Our own class provides vtbl ptr.  */
15948                   for (i = TYPE_NFIELDS (t) - 1;
15949                        i >= TYPE_N_BASECLASSES (t);
15950                        --i)
15951                     {
15952                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15953
15954                       if (is_vtable_name (fieldname, cu))
15955                         {
15956                           set_type_vptr_fieldno (type, i);
15957                           break;
15958                         }
15959                     }
15960
15961                   /* Complain if virtual function table field not found.  */
15962                   if (i < TYPE_N_BASECLASSES (t))
15963                     complaint (_("virtual function table pointer "
15964                                  "not found when defining class '%s'"),
15965                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
15966                 }
15967               else
15968                 {
15969                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15970                 }
15971             }
15972           else if (cu->producer
15973                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15974             {
15975               /* The IBM XLC compiler does not provide direct indication
15976                  of the containing type, but the vtable pointer is
15977                  always named __vfp.  */
15978
15979               int i;
15980
15981               for (i = TYPE_NFIELDS (type) - 1;
15982                    i >= TYPE_N_BASECLASSES (type);
15983                    --i)
15984                 {
15985                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15986                     {
15987                       set_type_vptr_fieldno (type, i);
15988                       set_type_vptr_basetype (type, type);
15989                       break;
15990                     }
15991                 }
15992             }
15993         }
15994
15995       /* Copy fi.typedef_field_list linked list elements content into the
15996          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15997       if (!fi.typedef_field_list.empty ())
15998         {
15999           int count = fi.typedef_field_list.size ();
16000
16001           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16002           TYPE_TYPEDEF_FIELD_ARRAY (type)
16003             = ((struct decl_field *)
16004                TYPE_ALLOC (type,
16005                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16006           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16007
16008           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16009             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16010         }
16011
16012       /* Copy fi.nested_types_list linked list elements content into the
16013          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16014       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16015         {
16016           int count = fi.nested_types_list.size ();
16017
16018           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16019           TYPE_NESTED_TYPES_ARRAY (type)
16020             = ((struct decl_field *)
16021                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16022           TYPE_NESTED_TYPES_COUNT (type) = count;
16023
16024           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16025             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16026         }
16027     }
16028
16029   quirk_gcc_member_function_pointer (type, objfile);
16030   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16031     cu->rust_unions.push_back (type);
16032
16033   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16034      snapshots) has been known to create a die giving a declaration
16035      for a class that has, as a child, a die giving a definition for a
16036      nested class.  So we have to process our children even if the
16037      current die is a declaration.  Normally, of course, a declaration
16038      won't have any children at all.  */
16039
16040   child_die = die->child;
16041
16042   while (child_die != NULL && child_die->tag)
16043     {
16044       if (child_die->tag == DW_TAG_member
16045           || child_die->tag == DW_TAG_variable
16046           || child_die->tag == DW_TAG_inheritance
16047           || child_die->tag == DW_TAG_template_value_param
16048           || child_die->tag == DW_TAG_template_type_param)
16049         {
16050           /* Do nothing.  */
16051         }
16052       else
16053         process_die (child_die, cu);
16054
16055       child_die = sibling_die (child_die);
16056     }
16057
16058   /* Do not consider external references.  According to the DWARF standard,
16059      these DIEs are identified by the fact that they have no byte_size
16060      attribute, and a declaration attribute.  */
16061   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16062       || !die_is_declaration (die, cu))
16063     new_symbol (die, type, cu);
16064 }
16065
16066 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16067    update TYPE using some information only available in DIE's children.  */
16068
16069 static void
16070 update_enumeration_type_from_children (struct die_info *die,
16071                                        struct type *type,
16072                                        struct dwarf2_cu *cu)
16073 {
16074   struct die_info *child_die;
16075   int unsigned_enum = 1;
16076   int flag_enum = 1;
16077   ULONGEST mask = 0;
16078
16079   auto_obstack obstack;
16080
16081   for (child_die = die->child;
16082        child_die != NULL && child_die->tag;
16083        child_die = sibling_die (child_die))
16084     {
16085       struct attribute *attr;
16086       LONGEST value;
16087       const gdb_byte *bytes;
16088       struct dwarf2_locexpr_baton *baton;
16089       const char *name;
16090
16091       if (child_die->tag != DW_TAG_enumerator)
16092         continue;
16093
16094       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16095       if (attr == NULL)
16096         continue;
16097
16098       name = dwarf2_name (child_die, cu);
16099       if (name == NULL)
16100         name = "<anonymous enumerator>";
16101
16102       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16103                                &value, &bytes, &baton);
16104       if (value < 0)
16105         {
16106           unsigned_enum = 0;
16107           flag_enum = 0;
16108         }
16109       else if ((mask & value) != 0)
16110         flag_enum = 0;
16111       else
16112         mask |= value;
16113
16114       /* If we already know that the enum type is neither unsigned, nor
16115          a flag type, no need to look at the rest of the enumerates.  */
16116       if (!unsigned_enum && !flag_enum)
16117         break;
16118     }
16119
16120   if (unsigned_enum)
16121     TYPE_UNSIGNED (type) = 1;
16122   if (flag_enum)
16123     TYPE_FLAG_ENUM (type) = 1;
16124 }
16125
16126 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16127    complete the type's fields yet, or create any symbols.  */
16128
16129 static struct type *
16130 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16131 {
16132   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16133   struct type *type;
16134   struct attribute *attr;
16135   const char *name;
16136
16137   /* If the definition of this type lives in .debug_types, read that type.
16138      Don't follow DW_AT_specification though, that will take us back up
16139      the chain and we want to go down.  */
16140   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16141   if (attr)
16142     {
16143       type = get_DW_AT_signature_type (die, attr, cu);
16144
16145       /* The type's CU may not be the same as CU.
16146          Ensure TYPE is recorded with CU in die_type_hash.  */
16147       return set_die_type (die, type, cu);
16148     }
16149
16150   type = alloc_type (objfile);
16151
16152   TYPE_CODE (type) = TYPE_CODE_ENUM;
16153   name = dwarf2_full_name (NULL, die, cu);
16154   if (name != NULL)
16155     TYPE_NAME (type) = name;
16156
16157   attr = dwarf2_attr (die, DW_AT_type, cu);
16158   if (attr != NULL)
16159     {
16160       struct type *underlying_type = die_type (die, cu);
16161
16162       TYPE_TARGET_TYPE (type) = underlying_type;
16163     }
16164
16165   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16166   if (attr)
16167     {
16168       TYPE_LENGTH (type) = DW_UNSND (attr);
16169     }
16170   else
16171     {
16172       TYPE_LENGTH (type) = 0;
16173     }
16174
16175   maybe_set_alignment (cu, die, type);
16176
16177   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16178      declared as private in the package spec, and then defined only
16179      inside the package body.  Such types are known as Taft Amendment
16180      Types.  When another package uses such a type, an incomplete DIE
16181      may be generated by the compiler.  */
16182   if (die_is_declaration (die, cu))
16183     TYPE_STUB (type) = 1;
16184
16185   /* Finish the creation of this type by using the enum's children.
16186      We must call this even when the underlying type has been provided
16187      so that we can determine if we're looking at a "flag" enum.  */
16188   update_enumeration_type_from_children (die, type, cu);
16189
16190   /* If this type has an underlying type that is not a stub, then we
16191      may use its attributes.  We always use the "unsigned" attribute
16192      in this situation, because ordinarily we guess whether the type
16193      is unsigned -- but the guess can be wrong and the underlying type
16194      can tell us the reality.  However, we defer to a local size
16195      attribute if one exists, because this lets the compiler override
16196      the underlying type if needed.  */
16197   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16198     {
16199       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16200       if (TYPE_LENGTH (type) == 0)
16201         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16202       if (TYPE_RAW_ALIGN (type) == 0
16203           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16204         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16205     }
16206
16207   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16208
16209   return set_die_type (die, type, cu);
16210 }
16211
16212 /* Given a pointer to a die which begins an enumeration, process all
16213    the dies that define the members of the enumeration, and create the
16214    symbol for the enumeration type.
16215
16216    NOTE: We reverse the order of the element list.  */
16217
16218 static void
16219 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16220 {
16221   struct type *this_type;
16222
16223   this_type = get_die_type (die, cu);
16224   if (this_type == NULL)
16225     this_type = read_enumeration_type (die, cu);
16226
16227   if (die->child != NULL)
16228     {
16229       struct die_info *child_die;
16230       struct symbol *sym;
16231       struct field *fields = NULL;
16232       int num_fields = 0;
16233       const char *name;
16234
16235       child_die = die->child;
16236       while (child_die && child_die->tag)
16237         {
16238           if (child_die->tag != DW_TAG_enumerator)
16239             {
16240               process_die (child_die, cu);
16241             }
16242           else
16243             {
16244               name = dwarf2_name (child_die, cu);
16245               if (name)
16246                 {
16247                   sym = new_symbol (child_die, this_type, cu);
16248
16249                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16250                     {
16251                       fields = (struct field *)
16252                         xrealloc (fields,
16253                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16254                                   * sizeof (struct field));
16255                     }
16256
16257                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16258                   FIELD_TYPE (fields[num_fields]) = NULL;
16259                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16260                   FIELD_BITSIZE (fields[num_fields]) = 0;
16261
16262                   num_fields++;
16263                 }
16264             }
16265
16266           child_die = sibling_die (child_die);
16267         }
16268
16269       if (num_fields)
16270         {
16271           TYPE_NFIELDS (this_type) = num_fields;
16272           TYPE_FIELDS (this_type) = (struct field *)
16273             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16274           memcpy (TYPE_FIELDS (this_type), fields,
16275                   sizeof (struct field) * num_fields);
16276           xfree (fields);
16277         }
16278     }
16279
16280   /* If we are reading an enum from a .debug_types unit, and the enum
16281      is a declaration, and the enum is not the signatured type in the
16282      unit, then we do not want to add a symbol for it.  Adding a
16283      symbol would in some cases obscure the true definition of the
16284      enum, giving users an incomplete type when the definition is
16285      actually available.  Note that we do not want to do this for all
16286      enums which are just declarations, because C++0x allows forward
16287      enum declarations.  */
16288   if (cu->per_cu->is_debug_types
16289       && die_is_declaration (die, cu))
16290     {
16291       struct signatured_type *sig_type;
16292
16293       sig_type = (struct signatured_type *) cu->per_cu;
16294       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16295       if (sig_type->type_offset_in_section != die->sect_off)
16296         return;
16297     }
16298
16299   new_symbol (die, this_type, cu);
16300 }
16301
16302 /* Extract all information from a DW_TAG_array_type DIE and put it in
16303    the DIE's type field.  For now, this only handles one dimensional
16304    arrays.  */
16305
16306 static struct type *
16307 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16308 {
16309   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16310   struct die_info *child_die;
16311   struct type *type;
16312   struct type *element_type, *range_type, *index_type;
16313   struct attribute *attr;
16314   const char *name;
16315   struct dynamic_prop *byte_stride_prop = NULL;
16316   unsigned int bit_stride = 0;
16317
16318   element_type = die_type (die, cu);
16319
16320   /* The die_type call above may have already set the type for this DIE.  */
16321   type = get_die_type (die, cu);
16322   if (type)
16323     return type;
16324
16325   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16326   if (attr != NULL)
16327     {
16328       int stride_ok;
16329
16330       byte_stride_prop
16331         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16332       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16333       if (!stride_ok)
16334         {
16335           complaint (_("unable to read array DW_AT_byte_stride "
16336                        " - DIE at %s [in module %s]"),
16337                      sect_offset_str (die->sect_off),
16338                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16339           /* Ignore this attribute.  We will likely not be able to print
16340              arrays of this type correctly, but there is little we can do
16341              to help if we cannot read the attribute's value.  */
16342           byte_stride_prop = NULL;
16343         }
16344     }
16345
16346   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16347   if (attr != NULL)
16348     bit_stride = DW_UNSND (attr);
16349
16350   /* Irix 6.2 native cc creates array types without children for
16351      arrays with unspecified length.  */
16352   if (die->child == NULL)
16353     {
16354       index_type = objfile_type (objfile)->builtin_int;
16355       range_type = create_static_range_type (NULL, index_type, 0, -1);
16356       type = create_array_type_with_stride (NULL, element_type, range_type,
16357                                             byte_stride_prop, bit_stride);
16358       return set_die_type (die, type, cu);
16359     }
16360
16361   std::vector<struct type *> range_types;
16362   child_die = die->child;
16363   while (child_die && child_die->tag)
16364     {
16365       if (child_die->tag == DW_TAG_subrange_type)
16366         {
16367           struct type *child_type = read_type_die (child_die, cu);
16368
16369           if (child_type != NULL)
16370             {
16371               /* The range type was succesfully read.  Save it for the
16372                  array type creation.  */
16373               range_types.push_back (child_type);
16374             }
16375         }
16376       child_die = sibling_die (child_die);
16377     }
16378
16379   /* Dwarf2 dimensions are output from left to right, create the
16380      necessary array types in backwards order.  */
16381
16382   type = element_type;
16383
16384   if (read_array_order (die, cu) == DW_ORD_col_major)
16385     {
16386       int i = 0;
16387
16388       while (i < range_types.size ())
16389         type = create_array_type_with_stride (NULL, type, range_types[i++],
16390                                               byte_stride_prop, bit_stride);
16391     }
16392   else
16393     {
16394       size_t ndim = range_types.size ();
16395       while (ndim-- > 0)
16396         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16397                                               byte_stride_prop, bit_stride);
16398     }
16399
16400   /* Understand Dwarf2 support for vector types (like they occur on
16401      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16402      array type.  This is not part of the Dwarf2/3 standard yet, but a
16403      custom vendor extension.  The main difference between a regular
16404      array and the vector variant is that vectors are passed by value
16405      to functions.  */
16406   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16407   if (attr)
16408     make_vector_type (type);
16409
16410   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16411      implementation may choose to implement triple vectors using this
16412      attribute.  */
16413   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16414   if (attr)
16415     {
16416       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16417         TYPE_LENGTH (type) = DW_UNSND (attr);
16418       else
16419         complaint (_("DW_AT_byte_size for array type smaller "
16420                      "than the total size of elements"));
16421     }
16422
16423   name = dwarf2_name (die, cu);
16424   if (name)
16425     TYPE_NAME (type) = name;
16426
16427   maybe_set_alignment (cu, die, type);
16428
16429   /* Install the type in the die.  */
16430   set_die_type (die, type, cu);
16431
16432   /* set_die_type should be already done.  */
16433   set_descriptive_type (type, die, cu);
16434
16435   return type;
16436 }
16437
16438 static enum dwarf_array_dim_ordering
16439 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16440 {
16441   struct attribute *attr;
16442
16443   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16444
16445   if (attr)
16446     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16447
16448   /* GNU F77 is a special case, as at 08/2004 array type info is the
16449      opposite order to the dwarf2 specification, but data is still
16450      laid out as per normal fortran.
16451
16452      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16453      version checking.  */
16454
16455   if (cu->language == language_fortran
16456       && cu->producer && strstr (cu->producer, "GNU F77"))
16457     {
16458       return DW_ORD_row_major;
16459     }
16460
16461   switch (cu->language_defn->la_array_ordering)
16462     {
16463     case array_column_major:
16464       return DW_ORD_col_major;
16465     case array_row_major:
16466     default:
16467       return DW_ORD_row_major;
16468     };
16469 }
16470
16471 /* Extract all information from a DW_TAG_set_type DIE and put it in
16472    the DIE's type field.  */
16473
16474 static struct type *
16475 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16476 {
16477   struct type *domain_type, *set_type;
16478   struct attribute *attr;
16479
16480   domain_type = die_type (die, cu);
16481
16482   /* The die_type call above may have already set the type for this DIE.  */
16483   set_type = get_die_type (die, cu);
16484   if (set_type)
16485     return set_type;
16486
16487   set_type = create_set_type (NULL, domain_type);
16488
16489   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16490   if (attr)
16491     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16492
16493   maybe_set_alignment (cu, die, set_type);
16494
16495   return set_die_type (die, set_type, cu);
16496 }
16497
16498 /* A helper for read_common_block that creates a locexpr baton.
16499    SYM is the symbol which we are marking as computed.
16500    COMMON_DIE is the DIE for the common block.
16501    COMMON_LOC is the location expression attribute for the common
16502    block itself.
16503    MEMBER_LOC is the location expression attribute for the particular
16504    member of the common block that we are processing.
16505    CU is the CU from which the above come.  */
16506
16507 static void
16508 mark_common_block_symbol_computed (struct symbol *sym,
16509                                    struct die_info *common_die,
16510                                    struct attribute *common_loc,
16511                                    struct attribute *member_loc,
16512                                    struct dwarf2_cu *cu)
16513 {
16514   struct dwarf2_per_objfile *dwarf2_per_objfile
16515     = cu->per_cu->dwarf2_per_objfile;
16516   struct objfile *objfile = dwarf2_per_objfile->objfile;
16517   struct dwarf2_locexpr_baton *baton;
16518   gdb_byte *ptr;
16519   unsigned int cu_off;
16520   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16521   LONGEST offset = 0;
16522
16523   gdb_assert (common_loc && member_loc);
16524   gdb_assert (attr_form_is_block (common_loc));
16525   gdb_assert (attr_form_is_block (member_loc)
16526               || attr_form_is_constant (member_loc));
16527
16528   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16529   baton->per_cu = cu->per_cu;
16530   gdb_assert (baton->per_cu);
16531
16532   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16533
16534   if (attr_form_is_constant (member_loc))
16535     {
16536       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16537       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16538     }
16539   else
16540     baton->size += DW_BLOCK (member_loc)->size;
16541
16542   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16543   baton->data = ptr;
16544
16545   *ptr++ = DW_OP_call4;
16546   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16547   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16548   ptr += 4;
16549
16550   if (attr_form_is_constant (member_loc))
16551     {
16552       *ptr++ = DW_OP_addr;
16553       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16554       ptr += cu->header.addr_size;
16555     }
16556   else
16557     {
16558       /* We have to copy the data here, because DW_OP_call4 will only
16559          use a DW_AT_location attribute.  */
16560       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16561       ptr += DW_BLOCK (member_loc)->size;
16562     }
16563
16564   *ptr++ = DW_OP_plus;
16565   gdb_assert (ptr - baton->data == baton->size);
16566
16567   SYMBOL_LOCATION_BATON (sym) = baton;
16568   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16569 }
16570
16571 /* Create appropriate locally-scoped variables for all the
16572    DW_TAG_common_block entries.  Also create a struct common_block
16573    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16574    is used to sepate the common blocks name namespace from regular
16575    variable names.  */
16576
16577 static void
16578 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16579 {
16580   struct attribute *attr;
16581
16582   attr = dwarf2_attr (die, DW_AT_location, cu);
16583   if (attr)
16584     {
16585       /* Support the .debug_loc offsets.  */
16586       if (attr_form_is_block (attr))
16587         {
16588           /* Ok.  */
16589         }
16590       else if (attr_form_is_section_offset (attr))
16591         {
16592           dwarf2_complex_location_expr_complaint ();
16593           attr = NULL;
16594         }
16595       else
16596         {
16597           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16598                                                  "common block member");
16599           attr = NULL;
16600         }
16601     }
16602
16603   if (die->child != NULL)
16604     {
16605       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16606       struct die_info *child_die;
16607       size_t n_entries = 0, size;
16608       struct common_block *common_block;
16609       struct symbol *sym;
16610
16611       for (child_die = die->child;
16612            child_die && child_die->tag;
16613            child_die = sibling_die (child_die))
16614         ++n_entries;
16615
16616       size = (sizeof (struct common_block)
16617               + (n_entries - 1) * sizeof (struct symbol *));
16618       common_block
16619         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16620                                                  size);
16621       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16622       common_block->n_entries = 0;
16623
16624       for (child_die = die->child;
16625            child_die && child_die->tag;
16626            child_die = sibling_die (child_die))
16627         {
16628           /* Create the symbol in the DW_TAG_common_block block in the current
16629              symbol scope.  */
16630           sym = new_symbol (child_die, NULL, cu);
16631           if (sym != NULL)
16632             {
16633               struct attribute *member_loc;
16634
16635               common_block->contents[common_block->n_entries++] = sym;
16636
16637               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16638                                         cu);
16639               if (member_loc)
16640                 {
16641                   /* GDB has handled this for a long time, but it is
16642                      not specified by DWARF.  It seems to have been
16643                      emitted by gfortran at least as recently as:
16644                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16645                   complaint (_("Variable in common block has "
16646                                "DW_AT_data_member_location "
16647                                "- DIE at %s [in module %s]"),
16648                                sect_offset_str (child_die->sect_off),
16649                              objfile_name (objfile));
16650
16651                   if (attr_form_is_section_offset (member_loc))
16652                     dwarf2_complex_location_expr_complaint ();
16653                   else if (attr_form_is_constant (member_loc)
16654                            || attr_form_is_block (member_loc))
16655                     {
16656                       if (attr)
16657                         mark_common_block_symbol_computed (sym, die, attr,
16658                                                            member_loc, cu);
16659                     }
16660                   else
16661                     dwarf2_complex_location_expr_complaint ();
16662                 }
16663             }
16664         }
16665
16666       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16667       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16668     }
16669 }
16670
16671 /* Create a type for a C++ namespace.  */
16672
16673 static struct type *
16674 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16675 {
16676   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16677   const char *previous_prefix, *name;
16678   int is_anonymous;
16679   struct type *type;
16680
16681   /* For extensions, reuse the type of the original namespace.  */
16682   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16683     {
16684       struct die_info *ext_die;
16685       struct dwarf2_cu *ext_cu = cu;
16686
16687       ext_die = dwarf2_extension (die, &ext_cu);
16688       type = read_type_die (ext_die, ext_cu);
16689
16690       /* EXT_CU may not be the same as CU.
16691          Ensure TYPE is recorded with CU in die_type_hash.  */
16692       return set_die_type (die, type, cu);
16693     }
16694
16695   name = namespace_name (die, &is_anonymous, cu);
16696
16697   /* Now build the name of the current namespace.  */
16698
16699   previous_prefix = determine_prefix (die, cu);
16700   if (previous_prefix[0] != '\0')
16701     name = typename_concat (&objfile->objfile_obstack,
16702                             previous_prefix, name, 0, cu);
16703
16704   /* Create the type.  */
16705   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16706
16707   return set_die_type (die, type, cu);
16708 }
16709
16710 /* Read a namespace scope.  */
16711
16712 static void
16713 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16714 {
16715   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16716   int is_anonymous;
16717
16718   /* Add a symbol associated to this if we haven't seen the namespace
16719      before.  Also, add a using directive if it's an anonymous
16720      namespace.  */
16721
16722   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16723     {
16724       struct type *type;
16725
16726       type = read_type_die (die, cu);
16727       new_symbol (die, type, cu);
16728
16729       namespace_name (die, &is_anonymous, cu);
16730       if (is_anonymous)
16731         {
16732           const char *previous_prefix = determine_prefix (die, cu);
16733
16734           std::vector<const char *> excludes;
16735           add_using_directive (using_directives (cu->language),
16736                                previous_prefix, TYPE_NAME (type), NULL,
16737                                NULL, excludes, 0, &objfile->objfile_obstack);
16738         }
16739     }
16740
16741   if (die->child != NULL)
16742     {
16743       struct die_info *child_die = die->child;
16744
16745       while (child_die && child_die->tag)
16746         {
16747           process_die (child_die, cu);
16748           child_die = sibling_die (child_die);
16749         }
16750     }
16751 }
16752
16753 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16754    imported module.  Still we need that type as local Fortran "use ... only"
16755    declaration imports depend on the created type in determine_prefix.  */
16756
16757 static struct type *
16758 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16759 {
16760   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16761   const char *module_name;
16762   struct type *type;
16763
16764   module_name = dwarf2_name (die, cu);
16765   if (!module_name)
16766     complaint (_("DW_TAG_module has no name, offset %s"),
16767                sect_offset_str (die->sect_off));
16768   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16769
16770   return set_die_type (die, type, cu);
16771 }
16772
16773 /* Read a Fortran module.  */
16774
16775 static void
16776 read_module (struct die_info *die, struct dwarf2_cu *cu)
16777 {
16778   struct die_info *child_die = die->child;
16779   struct type *type;
16780
16781   type = read_type_die (die, cu);
16782   new_symbol (die, type, cu);
16783
16784   while (child_die && child_die->tag)
16785     {
16786       process_die (child_die, cu);
16787       child_die = sibling_die (child_die);
16788     }
16789 }
16790
16791 /* Return the name of the namespace represented by DIE.  Set
16792    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16793    namespace.  */
16794
16795 static const char *
16796 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16797 {
16798   struct die_info *current_die;
16799   const char *name = NULL;
16800
16801   /* Loop through the extensions until we find a name.  */
16802
16803   for (current_die = die;
16804        current_die != NULL;
16805        current_die = dwarf2_extension (die, &cu))
16806     {
16807       /* We don't use dwarf2_name here so that we can detect the absence
16808          of a name -> anonymous namespace.  */
16809       name = dwarf2_string_attr (die, DW_AT_name, cu);
16810
16811       if (name != NULL)
16812         break;
16813     }
16814
16815   /* Is it an anonymous namespace?  */
16816
16817   *is_anonymous = (name == NULL);
16818   if (*is_anonymous)
16819     name = CP_ANONYMOUS_NAMESPACE_STR;
16820
16821   return name;
16822 }
16823
16824 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16825    the user defined type vector.  */
16826
16827 static struct type *
16828 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16829 {
16830   struct gdbarch *gdbarch
16831     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16832   struct comp_unit_head *cu_header = &cu->header;
16833   struct type *type;
16834   struct attribute *attr_byte_size;
16835   struct attribute *attr_address_class;
16836   int byte_size, addr_class;
16837   struct type *target_type;
16838
16839   target_type = die_type (die, cu);
16840
16841   /* The die_type call above may have already set the type for this DIE.  */
16842   type = get_die_type (die, cu);
16843   if (type)
16844     return type;
16845
16846   type = lookup_pointer_type (target_type);
16847
16848   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16849   if (attr_byte_size)
16850     byte_size = DW_UNSND (attr_byte_size);
16851   else
16852     byte_size = cu_header->addr_size;
16853
16854   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16855   if (attr_address_class)
16856     addr_class = DW_UNSND (attr_address_class);
16857   else
16858     addr_class = DW_ADDR_none;
16859
16860   ULONGEST alignment = get_alignment (cu, die);
16861
16862   /* If the pointer size, alignment, or address class is different
16863      than the default, create a type variant marked as such and set
16864      the length accordingly.  */
16865   if (TYPE_LENGTH (type) != byte_size
16866       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16867           && alignment != TYPE_RAW_ALIGN (type))
16868       || addr_class != DW_ADDR_none)
16869     {
16870       if (gdbarch_address_class_type_flags_p (gdbarch))
16871         {
16872           int type_flags;
16873
16874           type_flags = gdbarch_address_class_type_flags
16875                          (gdbarch, byte_size, addr_class);
16876           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16877                       == 0);
16878           type = make_type_with_address_space (type, type_flags);
16879         }
16880       else if (TYPE_LENGTH (type) != byte_size)
16881         {
16882           complaint (_("invalid pointer size %d"), byte_size);
16883         }
16884       else if (TYPE_RAW_ALIGN (type) != alignment)
16885         {
16886           complaint (_("Invalid DW_AT_alignment"
16887                        " - DIE at %s [in module %s]"),
16888                      sect_offset_str (die->sect_off),
16889                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16890         }
16891       else
16892         {
16893           /* Should we also complain about unhandled address classes?  */
16894         }
16895     }
16896
16897   TYPE_LENGTH (type) = byte_size;
16898   set_type_align (type, alignment);
16899   return set_die_type (die, type, cu);
16900 }
16901
16902 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16903    the user defined type vector.  */
16904
16905 static struct type *
16906 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16907 {
16908   struct type *type;
16909   struct type *to_type;
16910   struct type *domain;
16911
16912   to_type = die_type (die, cu);
16913   domain = die_containing_type (die, cu);
16914
16915   /* The calls above may have already set the type for this DIE.  */
16916   type = get_die_type (die, cu);
16917   if (type)
16918     return type;
16919
16920   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16921     type = lookup_methodptr_type (to_type);
16922   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16923     {
16924       struct type *new_type
16925         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16926
16927       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16928                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16929                             TYPE_VARARGS (to_type));
16930       type = lookup_methodptr_type (new_type);
16931     }
16932   else
16933     type = lookup_memberptr_type (to_type, domain);
16934
16935   return set_die_type (die, type, cu);
16936 }
16937
16938 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16939    the user defined type vector.  */
16940
16941 static struct type *
16942 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16943                           enum type_code refcode)
16944 {
16945   struct comp_unit_head *cu_header = &cu->header;
16946   struct type *type, *target_type;
16947   struct attribute *attr;
16948
16949   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16950
16951   target_type = die_type (die, cu);
16952
16953   /* The die_type call above may have already set the type for this DIE.  */
16954   type = get_die_type (die, cu);
16955   if (type)
16956     return type;
16957
16958   type = lookup_reference_type (target_type, refcode);
16959   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16960   if (attr)
16961     {
16962       TYPE_LENGTH (type) = DW_UNSND (attr);
16963     }
16964   else
16965     {
16966       TYPE_LENGTH (type) = cu_header->addr_size;
16967     }
16968   maybe_set_alignment (cu, die, type);
16969   return set_die_type (die, type, cu);
16970 }
16971
16972 /* Add the given cv-qualifiers to the element type of the array.  GCC
16973    outputs DWARF type qualifiers that apply to an array, not the
16974    element type.  But GDB relies on the array element type to carry
16975    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16976    specification.  */
16977
16978 static struct type *
16979 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16980                    struct type *base_type, int cnst, int voltl)
16981 {
16982   struct type *el_type, *inner_array;
16983
16984   base_type = copy_type (base_type);
16985   inner_array = base_type;
16986
16987   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16988     {
16989       TYPE_TARGET_TYPE (inner_array) =
16990         copy_type (TYPE_TARGET_TYPE (inner_array));
16991       inner_array = TYPE_TARGET_TYPE (inner_array);
16992     }
16993
16994   el_type = TYPE_TARGET_TYPE (inner_array);
16995   cnst |= TYPE_CONST (el_type);
16996   voltl |= TYPE_VOLATILE (el_type);
16997   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16998
16999   return set_die_type (die, base_type, cu);
17000 }
17001
17002 static struct type *
17003 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
17004 {
17005   struct type *base_type, *cv_type;
17006
17007   base_type = die_type (die, cu);
17008
17009   /* The die_type call above may have already set the type for this DIE.  */
17010   cv_type = get_die_type (die, cu);
17011   if (cv_type)
17012     return cv_type;
17013
17014   /* In case the const qualifier is applied to an array type, the element type
17015      is so qualified, not the array type (section 6.7.3 of C99).  */
17016   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17017     return add_array_cv_type (die, cu, base_type, 1, 0);
17018
17019   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17020   return set_die_type (die, cv_type, cu);
17021 }
17022
17023 static struct type *
17024 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17025 {
17026   struct type *base_type, *cv_type;
17027
17028   base_type = die_type (die, cu);
17029
17030   /* The die_type call above may have already set the type for this DIE.  */
17031   cv_type = get_die_type (die, cu);
17032   if (cv_type)
17033     return cv_type;
17034
17035   /* In case the volatile qualifier is applied to an array type, the
17036      element type is so qualified, not the array type (section 6.7.3
17037      of C99).  */
17038   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17039     return add_array_cv_type (die, cu, base_type, 0, 1);
17040
17041   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17042   return set_die_type (die, cv_type, cu);
17043 }
17044
17045 /* Handle DW_TAG_restrict_type.  */
17046
17047 static struct type *
17048 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17049 {
17050   struct type *base_type, *cv_type;
17051
17052   base_type = die_type (die, cu);
17053
17054   /* The die_type call above may have already set the type for this DIE.  */
17055   cv_type = get_die_type (die, cu);
17056   if (cv_type)
17057     return cv_type;
17058
17059   cv_type = make_restrict_type (base_type);
17060   return set_die_type (die, cv_type, cu);
17061 }
17062
17063 /* Handle DW_TAG_atomic_type.  */
17064
17065 static struct type *
17066 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17067 {
17068   struct type *base_type, *cv_type;
17069
17070   base_type = die_type (die, cu);
17071
17072   /* The die_type call above may have already set the type for this DIE.  */
17073   cv_type = get_die_type (die, cu);
17074   if (cv_type)
17075     return cv_type;
17076
17077   cv_type = make_atomic_type (base_type);
17078   return set_die_type (die, cv_type, cu);
17079 }
17080
17081 /* Extract all information from a DW_TAG_string_type DIE and add to
17082    the user defined type vector.  It isn't really a user defined type,
17083    but it behaves like one, with other DIE's using an AT_user_def_type
17084    attribute to reference it.  */
17085
17086 static struct type *
17087 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17088 {
17089   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17090   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17091   struct type *type, *range_type, *index_type, *char_type;
17092   struct attribute *attr;
17093   unsigned int length;
17094
17095   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17096   if (attr)
17097     {
17098       length = DW_UNSND (attr);
17099     }
17100   else
17101     {
17102       /* Check for the DW_AT_byte_size attribute.  */
17103       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17104       if (attr)
17105         {
17106           length = DW_UNSND (attr);
17107         }
17108       else
17109         {
17110           length = 1;
17111         }
17112     }
17113
17114   index_type = objfile_type (objfile)->builtin_int;
17115   range_type = create_static_range_type (NULL, index_type, 1, length);
17116   char_type = language_string_char_type (cu->language_defn, gdbarch);
17117   type = create_string_type (NULL, char_type, range_type);
17118
17119   return set_die_type (die, type, cu);
17120 }
17121
17122 /* Assuming that DIE corresponds to a function, returns nonzero
17123    if the function is prototyped.  */
17124
17125 static int
17126 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17127 {
17128   struct attribute *attr;
17129
17130   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17131   if (attr && (DW_UNSND (attr) != 0))
17132     return 1;
17133
17134   /* The DWARF standard implies that the DW_AT_prototyped attribute
17135      is only meaninful for C, but the concept also extends to other
17136      languages that allow unprototyped functions (Eg: Objective C).
17137      For all other languages, assume that functions are always
17138      prototyped.  */
17139   if (cu->language != language_c
17140       && cu->language != language_objc
17141       && cu->language != language_opencl)
17142     return 1;
17143
17144   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17145      prototyped and unprototyped functions; default to prototyped,
17146      since that is more common in modern code (and RealView warns
17147      about unprototyped functions).  */
17148   if (producer_is_realview (cu->producer))
17149     return 1;
17150
17151   return 0;
17152 }
17153
17154 /* Handle DIES due to C code like:
17155
17156    struct foo
17157    {
17158    int (*funcp)(int a, long l);
17159    int b;
17160    };
17161
17162    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17163
17164 static struct type *
17165 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17166 {
17167   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17168   struct type *type;            /* Type that this function returns.  */
17169   struct type *ftype;           /* Function that returns above type.  */
17170   struct attribute *attr;
17171
17172   type = die_type (die, cu);
17173
17174   /* The die_type call above may have already set the type for this DIE.  */
17175   ftype = get_die_type (die, cu);
17176   if (ftype)
17177     return ftype;
17178
17179   ftype = lookup_function_type (type);
17180
17181   if (prototyped_function_p (die, cu))
17182     TYPE_PROTOTYPED (ftype) = 1;
17183
17184   /* Store the calling convention in the type if it's available in
17185      the subroutine die.  Otherwise set the calling convention to
17186      the default value DW_CC_normal.  */
17187   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17188   if (attr)
17189     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17190   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17191     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17192   else
17193     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17194
17195   /* Record whether the function returns normally to its caller or not
17196      if the DWARF producer set that information.  */
17197   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17198   if (attr && (DW_UNSND (attr) != 0))
17199     TYPE_NO_RETURN (ftype) = 1;
17200
17201   /* We need to add the subroutine type to the die immediately so
17202      we don't infinitely recurse when dealing with parameters
17203      declared as the same subroutine type.  */
17204   set_die_type (die, ftype, cu);
17205
17206   if (die->child != NULL)
17207     {
17208       struct type *void_type = objfile_type (objfile)->builtin_void;
17209       struct die_info *child_die;
17210       int nparams, iparams;
17211
17212       /* Count the number of parameters.
17213          FIXME: GDB currently ignores vararg functions, but knows about
17214          vararg member functions.  */
17215       nparams = 0;
17216       child_die = die->child;
17217       while (child_die && child_die->tag)
17218         {
17219           if (child_die->tag == DW_TAG_formal_parameter)
17220             nparams++;
17221           else if (child_die->tag == DW_TAG_unspecified_parameters)
17222             TYPE_VARARGS (ftype) = 1;
17223           child_die = sibling_die (child_die);
17224         }
17225
17226       /* Allocate storage for parameters and fill them in.  */
17227       TYPE_NFIELDS (ftype) = nparams;
17228       TYPE_FIELDS (ftype) = (struct field *)
17229         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17230
17231       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17232          even if we error out during the parameters reading below.  */
17233       for (iparams = 0; iparams < nparams; iparams++)
17234         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17235
17236       iparams = 0;
17237       child_die = die->child;
17238       while (child_die && child_die->tag)
17239         {
17240           if (child_die->tag == DW_TAG_formal_parameter)
17241             {
17242               struct type *arg_type;
17243
17244               /* DWARF version 2 has no clean way to discern C++
17245                  static and non-static member functions.  G++ helps
17246                  GDB by marking the first parameter for non-static
17247                  member functions (which is the this pointer) as
17248                  artificial.  We pass this information to
17249                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17250
17251                  DWARF version 3 added DW_AT_object_pointer, which GCC
17252                  4.5 does not yet generate.  */
17253               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17254               if (attr)
17255                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17256               else
17257                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17258               arg_type = die_type (child_die, cu);
17259
17260               /* RealView does not mark THIS as const, which the testsuite
17261                  expects.  GCC marks THIS as const in method definitions,
17262                  but not in the class specifications (GCC PR 43053).  */
17263               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17264                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17265                 {
17266                   int is_this = 0;
17267                   struct dwarf2_cu *arg_cu = cu;
17268                   const char *name = dwarf2_name (child_die, cu);
17269
17270                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17271                   if (attr)
17272                     {
17273                       /* If the compiler emits this, use it.  */
17274                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17275                         is_this = 1;
17276                     }
17277                   else if (name && strcmp (name, "this") == 0)
17278                     /* Function definitions will have the argument names.  */
17279                     is_this = 1;
17280                   else if (name == NULL && iparams == 0)
17281                     /* Declarations may not have the names, so like
17282                        elsewhere in GDB, assume an artificial first
17283                        argument is "this".  */
17284                     is_this = 1;
17285
17286                   if (is_this)
17287                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17288                                              arg_type, 0);
17289                 }
17290
17291               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17292               iparams++;
17293             }
17294           child_die = sibling_die (child_die);
17295         }
17296     }
17297
17298   return ftype;
17299 }
17300
17301 static struct type *
17302 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17303 {
17304   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17305   const char *name = NULL;
17306   struct type *this_type, *target_type;
17307
17308   name = dwarf2_full_name (NULL, die, cu);
17309   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17310   TYPE_TARGET_STUB (this_type) = 1;
17311   set_die_type (die, this_type, cu);
17312   target_type = die_type (die, cu);
17313   if (target_type != this_type)
17314     TYPE_TARGET_TYPE (this_type) = target_type;
17315   else
17316     {
17317       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17318          spec and cause infinite loops in GDB.  */
17319       complaint (_("Self-referential DW_TAG_typedef "
17320                    "- DIE at %s [in module %s]"),
17321                  sect_offset_str (die->sect_off), objfile_name (objfile));
17322       TYPE_TARGET_TYPE (this_type) = NULL;
17323     }
17324   return this_type;
17325 }
17326
17327 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17328    (which may be different from NAME) to the architecture back-end to allow
17329    it to guess the correct format if necessary.  */
17330
17331 static struct type *
17332 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17333                         const char *name_hint)
17334 {
17335   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17336   const struct floatformat **format;
17337   struct type *type;
17338
17339   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17340   if (format)
17341     type = init_float_type (objfile, bits, name, format);
17342   else
17343     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17344
17345   return type;
17346 }
17347
17348 /* Find a representation of a given base type and install
17349    it in the TYPE field of the die.  */
17350
17351 static struct type *
17352 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17353 {
17354   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17355   struct type *type;
17356   struct attribute *attr;
17357   int encoding = 0, bits = 0;
17358   const char *name;
17359
17360   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17361   if (attr)
17362     {
17363       encoding = DW_UNSND (attr);
17364     }
17365   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17366   if (attr)
17367     {
17368       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17369     }
17370   name = dwarf2_name (die, cu);
17371   if (!name)
17372     {
17373       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17374     }
17375
17376   switch (encoding)
17377     {
17378       case DW_ATE_address:
17379         /* Turn DW_ATE_address into a void * pointer.  */
17380         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17381         type = init_pointer_type (objfile, bits, name, type);
17382         break;
17383       case DW_ATE_boolean:
17384         type = init_boolean_type (objfile, bits, 1, name);
17385         break;
17386       case DW_ATE_complex_float:
17387         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17388         type = init_complex_type (objfile, name, type);
17389         break;
17390       case DW_ATE_decimal_float:
17391         type = init_decfloat_type (objfile, bits, name);
17392         break;
17393       case DW_ATE_float:
17394         type = dwarf2_init_float_type (objfile, bits, name, name);
17395         break;
17396       case DW_ATE_signed:
17397         type = init_integer_type (objfile, bits, 0, name);
17398         break;
17399       case DW_ATE_unsigned:
17400         if (cu->language == language_fortran
17401             && name
17402             && startswith (name, "character("))
17403           type = init_character_type (objfile, bits, 1, name);
17404         else
17405           type = init_integer_type (objfile, bits, 1, name);
17406         break;
17407       case DW_ATE_signed_char:
17408         if (cu->language == language_ada || cu->language == language_m2
17409             || cu->language == language_pascal
17410             || cu->language == language_fortran)
17411           type = init_character_type (objfile, bits, 0, name);
17412         else
17413           type = init_integer_type (objfile, bits, 0, name);
17414         break;
17415       case DW_ATE_unsigned_char:
17416         if (cu->language == language_ada || cu->language == language_m2
17417             || cu->language == language_pascal
17418             || cu->language == language_fortran
17419             || cu->language == language_rust)
17420           type = init_character_type (objfile, bits, 1, name);
17421         else
17422           type = init_integer_type (objfile, bits, 1, name);
17423         break;
17424       case DW_ATE_UTF:
17425         {
17426           gdbarch *arch = get_objfile_arch (objfile);
17427
17428           if (bits == 16)
17429             type = builtin_type (arch)->builtin_char16;
17430           else if (bits == 32)
17431             type = builtin_type (arch)->builtin_char32;
17432           else
17433             {
17434               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17435                          bits);
17436               type = init_integer_type (objfile, bits, 1, name);
17437             }
17438           return set_die_type (die, type, cu);
17439         }
17440         break;
17441
17442       default:
17443         complaint (_("unsupported DW_AT_encoding: '%s'"),
17444                    dwarf_type_encoding_name (encoding));
17445         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17446         break;
17447     }
17448
17449   if (name && strcmp (name, "char") == 0)
17450     TYPE_NOSIGN (type) = 1;
17451
17452   maybe_set_alignment (cu, die, type);
17453
17454   return set_die_type (die, type, cu);
17455 }
17456
17457 /* Parse dwarf attribute if it's a block, reference or constant and put the
17458    resulting value of the attribute into struct bound_prop.
17459    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17460
17461 static int
17462 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17463                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17464 {
17465   struct dwarf2_property_baton *baton;
17466   struct obstack *obstack
17467     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17468
17469   if (attr == NULL || prop == NULL)
17470     return 0;
17471
17472   if (attr_form_is_block (attr))
17473     {
17474       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17475       baton->referenced_type = NULL;
17476       baton->locexpr.per_cu = cu->per_cu;
17477       baton->locexpr.size = DW_BLOCK (attr)->size;
17478       baton->locexpr.data = DW_BLOCK (attr)->data;
17479       prop->data.baton = baton;
17480       prop->kind = PROP_LOCEXPR;
17481       gdb_assert (prop->data.baton != NULL);
17482     }
17483   else if (attr_form_is_ref (attr))
17484     {
17485       struct dwarf2_cu *target_cu = cu;
17486       struct die_info *target_die;
17487       struct attribute *target_attr;
17488
17489       target_die = follow_die_ref (die, attr, &target_cu);
17490       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17491       if (target_attr == NULL)
17492         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17493                                    target_cu);
17494       if (target_attr == NULL)
17495         return 0;
17496
17497       switch (target_attr->name)
17498         {
17499           case DW_AT_location:
17500             if (attr_form_is_section_offset (target_attr))
17501               {
17502                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17503                 baton->referenced_type = die_type (target_die, target_cu);
17504                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17505                 prop->data.baton = baton;
17506                 prop->kind = PROP_LOCLIST;
17507                 gdb_assert (prop->data.baton != NULL);
17508               }
17509             else if (attr_form_is_block (target_attr))
17510               {
17511                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17512                 baton->referenced_type = die_type (target_die, target_cu);
17513                 baton->locexpr.per_cu = cu->per_cu;
17514                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17515                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17516                 prop->data.baton = baton;
17517                 prop->kind = PROP_LOCEXPR;
17518                 gdb_assert (prop->data.baton != NULL);
17519               }
17520             else
17521               {
17522                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17523                                                        "dynamic property");
17524                 return 0;
17525               }
17526             break;
17527           case DW_AT_data_member_location:
17528             {
17529               LONGEST offset;
17530
17531               if (!handle_data_member_location (target_die, target_cu,
17532                                                 &offset))
17533                 return 0;
17534
17535               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17536               baton->referenced_type = read_type_die (target_die->parent,
17537                                                       target_cu);
17538               baton->offset_info.offset = offset;
17539               baton->offset_info.type = die_type (target_die, target_cu);
17540               prop->data.baton = baton;
17541               prop->kind = PROP_ADDR_OFFSET;
17542               break;
17543             }
17544         }
17545     }
17546   else if (attr_form_is_constant (attr))
17547     {
17548       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17549       prop->kind = PROP_CONST;
17550     }
17551   else
17552     {
17553       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17554                                              dwarf2_name (die, cu));
17555       return 0;
17556     }
17557
17558   return 1;
17559 }
17560
17561 /* Read the given DW_AT_subrange DIE.  */
17562
17563 static struct type *
17564 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17565 {
17566   struct type *base_type, *orig_base_type;
17567   struct type *range_type;
17568   struct attribute *attr;
17569   struct dynamic_prop low, high;
17570   int low_default_is_valid;
17571   int high_bound_is_count = 0;
17572   const char *name;
17573   LONGEST negative_mask;
17574
17575   orig_base_type = die_type (die, cu);
17576   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17577      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17578      creating the range type, but we use the result of check_typedef
17579      when examining properties of the type.  */
17580   base_type = check_typedef (orig_base_type);
17581
17582   /* The die_type call above may have already set the type for this DIE.  */
17583   range_type = get_die_type (die, cu);
17584   if (range_type)
17585     return range_type;
17586
17587   low.kind = PROP_CONST;
17588   high.kind = PROP_CONST;
17589   high.data.const_val = 0;
17590
17591   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17592      omitting DW_AT_lower_bound.  */
17593   switch (cu->language)
17594     {
17595     case language_c:
17596     case language_cplus:
17597       low.data.const_val = 0;
17598       low_default_is_valid = 1;
17599       break;
17600     case language_fortran:
17601       low.data.const_val = 1;
17602       low_default_is_valid = 1;
17603       break;
17604     case language_d:
17605     case language_objc:
17606     case language_rust:
17607       low.data.const_val = 0;
17608       low_default_is_valid = (cu->header.version >= 4);
17609       break;
17610     case language_ada:
17611     case language_m2:
17612     case language_pascal:
17613       low.data.const_val = 1;
17614       low_default_is_valid = (cu->header.version >= 4);
17615       break;
17616     default:
17617       low.data.const_val = 0;
17618       low_default_is_valid = 0;
17619       break;
17620     }
17621
17622   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17623   if (attr)
17624     attr_to_dynamic_prop (attr, die, cu, &low);
17625   else if (!low_default_is_valid)
17626     complaint (_("Missing DW_AT_lower_bound "
17627                                       "- DIE at %s [in module %s]"),
17628                sect_offset_str (die->sect_off),
17629                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17630
17631   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17632   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17633     {
17634       attr = dwarf2_attr (die, DW_AT_count, cu);
17635       if (attr_to_dynamic_prop (attr, die, cu, &high))
17636         {
17637           /* If bounds are constant do the final calculation here.  */
17638           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17639             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17640           else
17641             high_bound_is_count = 1;
17642         }
17643     }
17644
17645   /* Dwarf-2 specifications explicitly allows to create subrange types
17646      without specifying a base type.
17647      In that case, the base type must be set to the type of
17648      the lower bound, upper bound or count, in that order, if any of these
17649      three attributes references an object that has a type.
17650      If no base type is found, the Dwarf-2 specifications say that
17651      a signed integer type of size equal to the size of an address should
17652      be used.
17653      For the following C code: `extern char gdb_int [];'
17654      GCC produces an empty range DIE.
17655      FIXME: muller/2010-05-28: Possible references to object for low bound,
17656      high bound or count are not yet handled by this code.  */
17657   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17658     {
17659       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17660       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17661       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17662       struct type *int_type = objfile_type (objfile)->builtin_int;
17663
17664       /* Test "int", "long int", and "long long int" objfile types,
17665          and select the first one having a size above or equal to the
17666          architecture address size.  */
17667       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17668         base_type = int_type;
17669       else
17670         {
17671           int_type = objfile_type (objfile)->builtin_long;
17672           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17673             base_type = int_type;
17674           else
17675             {
17676               int_type = objfile_type (objfile)->builtin_long_long;
17677               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17678                 base_type = int_type;
17679             }
17680         }
17681     }
17682
17683   /* Normally, the DWARF producers are expected to use a signed
17684      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17685      But this is unfortunately not always the case, as witnessed
17686      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17687      is used instead.  To work around that ambiguity, we treat
17688      the bounds as signed, and thus sign-extend their values, when
17689      the base type is signed.  */
17690   negative_mask =
17691     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17692   if (low.kind == PROP_CONST
17693       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17694     low.data.const_val |= negative_mask;
17695   if (high.kind == PROP_CONST
17696       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17697     high.data.const_val |= negative_mask;
17698
17699   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17700
17701   if (high_bound_is_count)
17702     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17703
17704   /* Ada expects an empty array on no boundary attributes.  */
17705   if (attr == NULL && cu->language != language_ada)
17706     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17707
17708   name = dwarf2_name (die, cu);
17709   if (name)
17710     TYPE_NAME (range_type) = name;
17711
17712   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17713   if (attr)
17714     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17715
17716   maybe_set_alignment (cu, die, range_type);
17717
17718   set_die_type (die, range_type, cu);
17719
17720   /* set_die_type should be already done.  */
17721   set_descriptive_type (range_type, die, cu);
17722
17723   return range_type;
17724 }
17725
17726 static struct type *
17727 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17728 {
17729   struct type *type;
17730
17731   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17732                     NULL);
17733   TYPE_NAME (type) = dwarf2_name (die, cu);
17734
17735   /* In Ada, an unspecified type is typically used when the description
17736      of the type is defered to a different unit.  When encountering
17737      such a type, we treat it as a stub, and try to resolve it later on,
17738      when needed.  */
17739   if (cu->language == language_ada)
17740     TYPE_STUB (type) = 1;
17741
17742   return set_die_type (die, type, cu);
17743 }
17744
17745 /* Read a single die and all its descendents.  Set the die's sibling
17746    field to NULL; set other fields in the die correctly, and set all
17747    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17748    location of the info_ptr after reading all of those dies.  PARENT
17749    is the parent of the die in question.  */
17750
17751 static struct die_info *
17752 read_die_and_children (const struct die_reader_specs *reader,
17753                        const gdb_byte *info_ptr,
17754                        const gdb_byte **new_info_ptr,
17755                        struct die_info *parent)
17756 {
17757   struct die_info *die;
17758   const gdb_byte *cur_ptr;
17759   int has_children;
17760
17761   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17762   if (die == NULL)
17763     {
17764       *new_info_ptr = cur_ptr;
17765       return NULL;
17766     }
17767   store_in_ref_table (die, reader->cu);
17768
17769   if (has_children)
17770     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17771   else
17772     {
17773       die->child = NULL;
17774       *new_info_ptr = cur_ptr;
17775     }
17776
17777   die->sibling = NULL;
17778   die->parent = parent;
17779   return die;
17780 }
17781
17782 /* Read a die, all of its descendents, and all of its siblings; set
17783    all of the fields of all of the dies correctly.  Arguments are as
17784    in read_die_and_children.  */
17785
17786 static struct die_info *
17787 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17788                          const gdb_byte *info_ptr,
17789                          const gdb_byte **new_info_ptr,
17790                          struct die_info *parent)
17791 {
17792   struct die_info *first_die, *last_sibling;
17793   const gdb_byte *cur_ptr;
17794
17795   cur_ptr = info_ptr;
17796   first_die = last_sibling = NULL;
17797
17798   while (1)
17799     {
17800       struct die_info *die
17801         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17802
17803       if (die == NULL)
17804         {
17805           *new_info_ptr = cur_ptr;
17806           return first_die;
17807         }
17808
17809       if (!first_die)
17810         first_die = die;
17811       else
17812         last_sibling->sibling = die;
17813
17814       last_sibling = die;
17815     }
17816 }
17817
17818 /* Read a die, all of its descendents, and all of its siblings; set
17819    all of the fields of all of the dies correctly.  Arguments are as
17820    in read_die_and_children.
17821    This the main entry point for reading a DIE and all its children.  */
17822
17823 static struct die_info *
17824 read_die_and_siblings (const struct die_reader_specs *reader,
17825                        const gdb_byte *info_ptr,
17826                        const gdb_byte **new_info_ptr,
17827                        struct die_info *parent)
17828 {
17829   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17830                                                   new_info_ptr, parent);
17831
17832   if (dwarf_die_debug)
17833     {
17834       fprintf_unfiltered (gdb_stdlog,
17835                           "Read die from %s@0x%x of %s:\n",
17836                           get_section_name (reader->die_section),
17837                           (unsigned) (info_ptr - reader->die_section->buffer),
17838                           bfd_get_filename (reader->abfd));
17839       dump_die (die, dwarf_die_debug);
17840     }
17841
17842   return die;
17843 }
17844
17845 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17846    attributes.
17847    The caller is responsible for filling in the extra attributes
17848    and updating (*DIEP)->num_attrs.
17849    Set DIEP to point to a newly allocated die with its information,
17850    except for its child, sibling, and parent fields.
17851    Set HAS_CHILDREN to tell whether the die has children or not.  */
17852
17853 static const gdb_byte *
17854 read_full_die_1 (const struct die_reader_specs *reader,
17855                  struct die_info **diep, const gdb_byte *info_ptr,
17856                  int *has_children, int num_extra_attrs)
17857 {
17858   unsigned int abbrev_number, bytes_read, i;
17859   struct abbrev_info *abbrev;
17860   struct die_info *die;
17861   struct dwarf2_cu *cu = reader->cu;
17862   bfd *abfd = reader->abfd;
17863
17864   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17865   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17866   info_ptr += bytes_read;
17867   if (!abbrev_number)
17868     {
17869       *diep = NULL;
17870       *has_children = 0;
17871       return info_ptr;
17872     }
17873
17874   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17875   if (!abbrev)
17876     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17877            abbrev_number,
17878            bfd_get_filename (abfd));
17879
17880   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17881   die->sect_off = sect_off;
17882   die->tag = abbrev->tag;
17883   die->abbrev = abbrev_number;
17884
17885   /* Make the result usable.
17886      The caller needs to update num_attrs after adding the extra
17887      attributes.  */
17888   die->num_attrs = abbrev->num_attrs;
17889
17890   for (i = 0; i < abbrev->num_attrs; ++i)
17891     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17892                                info_ptr);
17893
17894   *diep = die;
17895   *has_children = abbrev->has_children;
17896   return info_ptr;
17897 }
17898
17899 /* Read a die and all its attributes.
17900    Set DIEP to point to a newly allocated die with its information,
17901    except for its child, sibling, and parent fields.
17902    Set HAS_CHILDREN to tell whether the die has children or not.  */
17903
17904 static const gdb_byte *
17905 read_full_die (const struct die_reader_specs *reader,
17906                struct die_info **diep, const gdb_byte *info_ptr,
17907                int *has_children)
17908 {
17909   const gdb_byte *result;
17910
17911   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17912
17913   if (dwarf_die_debug)
17914     {
17915       fprintf_unfiltered (gdb_stdlog,
17916                           "Read die from %s@0x%x of %s:\n",
17917                           get_section_name (reader->die_section),
17918                           (unsigned) (info_ptr - reader->die_section->buffer),
17919                           bfd_get_filename (reader->abfd));
17920       dump_die (*diep, dwarf_die_debug);
17921     }
17922
17923   return result;
17924 }
17925 \f
17926 /* Abbreviation tables.
17927
17928    In DWARF version 2, the description of the debugging information is
17929    stored in a separate .debug_abbrev section.  Before we read any
17930    dies from a section we read in all abbreviations and install them
17931    in a hash table.  */
17932
17933 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17934
17935 struct abbrev_info *
17936 abbrev_table::alloc_abbrev ()
17937 {
17938   struct abbrev_info *abbrev;
17939
17940   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
17941   memset (abbrev, 0, sizeof (struct abbrev_info));
17942
17943   return abbrev;
17944 }
17945
17946 /* Add an abbreviation to the table.  */
17947
17948 void
17949 abbrev_table::add_abbrev (unsigned int abbrev_number,
17950                           struct abbrev_info *abbrev)
17951 {
17952   unsigned int hash_number;
17953
17954   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17955   abbrev->next = m_abbrevs[hash_number];
17956   m_abbrevs[hash_number] = abbrev;
17957 }
17958
17959 /* Look up an abbrev in the table.
17960    Returns NULL if the abbrev is not found.  */
17961
17962 struct abbrev_info *
17963 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
17964 {
17965   unsigned int hash_number;
17966   struct abbrev_info *abbrev;
17967
17968   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17969   abbrev = m_abbrevs[hash_number];
17970
17971   while (abbrev)
17972     {
17973       if (abbrev->number == abbrev_number)
17974         return abbrev;
17975       abbrev = abbrev->next;
17976     }
17977   return NULL;
17978 }
17979
17980 /* Read in an abbrev table.  */
17981
17982 static abbrev_table_up
17983 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
17984                          struct dwarf2_section_info *section,
17985                          sect_offset sect_off)
17986 {
17987   struct objfile *objfile = dwarf2_per_objfile->objfile;
17988   bfd *abfd = get_section_bfd_owner (section);
17989   const gdb_byte *abbrev_ptr;
17990   struct abbrev_info *cur_abbrev;
17991   unsigned int abbrev_number, bytes_read, abbrev_name;
17992   unsigned int abbrev_form;
17993   struct attr_abbrev *cur_attrs;
17994   unsigned int allocated_attrs;
17995
17996   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
17997
17998   dwarf2_read_section (objfile, section);
17999   abbrev_ptr = section->buffer + to_underlying (sect_off);
18000   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18001   abbrev_ptr += bytes_read;
18002
18003   allocated_attrs = ATTR_ALLOC_CHUNK;
18004   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18005
18006   /* Loop until we reach an abbrev number of 0.  */
18007   while (abbrev_number)
18008     {
18009       cur_abbrev = abbrev_table->alloc_abbrev ();
18010
18011       /* read in abbrev header */
18012       cur_abbrev->number = abbrev_number;
18013       cur_abbrev->tag
18014         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18015       abbrev_ptr += bytes_read;
18016       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18017       abbrev_ptr += 1;
18018
18019       /* now read in declarations */
18020       for (;;)
18021         {
18022           LONGEST implicit_const;
18023
18024           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18025           abbrev_ptr += bytes_read;
18026           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18027           abbrev_ptr += bytes_read;
18028           if (abbrev_form == DW_FORM_implicit_const)
18029             {
18030               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18031                                                    &bytes_read);
18032               abbrev_ptr += bytes_read;
18033             }
18034           else
18035             {
18036               /* Initialize it due to a false compiler warning.  */
18037               implicit_const = -1;
18038             }
18039
18040           if (abbrev_name == 0)
18041             break;
18042
18043           if (cur_abbrev->num_attrs == allocated_attrs)
18044             {
18045               allocated_attrs += ATTR_ALLOC_CHUNK;
18046               cur_attrs
18047                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18048             }
18049
18050           cur_attrs[cur_abbrev->num_attrs].name
18051             = (enum dwarf_attribute) abbrev_name;
18052           cur_attrs[cur_abbrev->num_attrs].form
18053             = (enum dwarf_form) abbrev_form;
18054           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18055           ++cur_abbrev->num_attrs;
18056         }
18057
18058       cur_abbrev->attrs =
18059         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18060                    cur_abbrev->num_attrs);
18061       memcpy (cur_abbrev->attrs, cur_attrs,
18062               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18063
18064       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18065
18066       /* Get next abbreviation.
18067          Under Irix6 the abbreviations for a compilation unit are not
18068          always properly terminated with an abbrev number of 0.
18069          Exit loop if we encounter an abbreviation which we have
18070          already read (which means we are about to read the abbreviations
18071          for the next compile unit) or if the end of the abbreviation
18072          table is reached.  */
18073       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18074         break;
18075       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18076       abbrev_ptr += bytes_read;
18077       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18078         break;
18079     }
18080
18081   xfree (cur_attrs);
18082   return abbrev_table;
18083 }
18084
18085 /* Returns nonzero if TAG represents a type that we might generate a partial
18086    symbol for.  */
18087
18088 static int
18089 is_type_tag_for_partial (int tag)
18090 {
18091   switch (tag)
18092     {
18093 #if 0
18094     /* Some types that would be reasonable to generate partial symbols for,
18095        that we don't at present.  */
18096     case DW_TAG_array_type:
18097     case DW_TAG_file_type:
18098     case DW_TAG_ptr_to_member_type:
18099     case DW_TAG_set_type:
18100     case DW_TAG_string_type:
18101     case DW_TAG_subroutine_type:
18102 #endif
18103     case DW_TAG_base_type:
18104     case DW_TAG_class_type:
18105     case DW_TAG_interface_type:
18106     case DW_TAG_enumeration_type:
18107     case DW_TAG_structure_type:
18108     case DW_TAG_subrange_type:
18109     case DW_TAG_typedef:
18110     case DW_TAG_union_type:
18111       return 1;
18112     default:
18113       return 0;
18114     }
18115 }
18116
18117 /* Load all DIEs that are interesting for partial symbols into memory.  */
18118
18119 static struct partial_die_info *
18120 load_partial_dies (const struct die_reader_specs *reader,
18121                    const gdb_byte *info_ptr, int building_psymtab)
18122 {
18123   struct dwarf2_cu *cu = reader->cu;
18124   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18125   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18126   unsigned int bytes_read;
18127   unsigned int load_all = 0;
18128   int nesting_level = 1;
18129
18130   parent_die = NULL;
18131   last_die = NULL;
18132
18133   gdb_assert (cu->per_cu != NULL);
18134   if (cu->per_cu->load_all_dies)
18135     load_all = 1;
18136
18137   cu->partial_dies
18138     = htab_create_alloc_ex (cu->header.length / 12,
18139                             partial_die_hash,
18140                             partial_die_eq,
18141                             NULL,
18142                             &cu->comp_unit_obstack,
18143                             hashtab_obstack_allocate,
18144                             dummy_obstack_deallocate);
18145
18146   while (1)
18147     {
18148       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18149
18150       /* A NULL abbrev means the end of a series of children.  */
18151       if (abbrev == NULL)
18152         {
18153           if (--nesting_level == 0)
18154             return first_die;
18155
18156           info_ptr += bytes_read;
18157           last_die = parent_die;
18158           parent_die = parent_die->die_parent;
18159           continue;
18160         }
18161
18162       /* Check for template arguments.  We never save these; if
18163          they're seen, we just mark the parent, and go on our way.  */
18164       if (parent_die != NULL
18165           && cu->language == language_cplus
18166           && (abbrev->tag == DW_TAG_template_type_param
18167               || abbrev->tag == DW_TAG_template_value_param))
18168         {
18169           parent_die->has_template_arguments = 1;
18170
18171           if (!load_all)
18172             {
18173               /* We don't need a partial DIE for the template argument.  */
18174               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18175               continue;
18176             }
18177         }
18178
18179       /* We only recurse into c++ subprograms looking for template arguments.
18180          Skip their other children.  */
18181       if (!load_all
18182           && cu->language == language_cplus
18183           && parent_die != NULL
18184           && parent_die->tag == DW_TAG_subprogram)
18185         {
18186           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18187           continue;
18188         }
18189
18190       /* Check whether this DIE is interesting enough to save.  Normally
18191          we would not be interested in members here, but there may be
18192          later variables referencing them via DW_AT_specification (for
18193          static members).  */
18194       if (!load_all
18195           && !is_type_tag_for_partial (abbrev->tag)
18196           && abbrev->tag != DW_TAG_constant
18197           && abbrev->tag != DW_TAG_enumerator
18198           && abbrev->tag != DW_TAG_subprogram
18199           && abbrev->tag != DW_TAG_inlined_subroutine
18200           && abbrev->tag != DW_TAG_lexical_block
18201           && abbrev->tag != DW_TAG_variable
18202           && abbrev->tag != DW_TAG_namespace
18203           && abbrev->tag != DW_TAG_module
18204           && abbrev->tag != DW_TAG_member
18205           && abbrev->tag != DW_TAG_imported_unit
18206           && abbrev->tag != DW_TAG_imported_declaration)
18207         {
18208           /* Otherwise we skip to the next sibling, if any.  */
18209           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18210           continue;
18211         }
18212
18213       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18214                                    abbrev);
18215
18216       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18217
18218       /* This two-pass algorithm for processing partial symbols has a
18219          high cost in cache pressure.  Thus, handle some simple cases
18220          here which cover the majority of C partial symbols.  DIEs
18221          which neither have specification tags in them, nor could have
18222          specification tags elsewhere pointing at them, can simply be
18223          processed and discarded.
18224
18225          This segment is also optional; scan_partial_symbols and
18226          add_partial_symbol will handle these DIEs if we chain
18227          them in normally.  When compilers which do not emit large
18228          quantities of duplicate debug information are more common,
18229          this code can probably be removed.  */
18230
18231       /* Any complete simple types at the top level (pretty much all
18232          of them, for a language without namespaces), can be processed
18233          directly.  */
18234       if (parent_die == NULL
18235           && pdi.has_specification == 0
18236           && pdi.is_declaration == 0
18237           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18238               || pdi.tag == DW_TAG_base_type
18239               || pdi.tag == DW_TAG_subrange_type))
18240         {
18241           if (building_psymtab && pdi.name != NULL)
18242             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18243                                  VAR_DOMAIN, LOC_TYPEDEF,
18244                                  &objfile->static_psymbols,
18245                                  0, cu->language, objfile);
18246           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18247           continue;
18248         }
18249
18250       /* The exception for DW_TAG_typedef with has_children above is
18251          a workaround of GCC PR debug/47510.  In the case of this complaint
18252          type_name_or_error will error on such types later.
18253
18254          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18255          it could not find the child DIEs referenced later, this is checked
18256          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18257
18258       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18259         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18260                      "- DIE at %s [in module %s]"),
18261                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18262
18263       /* If we're at the second level, and we're an enumerator, and
18264          our parent has no specification (meaning possibly lives in a
18265          namespace elsewhere), then we can add the partial symbol now
18266          instead of queueing it.  */
18267       if (pdi.tag == DW_TAG_enumerator
18268           && parent_die != NULL
18269           && parent_die->die_parent == NULL
18270           && parent_die->tag == DW_TAG_enumeration_type
18271           && parent_die->has_specification == 0)
18272         {
18273           if (pdi.name == NULL)
18274             complaint (_("malformed enumerator DIE ignored"));
18275           else if (building_psymtab)
18276             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18277                                  VAR_DOMAIN, LOC_CONST,
18278                                  cu->language == language_cplus
18279                                  ? &objfile->global_psymbols
18280                                  : &objfile->static_psymbols,
18281                                  0, cu->language, objfile);
18282
18283           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18284           continue;
18285         }
18286
18287       struct partial_die_info *part_die
18288         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18289
18290       /* We'll save this DIE so link it in.  */
18291       part_die->die_parent = parent_die;
18292       part_die->die_sibling = NULL;
18293       part_die->die_child = NULL;
18294
18295       if (last_die && last_die == parent_die)
18296         last_die->die_child = part_die;
18297       else if (last_die)
18298         last_die->die_sibling = part_die;
18299
18300       last_die = part_die;
18301
18302       if (first_die == NULL)
18303         first_die = part_die;
18304
18305       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18306          find interesting need to be in the hash table, because we
18307          also have the parent/sibling/child chains; only those that we
18308          might refer to by offset later during partial symbol reading.
18309
18310          For now this means things that might have be the target of a
18311          DW_AT_specification, DW_AT_abstract_origin, or
18312          DW_AT_extension.  DW_AT_extension will refer only to
18313          namespaces; DW_AT_abstract_origin refers to functions (and
18314          many things under the function DIE, but we do not recurse
18315          into function DIEs during partial symbol reading) and
18316          possibly variables as well; DW_AT_specification refers to
18317          declarations.  Declarations ought to have the DW_AT_declaration
18318          flag.  It happens that GCC forgets to put it in sometimes, but
18319          only for functions, not for types.
18320
18321          Adding more things than necessary to the hash table is harmless
18322          except for the performance cost.  Adding too few will result in
18323          wasted time in find_partial_die, when we reread the compilation
18324          unit with load_all_dies set.  */
18325
18326       if (load_all
18327           || abbrev->tag == DW_TAG_constant
18328           || abbrev->tag == DW_TAG_subprogram
18329           || abbrev->tag == DW_TAG_variable
18330           || abbrev->tag == DW_TAG_namespace
18331           || part_die->is_declaration)
18332         {
18333           void **slot;
18334
18335           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18336                                            to_underlying (part_die->sect_off),
18337                                            INSERT);
18338           *slot = part_die;
18339         }
18340
18341       /* For some DIEs we want to follow their children (if any).  For C
18342          we have no reason to follow the children of structures; for other
18343          languages we have to, so that we can get at method physnames
18344          to infer fully qualified class names, for DW_AT_specification,
18345          and for C++ template arguments.  For C++, we also look one level
18346          inside functions to find template arguments (if the name of the
18347          function does not already contain the template arguments).
18348
18349          For Ada, we need to scan the children of subprograms and lexical
18350          blocks as well because Ada allows the definition of nested
18351          entities that could be interesting for the debugger, such as
18352          nested subprograms for instance.  */
18353       if (last_die->has_children
18354           && (load_all
18355               || last_die->tag == DW_TAG_namespace
18356               || last_die->tag == DW_TAG_module
18357               || last_die->tag == DW_TAG_enumeration_type
18358               || (cu->language == language_cplus
18359                   && last_die->tag == DW_TAG_subprogram
18360                   && (last_die->name == NULL
18361                       || strchr (last_die->name, '<') == NULL))
18362               || (cu->language != language_c
18363                   && (last_die->tag == DW_TAG_class_type
18364                       || last_die->tag == DW_TAG_interface_type
18365                       || last_die->tag == DW_TAG_structure_type
18366                       || last_die->tag == DW_TAG_union_type))
18367               || (cu->language == language_ada
18368                   && (last_die->tag == DW_TAG_subprogram
18369                       || last_die->tag == DW_TAG_lexical_block))))
18370         {
18371           nesting_level++;
18372           parent_die = last_die;
18373           continue;
18374         }
18375
18376       /* Otherwise we skip to the next sibling, if any.  */
18377       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18378
18379       /* Back to the top, do it again.  */
18380     }
18381 }
18382
18383 partial_die_info::partial_die_info (sect_offset sect_off_,
18384                                     struct abbrev_info *abbrev)
18385   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18386 {
18387 }
18388
18389 /* Read a minimal amount of information into the minimal die structure.
18390    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18391
18392 const gdb_byte *
18393 partial_die_info::read (const struct die_reader_specs *reader,
18394                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18395 {
18396   struct dwarf2_cu *cu = reader->cu;
18397   struct dwarf2_per_objfile *dwarf2_per_objfile
18398     = cu->per_cu->dwarf2_per_objfile;
18399   unsigned int i;
18400   int has_low_pc_attr = 0;
18401   int has_high_pc_attr = 0;
18402   int high_pc_relative = 0;
18403
18404   for (i = 0; i < abbrev.num_attrs; ++i)
18405     {
18406       struct attribute attr;
18407
18408       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18409
18410       /* Store the data if it is of an attribute we want to keep in a
18411          partial symbol table.  */
18412       switch (attr.name)
18413         {
18414         case DW_AT_name:
18415           switch (tag)
18416             {
18417             case DW_TAG_compile_unit:
18418             case DW_TAG_partial_unit:
18419             case DW_TAG_type_unit:
18420               /* Compilation units have a DW_AT_name that is a filename, not
18421                  a source language identifier.  */
18422             case DW_TAG_enumeration_type:
18423             case DW_TAG_enumerator:
18424               /* These tags always have simple identifiers already; no need
18425                  to canonicalize them.  */
18426               name = DW_STRING (&attr);
18427               break;
18428             default:
18429               {
18430                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18431
18432                 name
18433                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18434                                               &objfile->per_bfd->storage_obstack);
18435               }
18436               break;
18437             }
18438           break;
18439         case DW_AT_linkage_name:
18440         case DW_AT_MIPS_linkage_name:
18441           /* Note that both forms of linkage name might appear.  We
18442              assume they will be the same, and we only store the last
18443              one we see.  */
18444           if (cu->language == language_ada)
18445             name = DW_STRING (&attr);
18446           linkage_name = DW_STRING (&attr);
18447           break;
18448         case DW_AT_low_pc:
18449           has_low_pc_attr = 1;
18450           lowpc = attr_value_as_address (&attr);
18451           break;
18452         case DW_AT_high_pc:
18453           has_high_pc_attr = 1;
18454           highpc = attr_value_as_address (&attr);
18455           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18456                 high_pc_relative = 1;
18457           break;
18458         case DW_AT_location:
18459           /* Support the .debug_loc offsets.  */
18460           if (attr_form_is_block (&attr))
18461             {
18462                d.locdesc = DW_BLOCK (&attr);
18463             }
18464           else if (attr_form_is_section_offset (&attr))
18465             {
18466               dwarf2_complex_location_expr_complaint ();
18467             }
18468           else
18469             {
18470               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18471                                                      "partial symbol information");
18472             }
18473           break;
18474         case DW_AT_external:
18475           is_external = DW_UNSND (&attr);
18476           break;
18477         case DW_AT_declaration:
18478           is_declaration = DW_UNSND (&attr);
18479           break;
18480         case DW_AT_type:
18481           has_type = 1;
18482           break;
18483         case DW_AT_abstract_origin:
18484         case DW_AT_specification:
18485         case DW_AT_extension:
18486           has_specification = 1;
18487           spec_offset = dwarf2_get_ref_die_offset (&attr);
18488           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18489                                    || cu->per_cu->is_dwz);
18490           break;
18491         case DW_AT_sibling:
18492           /* Ignore absolute siblings, they might point outside of
18493              the current compile unit.  */
18494           if (attr.form == DW_FORM_ref_addr)
18495             complaint (_("ignoring absolute DW_AT_sibling"));
18496           else
18497             {
18498               const gdb_byte *buffer = reader->buffer;
18499               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18500               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18501
18502               if (sibling_ptr < info_ptr)
18503                 complaint (_("DW_AT_sibling points backwards"));
18504               else if (sibling_ptr > reader->buffer_end)
18505                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18506               else
18507                 sibling = sibling_ptr;
18508             }
18509           break;
18510         case DW_AT_byte_size:
18511           has_byte_size = 1;
18512           break;
18513         case DW_AT_const_value:
18514           has_const_value = 1;
18515           break;
18516         case DW_AT_calling_convention:
18517           /* DWARF doesn't provide a way to identify a program's source-level
18518              entry point.  DW_AT_calling_convention attributes are only meant
18519              to describe functions' calling conventions.
18520
18521              However, because it's a necessary piece of information in
18522              Fortran, and before DWARF 4 DW_CC_program was the only
18523              piece of debugging information whose definition refers to
18524              a 'main program' at all, several compilers marked Fortran
18525              main programs with DW_CC_program --- even when those
18526              functions use the standard calling conventions.
18527
18528              Although DWARF now specifies a way to provide this
18529              information, we support this practice for backward
18530              compatibility.  */
18531           if (DW_UNSND (&attr) == DW_CC_program
18532               && cu->language == language_fortran)
18533             main_subprogram = 1;
18534           break;
18535         case DW_AT_inline:
18536           if (DW_UNSND (&attr) == DW_INL_inlined
18537               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18538             may_be_inlined = 1;
18539           break;
18540
18541         case DW_AT_import:
18542           if (tag == DW_TAG_imported_unit)
18543             {
18544               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18545               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18546                                   || cu->per_cu->is_dwz);
18547             }
18548           break;
18549
18550         case DW_AT_main_subprogram:
18551           main_subprogram = DW_UNSND (&attr);
18552           break;
18553
18554         default:
18555           break;
18556         }
18557     }
18558
18559   if (high_pc_relative)
18560     highpc += lowpc;
18561
18562   if (has_low_pc_attr && has_high_pc_attr)
18563     {
18564       /* When using the GNU linker, .gnu.linkonce. sections are used to
18565          eliminate duplicate copies of functions and vtables and such.
18566          The linker will arbitrarily choose one and discard the others.
18567          The AT_*_pc values for such functions refer to local labels in
18568          these sections.  If the section from that file was discarded, the
18569          labels are not in the output, so the relocs get a value of 0.
18570          If this is a discarded function, mark the pc bounds as invalid,
18571          so that GDB will ignore it.  */
18572       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18573         {
18574           struct objfile *objfile = dwarf2_per_objfile->objfile;
18575           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18576
18577           complaint (_("DW_AT_low_pc %s is zero "
18578                        "for DIE at %s [in module %s]"),
18579                      paddress (gdbarch, lowpc),
18580                      sect_offset_str (sect_off),
18581                      objfile_name (objfile));
18582         }
18583       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18584       else if (lowpc >= highpc)
18585         {
18586           struct objfile *objfile = dwarf2_per_objfile->objfile;
18587           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18588
18589           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18590                        "for DIE at %s [in module %s]"),
18591                      paddress (gdbarch, lowpc),
18592                      paddress (gdbarch, highpc),
18593                      sect_offset_str (sect_off),
18594                      objfile_name (objfile));
18595         }
18596       else
18597         has_pc_info = 1;
18598     }
18599
18600   return info_ptr;
18601 }
18602
18603 /* Find a cached partial DIE at OFFSET in CU.  */
18604
18605 struct partial_die_info *
18606 dwarf2_cu::find_partial_die (sect_offset sect_off)
18607 {
18608   struct partial_die_info *lookup_die = NULL;
18609   struct partial_die_info part_die (sect_off);
18610
18611   lookup_die = ((struct partial_die_info *)
18612                 htab_find_with_hash (partial_dies, &part_die,
18613                                      to_underlying (sect_off)));
18614
18615   return lookup_die;
18616 }
18617
18618 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18619    except in the case of .debug_types DIEs which do not reference
18620    outside their CU (they do however referencing other types via
18621    DW_FORM_ref_sig8).  */
18622
18623 static struct partial_die_info *
18624 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18625 {
18626   struct dwarf2_per_objfile *dwarf2_per_objfile
18627     = cu->per_cu->dwarf2_per_objfile;
18628   struct objfile *objfile = dwarf2_per_objfile->objfile;
18629   struct dwarf2_per_cu_data *per_cu = NULL;
18630   struct partial_die_info *pd = NULL;
18631
18632   if (offset_in_dwz == cu->per_cu->is_dwz
18633       && offset_in_cu_p (&cu->header, sect_off))
18634     {
18635       pd = cu->find_partial_die (sect_off);
18636       if (pd != NULL)
18637         return pd;
18638       /* We missed recording what we needed.
18639          Load all dies and try again.  */
18640       per_cu = cu->per_cu;
18641     }
18642   else
18643     {
18644       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18645       if (cu->per_cu->is_debug_types)
18646         {
18647           error (_("Dwarf Error: Type Unit at offset %s contains"
18648                    " external reference to offset %s [in module %s].\n"),
18649                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18650                  bfd_get_filename (objfile->obfd));
18651         }
18652       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18653                                                  dwarf2_per_objfile);
18654
18655       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18656         load_partial_comp_unit (per_cu);
18657
18658       per_cu->cu->last_used = 0;
18659       pd = per_cu->cu->find_partial_die (sect_off);
18660     }
18661
18662   /* If we didn't find it, and not all dies have been loaded,
18663      load them all and try again.  */
18664
18665   if (pd == NULL && per_cu->load_all_dies == 0)
18666     {
18667       per_cu->load_all_dies = 1;
18668
18669       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18670          THIS_CU->cu may already be in use.  So we can't just free it and
18671          replace its DIEs with the ones we read in.  Instead, we leave those
18672          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18673          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18674          set.  */
18675       load_partial_comp_unit (per_cu);
18676
18677       pd = per_cu->cu->find_partial_die (sect_off);
18678     }
18679
18680   if (pd == NULL)
18681     internal_error (__FILE__, __LINE__,
18682                     _("could not find partial DIE %s "
18683                       "in cache [from module %s]\n"),
18684                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18685   return pd;
18686 }
18687
18688 /* See if we can figure out if the class lives in a namespace.  We do
18689    this by looking for a member function; its demangled name will
18690    contain namespace info, if there is any.  */
18691
18692 static void
18693 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18694                                   struct dwarf2_cu *cu)
18695 {
18696   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18697      what template types look like, because the demangler
18698      frequently doesn't give the same name as the debug info.  We
18699      could fix this by only using the demangled name to get the
18700      prefix (but see comment in read_structure_type).  */
18701
18702   struct partial_die_info *real_pdi;
18703   struct partial_die_info *child_pdi;
18704
18705   /* If this DIE (this DIE's specification, if any) has a parent, then
18706      we should not do this.  We'll prepend the parent's fully qualified
18707      name when we create the partial symbol.  */
18708
18709   real_pdi = struct_pdi;
18710   while (real_pdi->has_specification)
18711     real_pdi = find_partial_die (real_pdi->spec_offset,
18712                                  real_pdi->spec_is_dwz, cu);
18713
18714   if (real_pdi->die_parent != NULL)
18715     return;
18716
18717   for (child_pdi = struct_pdi->die_child;
18718        child_pdi != NULL;
18719        child_pdi = child_pdi->die_sibling)
18720     {
18721       if (child_pdi->tag == DW_TAG_subprogram
18722           && child_pdi->linkage_name != NULL)
18723         {
18724           char *actual_class_name
18725             = language_class_name_from_physname (cu->language_defn,
18726                                                  child_pdi->linkage_name);
18727           if (actual_class_name != NULL)
18728             {
18729               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18730               struct_pdi->name
18731                 = ((const char *)
18732                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18733                                   actual_class_name,
18734                                   strlen (actual_class_name)));
18735               xfree (actual_class_name);
18736             }
18737           break;
18738         }
18739     }
18740 }
18741
18742 void
18743 partial_die_info::fixup (struct dwarf2_cu *cu)
18744 {
18745   /* Once we've fixed up a die, there's no point in doing so again.
18746      This also avoids a memory leak if we were to call
18747      guess_partial_die_structure_name multiple times.  */
18748   if (fixup_called)
18749     return;
18750
18751   /* If we found a reference attribute and the DIE has no name, try
18752      to find a name in the referred to DIE.  */
18753
18754   if (name == NULL && has_specification)
18755     {
18756       struct partial_die_info *spec_die;
18757
18758       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18759
18760       spec_die->fixup (cu);
18761
18762       if (spec_die->name)
18763         {
18764           name = spec_die->name;
18765
18766           /* Copy DW_AT_external attribute if it is set.  */
18767           if (spec_die->is_external)
18768             is_external = spec_die->is_external;
18769         }
18770     }
18771
18772   /* Set default names for some unnamed DIEs.  */
18773
18774   if (name == NULL && tag == DW_TAG_namespace)
18775     name = CP_ANONYMOUS_NAMESPACE_STR;
18776
18777   /* If there is no parent die to provide a namespace, and there are
18778      children, see if we can determine the namespace from their linkage
18779      name.  */
18780   if (cu->language == language_cplus
18781       && !VEC_empty (dwarf2_section_info_def,
18782                      cu->per_cu->dwarf2_per_objfile->types)
18783       && die_parent == NULL
18784       && has_children
18785       && (tag == DW_TAG_class_type
18786           || tag == DW_TAG_structure_type
18787           || tag == DW_TAG_union_type))
18788     guess_partial_die_structure_name (this, cu);
18789
18790   /* GCC might emit a nameless struct or union that has a linkage
18791      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18792   if (name == NULL
18793       && (tag == DW_TAG_class_type
18794           || tag == DW_TAG_interface_type
18795           || tag == DW_TAG_structure_type
18796           || tag == DW_TAG_union_type)
18797       && linkage_name != NULL)
18798     {
18799       char *demangled;
18800
18801       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18802       if (demangled)
18803         {
18804           const char *base;
18805
18806           /* Strip any leading namespaces/classes, keep only the base name.
18807              DW_AT_name for named DIEs does not contain the prefixes.  */
18808           base = strrchr (demangled, ':');
18809           if (base && base > demangled && base[-1] == ':')
18810             base++;
18811           else
18812             base = demangled;
18813
18814           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18815           name
18816             = ((const char *)
18817                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18818                               base, strlen (base)));
18819           xfree (demangled);
18820         }
18821     }
18822
18823   fixup_called = 1;
18824 }
18825
18826 /* Read an attribute value described by an attribute form.  */
18827
18828 static const gdb_byte *
18829 read_attribute_value (const struct die_reader_specs *reader,
18830                       struct attribute *attr, unsigned form,
18831                       LONGEST implicit_const, const gdb_byte *info_ptr)
18832 {
18833   struct dwarf2_cu *cu = reader->cu;
18834   struct dwarf2_per_objfile *dwarf2_per_objfile
18835     = cu->per_cu->dwarf2_per_objfile;
18836   struct objfile *objfile = dwarf2_per_objfile->objfile;
18837   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18838   bfd *abfd = reader->abfd;
18839   struct comp_unit_head *cu_header = &cu->header;
18840   unsigned int bytes_read;
18841   struct dwarf_block *blk;
18842
18843   attr->form = (enum dwarf_form) form;
18844   switch (form)
18845     {
18846     case DW_FORM_ref_addr:
18847       if (cu->header.version == 2)
18848         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18849       else
18850         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18851                                        &cu->header, &bytes_read);
18852       info_ptr += bytes_read;
18853       break;
18854     case DW_FORM_GNU_ref_alt:
18855       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18856       info_ptr += bytes_read;
18857       break;
18858     case DW_FORM_addr:
18859       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18860       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18861       info_ptr += bytes_read;
18862       break;
18863     case DW_FORM_block2:
18864       blk = dwarf_alloc_block (cu);
18865       blk->size = read_2_bytes (abfd, info_ptr);
18866       info_ptr += 2;
18867       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18868       info_ptr += blk->size;
18869       DW_BLOCK (attr) = blk;
18870       break;
18871     case DW_FORM_block4:
18872       blk = dwarf_alloc_block (cu);
18873       blk->size = read_4_bytes (abfd, info_ptr);
18874       info_ptr += 4;
18875       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18876       info_ptr += blk->size;
18877       DW_BLOCK (attr) = blk;
18878       break;
18879     case DW_FORM_data2:
18880       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18881       info_ptr += 2;
18882       break;
18883     case DW_FORM_data4:
18884       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18885       info_ptr += 4;
18886       break;
18887     case DW_FORM_data8:
18888       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18889       info_ptr += 8;
18890       break;
18891     case DW_FORM_data16:
18892       blk = dwarf_alloc_block (cu);
18893       blk->size = 16;
18894       blk->data = read_n_bytes (abfd, info_ptr, 16);
18895       info_ptr += 16;
18896       DW_BLOCK (attr) = blk;
18897       break;
18898     case DW_FORM_sec_offset:
18899       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18900       info_ptr += bytes_read;
18901       break;
18902     case DW_FORM_string:
18903       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18904       DW_STRING_IS_CANONICAL (attr) = 0;
18905       info_ptr += bytes_read;
18906       break;
18907     case DW_FORM_strp:
18908       if (!cu->per_cu->is_dwz)
18909         {
18910           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18911                                                    abfd, info_ptr, cu_header,
18912                                                    &bytes_read);
18913           DW_STRING_IS_CANONICAL (attr) = 0;
18914           info_ptr += bytes_read;
18915           break;
18916         }
18917       /* FALLTHROUGH */
18918     case DW_FORM_line_strp:
18919       if (!cu->per_cu->is_dwz)
18920         {
18921           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18922                                                         abfd, info_ptr,
18923                                                         cu_header, &bytes_read);
18924           DW_STRING_IS_CANONICAL (attr) = 0;
18925           info_ptr += bytes_read;
18926           break;
18927         }
18928       /* FALLTHROUGH */
18929     case DW_FORM_GNU_strp_alt:
18930       {
18931         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
18932         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18933                                           &bytes_read);
18934
18935         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
18936                                                           dwz, str_offset);
18937         DW_STRING_IS_CANONICAL (attr) = 0;
18938         info_ptr += bytes_read;
18939       }
18940       break;
18941     case DW_FORM_exprloc:
18942     case DW_FORM_block:
18943       blk = dwarf_alloc_block (cu);
18944       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18945       info_ptr += bytes_read;
18946       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18947       info_ptr += blk->size;
18948       DW_BLOCK (attr) = blk;
18949       break;
18950     case DW_FORM_block1:
18951       blk = dwarf_alloc_block (cu);
18952       blk->size = read_1_byte (abfd, info_ptr);
18953       info_ptr += 1;
18954       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18955       info_ptr += blk->size;
18956       DW_BLOCK (attr) = blk;
18957       break;
18958     case DW_FORM_data1:
18959       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18960       info_ptr += 1;
18961       break;
18962     case DW_FORM_flag:
18963       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18964       info_ptr += 1;
18965       break;
18966     case DW_FORM_flag_present:
18967       DW_UNSND (attr) = 1;
18968       break;
18969     case DW_FORM_sdata:
18970       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18971       info_ptr += bytes_read;
18972       break;
18973     case DW_FORM_udata:
18974       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18975       info_ptr += bytes_read;
18976       break;
18977     case DW_FORM_ref1:
18978       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18979                          + read_1_byte (abfd, info_ptr));
18980       info_ptr += 1;
18981       break;
18982     case DW_FORM_ref2:
18983       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18984                          + read_2_bytes (abfd, info_ptr));
18985       info_ptr += 2;
18986       break;
18987     case DW_FORM_ref4:
18988       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18989                          + read_4_bytes (abfd, info_ptr));
18990       info_ptr += 4;
18991       break;
18992     case DW_FORM_ref8:
18993       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18994                          + read_8_bytes (abfd, info_ptr));
18995       info_ptr += 8;
18996       break;
18997     case DW_FORM_ref_sig8:
18998       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
18999       info_ptr += 8;
19000       break;
19001     case DW_FORM_ref_udata:
19002       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19003                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19004       info_ptr += bytes_read;
19005       break;
19006     case DW_FORM_indirect:
19007       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19008       info_ptr += bytes_read;
19009       if (form == DW_FORM_implicit_const)
19010         {
19011           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19012           info_ptr += bytes_read;
19013         }
19014       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19015                                        info_ptr);
19016       break;
19017     case DW_FORM_implicit_const:
19018       DW_SND (attr) = implicit_const;
19019       break;
19020     case DW_FORM_GNU_addr_index:
19021       if (reader->dwo_file == NULL)
19022         {
19023           /* For now flag a hard error.
19024              Later we can turn this into a complaint.  */
19025           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19026                  dwarf_form_name (form),
19027                  bfd_get_filename (abfd));
19028         }
19029       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19030       info_ptr += bytes_read;
19031       break;
19032     case DW_FORM_GNU_str_index:
19033       if (reader->dwo_file == NULL)
19034         {
19035           /* For now flag a hard error.
19036              Later we can turn this into a complaint if warranted.  */
19037           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19038                  dwarf_form_name (form),
19039                  bfd_get_filename (abfd));
19040         }
19041       {
19042         ULONGEST str_index =
19043           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19044
19045         DW_STRING (attr) = read_str_index (reader, str_index);
19046         DW_STRING_IS_CANONICAL (attr) = 0;
19047         info_ptr += bytes_read;
19048       }
19049       break;
19050     default:
19051       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19052              dwarf_form_name (form),
19053              bfd_get_filename (abfd));
19054     }
19055
19056   /* Super hack.  */
19057   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19058     attr->form = DW_FORM_GNU_ref_alt;
19059
19060   /* We have seen instances where the compiler tried to emit a byte
19061      size attribute of -1 which ended up being encoded as an unsigned
19062      0xffffffff.  Although 0xffffffff is technically a valid size value,
19063      an object of this size seems pretty unlikely so we can relatively
19064      safely treat these cases as if the size attribute was invalid and
19065      treat them as zero by default.  */
19066   if (attr->name == DW_AT_byte_size
19067       && form == DW_FORM_data4
19068       && DW_UNSND (attr) >= 0xffffffff)
19069     {
19070       complaint
19071         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19072          hex_string (DW_UNSND (attr)));
19073       DW_UNSND (attr) = 0;
19074     }
19075
19076   return info_ptr;
19077 }
19078
19079 /* Read an attribute described by an abbreviated attribute.  */
19080
19081 static const gdb_byte *
19082 read_attribute (const struct die_reader_specs *reader,
19083                 struct attribute *attr, struct attr_abbrev *abbrev,
19084                 const gdb_byte *info_ptr)
19085 {
19086   attr->name = abbrev->name;
19087   return read_attribute_value (reader, attr, abbrev->form,
19088                                abbrev->implicit_const, info_ptr);
19089 }
19090
19091 /* Read dwarf information from a buffer.  */
19092
19093 static unsigned int
19094 read_1_byte (bfd *abfd, const gdb_byte *buf)
19095 {
19096   return bfd_get_8 (abfd, buf);
19097 }
19098
19099 static int
19100 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19101 {
19102   return bfd_get_signed_8 (abfd, buf);
19103 }
19104
19105 static unsigned int
19106 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19107 {
19108   return bfd_get_16 (abfd, buf);
19109 }
19110
19111 static int
19112 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19113 {
19114   return bfd_get_signed_16 (abfd, buf);
19115 }
19116
19117 static unsigned int
19118 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19119 {
19120   return bfd_get_32 (abfd, buf);
19121 }
19122
19123 static int
19124 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19125 {
19126   return bfd_get_signed_32 (abfd, buf);
19127 }
19128
19129 static ULONGEST
19130 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19131 {
19132   return bfd_get_64 (abfd, buf);
19133 }
19134
19135 static CORE_ADDR
19136 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19137               unsigned int *bytes_read)
19138 {
19139   struct comp_unit_head *cu_header = &cu->header;
19140   CORE_ADDR retval = 0;
19141
19142   if (cu_header->signed_addr_p)
19143     {
19144       switch (cu_header->addr_size)
19145         {
19146         case 2:
19147           retval = bfd_get_signed_16 (abfd, buf);
19148           break;
19149         case 4:
19150           retval = bfd_get_signed_32 (abfd, buf);
19151           break;
19152         case 8:
19153           retval = bfd_get_signed_64 (abfd, buf);
19154           break;
19155         default:
19156           internal_error (__FILE__, __LINE__,
19157                           _("read_address: bad switch, signed [in module %s]"),
19158                           bfd_get_filename (abfd));
19159         }
19160     }
19161   else
19162     {
19163       switch (cu_header->addr_size)
19164         {
19165         case 2:
19166           retval = bfd_get_16 (abfd, buf);
19167           break;
19168         case 4:
19169           retval = bfd_get_32 (abfd, buf);
19170           break;
19171         case 8:
19172           retval = bfd_get_64 (abfd, buf);
19173           break;
19174         default:
19175           internal_error (__FILE__, __LINE__,
19176                           _("read_address: bad switch, "
19177                             "unsigned [in module %s]"),
19178                           bfd_get_filename (abfd));
19179         }
19180     }
19181
19182   *bytes_read = cu_header->addr_size;
19183   return retval;
19184 }
19185
19186 /* Read the initial length from a section.  The (draft) DWARF 3
19187    specification allows the initial length to take up either 4 bytes
19188    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19189    bytes describe the length and all offsets will be 8 bytes in length
19190    instead of 4.
19191
19192    An older, non-standard 64-bit format is also handled by this
19193    function.  The older format in question stores the initial length
19194    as an 8-byte quantity without an escape value.  Lengths greater
19195    than 2^32 aren't very common which means that the initial 4 bytes
19196    is almost always zero.  Since a length value of zero doesn't make
19197    sense for the 32-bit format, this initial zero can be considered to
19198    be an escape value which indicates the presence of the older 64-bit
19199    format.  As written, the code can't detect (old format) lengths
19200    greater than 4GB.  If it becomes necessary to handle lengths
19201    somewhat larger than 4GB, we could allow other small values (such
19202    as the non-sensical values of 1, 2, and 3) to also be used as
19203    escape values indicating the presence of the old format.
19204
19205    The value returned via bytes_read should be used to increment the
19206    relevant pointer after calling read_initial_length().
19207
19208    [ Note:  read_initial_length() and read_offset() are based on the
19209      document entitled "DWARF Debugging Information Format", revision
19210      3, draft 8, dated November 19, 2001.  This document was obtained
19211      from:
19212
19213         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19214
19215      This document is only a draft and is subject to change.  (So beware.)
19216
19217      Details regarding the older, non-standard 64-bit format were
19218      determined empirically by examining 64-bit ELF files produced by
19219      the SGI toolchain on an IRIX 6.5 machine.
19220
19221      - Kevin, July 16, 2002
19222    ] */
19223
19224 static LONGEST
19225 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19226 {
19227   LONGEST length = bfd_get_32 (abfd, buf);
19228
19229   if (length == 0xffffffff)
19230     {
19231       length = bfd_get_64 (abfd, buf + 4);
19232       *bytes_read = 12;
19233     }
19234   else if (length == 0)
19235     {
19236       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19237       length = bfd_get_64 (abfd, buf);
19238       *bytes_read = 8;
19239     }
19240   else
19241     {
19242       *bytes_read = 4;
19243     }
19244
19245   return length;
19246 }
19247
19248 /* Cover function for read_initial_length.
19249    Returns the length of the object at BUF, and stores the size of the
19250    initial length in *BYTES_READ and stores the size that offsets will be in
19251    *OFFSET_SIZE.
19252    If the initial length size is not equivalent to that specified in
19253    CU_HEADER then issue a complaint.
19254    This is useful when reading non-comp-unit headers.  */
19255
19256 static LONGEST
19257 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19258                                         const struct comp_unit_head *cu_header,
19259                                         unsigned int *bytes_read,
19260                                         unsigned int *offset_size)
19261 {
19262   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19263
19264   gdb_assert (cu_header->initial_length_size == 4
19265               || cu_header->initial_length_size == 8
19266               || cu_header->initial_length_size == 12);
19267
19268   if (cu_header->initial_length_size != *bytes_read)
19269     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19270
19271   *offset_size = (*bytes_read == 4) ? 4 : 8;
19272   return length;
19273 }
19274
19275 /* Read an offset from the data stream.  The size of the offset is
19276    given by cu_header->offset_size.  */
19277
19278 static LONGEST
19279 read_offset (bfd *abfd, const gdb_byte *buf,
19280              const struct comp_unit_head *cu_header,
19281              unsigned int *bytes_read)
19282 {
19283   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19284
19285   *bytes_read = cu_header->offset_size;
19286   return offset;
19287 }
19288
19289 /* Read an offset from the data stream.  */
19290
19291 static LONGEST
19292 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19293 {
19294   LONGEST retval = 0;
19295
19296   switch (offset_size)
19297     {
19298     case 4:
19299       retval = bfd_get_32 (abfd, buf);
19300       break;
19301     case 8:
19302       retval = bfd_get_64 (abfd, buf);
19303       break;
19304     default:
19305       internal_error (__FILE__, __LINE__,
19306                       _("read_offset_1: bad switch [in module %s]"),
19307                       bfd_get_filename (abfd));
19308     }
19309
19310   return retval;
19311 }
19312
19313 static const gdb_byte *
19314 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19315 {
19316   /* If the size of a host char is 8 bits, we can return a pointer
19317      to the buffer, otherwise we have to copy the data to a buffer
19318      allocated on the temporary obstack.  */
19319   gdb_assert (HOST_CHAR_BIT == 8);
19320   return buf;
19321 }
19322
19323 static const char *
19324 read_direct_string (bfd *abfd, const gdb_byte *buf,
19325                     unsigned int *bytes_read_ptr)
19326 {
19327   /* If the size of a host char is 8 bits, we can return a pointer
19328      to the string, otherwise we have to copy the string to a buffer
19329      allocated on the temporary obstack.  */
19330   gdb_assert (HOST_CHAR_BIT == 8);
19331   if (*buf == '\0')
19332     {
19333       *bytes_read_ptr = 1;
19334       return NULL;
19335     }
19336   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19337   return (const char *) buf;
19338 }
19339
19340 /* Return pointer to string at section SECT offset STR_OFFSET with error
19341    reporting strings FORM_NAME and SECT_NAME.  */
19342
19343 static const char *
19344 read_indirect_string_at_offset_from (struct objfile *objfile,
19345                                      bfd *abfd, LONGEST str_offset,
19346                                      struct dwarf2_section_info *sect,
19347                                      const char *form_name,
19348                                      const char *sect_name)
19349 {
19350   dwarf2_read_section (objfile, sect);
19351   if (sect->buffer == NULL)
19352     error (_("%s used without %s section [in module %s]"),
19353            form_name, sect_name, bfd_get_filename (abfd));
19354   if (str_offset >= sect->size)
19355     error (_("%s pointing outside of %s section [in module %s]"),
19356            form_name, sect_name, bfd_get_filename (abfd));
19357   gdb_assert (HOST_CHAR_BIT == 8);
19358   if (sect->buffer[str_offset] == '\0')
19359     return NULL;
19360   return (const char *) (sect->buffer + str_offset);
19361 }
19362
19363 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19364
19365 static const char *
19366 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19367                                 bfd *abfd, LONGEST str_offset)
19368 {
19369   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19370                                               abfd, str_offset,
19371                                               &dwarf2_per_objfile->str,
19372                                               "DW_FORM_strp", ".debug_str");
19373 }
19374
19375 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19376
19377 static const char *
19378 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19379                                      bfd *abfd, LONGEST str_offset)
19380 {
19381   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19382                                               abfd, str_offset,
19383                                               &dwarf2_per_objfile->line_str,
19384                                               "DW_FORM_line_strp",
19385                                               ".debug_line_str");
19386 }
19387
19388 /* Read a string at offset STR_OFFSET in the .debug_str section from
19389    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19390    the string consists of a single NUL byte, return NULL; otherwise
19391    return a pointer to the string.  */
19392
19393 static const char *
19394 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19395                                LONGEST str_offset)
19396 {
19397   dwarf2_read_section (objfile, &dwz->str);
19398
19399   if (dwz->str.buffer == NULL)
19400     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19401              "section [in module %s]"),
19402            bfd_get_filename (dwz->dwz_bfd));
19403   if (str_offset >= dwz->str.size)
19404     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19405              ".debug_str section [in module %s]"),
19406            bfd_get_filename (dwz->dwz_bfd));
19407   gdb_assert (HOST_CHAR_BIT == 8);
19408   if (dwz->str.buffer[str_offset] == '\0')
19409     return NULL;
19410   return (const char *) (dwz->str.buffer + str_offset);
19411 }
19412
19413 /* Return pointer to string at .debug_str offset as read from BUF.
19414    BUF is assumed to be in a compilation unit described by CU_HEADER.
19415    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19416
19417 static const char *
19418 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19419                       const gdb_byte *buf,
19420                       const struct comp_unit_head *cu_header,
19421                       unsigned int *bytes_read_ptr)
19422 {
19423   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19424
19425   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19426 }
19427
19428 /* Return pointer to string at .debug_line_str offset as read from BUF.
19429    BUF is assumed to be in a compilation unit described by CU_HEADER.
19430    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19431
19432 static const char *
19433 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19434                            bfd *abfd, const gdb_byte *buf,
19435                            const struct comp_unit_head *cu_header,
19436                            unsigned int *bytes_read_ptr)
19437 {
19438   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19439
19440   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19441                                               str_offset);
19442 }
19443
19444 ULONGEST
19445 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19446                           unsigned int *bytes_read_ptr)
19447 {
19448   ULONGEST result;
19449   unsigned int num_read;
19450   int shift;
19451   unsigned char byte;
19452
19453   result = 0;
19454   shift = 0;
19455   num_read = 0;
19456   while (1)
19457     {
19458       byte = bfd_get_8 (abfd, buf);
19459       buf++;
19460       num_read++;
19461       result |= ((ULONGEST) (byte & 127) << shift);
19462       if ((byte & 128) == 0)
19463         {
19464           break;
19465         }
19466       shift += 7;
19467     }
19468   *bytes_read_ptr = num_read;
19469   return result;
19470 }
19471
19472 static LONGEST
19473 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19474                     unsigned int *bytes_read_ptr)
19475 {
19476   LONGEST result;
19477   int shift, num_read;
19478   unsigned char byte;
19479
19480   result = 0;
19481   shift = 0;
19482   num_read = 0;
19483   while (1)
19484     {
19485       byte = bfd_get_8 (abfd, buf);
19486       buf++;
19487       num_read++;
19488       result |= ((LONGEST) (byte & 127) << shift);
19489       shift += 7;
19490       if ((byte & 128) == 0)
19491         {
19492           break;
19493         }
19494     }
19495   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19496     result |= -(((LONGEST) 1) << shift);
19497   *bytes_read_ptr = num_read;
19498   return result;
19499 }
19500
19501 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19502    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19503    ADDR_SIZE is the size of addresses from the CU header.  */
19504
19505 static CORE_ADDR
19506 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19507                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19508 {
19509   struct objfile *objfile = dwarf2_per_objfile->objfile;
19510   bfd *abfd = objfile->obfd;
19511   const gdb_byte *info_ptr;
19512
19513   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19514   if (dwarf2_per_objfile->addr.buffer == NULL)
19515     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19516            objfile_name (objfile));
19517   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19518     error (_("DW_FORM_addr_index pointing outside of "
19519              ".debug_addr section [in module %s]"),
19520            objfile_name (objfile));
19521   info_ptr = (dwarf2_per_objfile->addr.buffer
19522               + addr_base + addr_index * addr_size);
19523   if (addr_size == 4)
19524     return bfd_get_32 (abfd, info_ptr);
19525   else
19526     return bfd_get_64 (abfd, info_ptr);
19527 }
19528
19529 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19530
19531 static CORE_ADDR
19532 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19533 {
19534   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19535                             cu->addr_base, cu->header.addr_size);
19536 }
19537
19538 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19539
19540 static CORE_ADDR
19541 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19542                              unsigned int *bytes_read)
19543 {
19544   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19545   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19546
19547   return read_addr_index (cu, addr_index);
19548 }
19549
19550 /* Data structure to pass results from dwarf2_read_addr_index_reader
19551    back to dwarf2_read_addr_index.  */
19552
19553 struct dwarf2_read_addr_index_data
19554 {
19555   ULONGEST addr_base;
19556   int addr_size;
19557 };
19558
19559 /* die_reader_func for dwarf2_read_addr_index.  */
19560
19561 static void
19562 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19563                                const gdb_byte *info_ptr,
19564                                struct die_info *comp_unit_die,
19565                                int has_children,
19566                                void *data)
19567 {
19568   struct dwarf2_cu *cu = reader->cu;
19569   struct dwarf2_read_addr_index_data *aidata =
19570     (struct dwarf2_read_addr_index_data *) data;
19571
19572   aidata->addr_base = cu->addr_base;
19573   aidata->addr_size = cu->header.addr_size;
19574 }
19575
19576 /* Given an index in .debug_addr, fetch the value.
19577    NOTE: This can be called during dwarf expression evaluation,
19578    long after the debug information has been read, and thus per_cu->cu
19579    may no longer exist.  */
19580
19581 CORE_ADDR
19582 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19583                         unsigned int addr_index)
19584 {
19585   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19586   struct dwarf2_cu *cu = per_cu->cu;
19587   ULONGEST addr_base;
19588   int addr_size;
19589
19590   /* We need addr_base and addr_size.
19591      If we don't have PER_CU->cu, we have to get it.
19592      Nasty, but the alternative is storing the needed info in PER_CU,
19593      which at this point doesn't seem justified: it's not clear how frequently
19594      it would get used and it would increase the size of every PER_CU.
19595      Entry points like dwarf2_per_cu_addr_size do a similar thing
19596      so we're not in uncharted territory here.
19597      Alas we need to be a bit more complicated as addr_base is contained
19598      in the DIE.
19599
19600      We don't need to read the entire CU(/TU).
19601      We just need the header and top level die.
19602
19603      IWBN to use the aging mechanism to let us lazily later discard the CU.
19604      For now we skip this optimization.  */
19605
19606   if (cu != NULL)
19607     {
19608       addr_base = cu->addr_base;
19609       addr_size = cu->header.addr_size;
19610     }
19611   else
19612     {
19613       struct dwarf2_read_addr_index_data aidata;
19614
19615       /* Note: We can't use init_cutu_and_read_dies_simple here,
19616          we need addr_base.  */
19617       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19618                                dwarf2_read_addr_index_reader, &aidata);
19619       addr_base = aidata.addr_base;
19620       addr_size = aidata.addr_size;
19621     }
19622
19623   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19624                             addr_size);
19625 }
19626
19627 /* Given a DW_FORM_GNU_str_index, fetch the string.
19628    This is only used by the Fission support.  */
19629
19630 static const char *
19631 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19632 {
19633   struct dwarf2_cu *cu = reader->cu;
19634   struct dwarf2_per_objfile *dwarf2_per_objfile
19635     = cu->per_cu->dwarf2_per_objfile;
19636   struct objfile *objfile = dwarf2_per_objfile->objfile;
19637   const char *objf_name = objfile_name (objfile);
19638   bfd *abfd = objfile->obfd;
19639   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19640   struct dwarf2_section_info *str_offsets_section =
19641     &reader->dwo_file->sections.str_offsets;
19642   const gdb_byte *info_ptr;
19643   ULONGEST str_offset;
19644   static const char form_name[] = "DW_FORM_GNU_str_index";
19645
19646   dwarf2_read_section (objfile, str_section);
19647   dwarf2_read_section (objfile, str_offsets_section);
19648   if (str_section->buffer == NULL)
19649     error (_("%s used without .debug_str.dwo section"
19650              " in CU at offset %s [in module %s]"),
19651            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19652   if (str_offsets_section->buffer == NULL)
19653     error (_("%s used without .debug_str_offsets.dwo section"
19654              " in CU at offset %s [in module %s]"),
19655            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19656   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19657     error (_("%s pointing outside of .debug_str_offsets.dwo"
19658              " section in CU at offset %s [in module %s]"),
19659            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19660   info_ptr = (str_offsets_section->buffer
19661               + str_index * cu->header.offset_size);
19662   if (cu->header.offset_size == 4)
19663     str_offset = bfd_get_32 (abfd, info_ptr);
19664   else
19665     str_offset = bfd_get_64 (abfd, info_ptr);
19666   if (str_offset >= str_section->size)
19667     error (_("Offset from %s pointing outside of"
19668              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19669            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19670   return (const char *) (str_section->buffer + str_offset);
19671 }
19672
19673 /* Return the length of an LEB128 number in BUF.  */
19674
19675 static int
19676 leb128_size (const gdb_byte *buf)
19677 {
19678   const gdb_byte *begin = buf;
19679   gdb_byte byte;
19680
19681   while (1)
19682     {
19683       byte = *buf++;
19684       if ((byte & 128) == 0)
19685         return buf - begin;
19686     }
19687 }
19688
19689 static void
19690 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19691 {
19692   switch (lang)
19693     {
19694     case DW_LANG_C89:
19695     case DW_LANG_C99:
19696     case DW_LANG_C11:
19697     case DW_LANG_C:
19698     case DW_LANG_UPC:
19699       cu->language = language_c;
19700       break;
19701     case DW_LANG_Java:
19702     case DW_LANG_C_plus_plus:
19703     case DW_LANG_C_plus_plus_11:
19704     case DW_LANG_C_plus_plus_14:
19705       cu->language = language_cplus;
19706       break;
19707     case DW_LANG_D:
19708       cu->language = language_d;
19709       break;
19710     case DW_LANG_Fortran77:
19711     case DW_LANG_Fortran90:
19712     case DW_LANG_Fortran95:
19713     case DW_LANG_Fortran03:
19714     case DW_LANG_Fortran08:
19715       cu->language = language_fortran;
19716       break;
19717     case DW_LANG_Go:
19718       cu->language = language_go;
19719       break;
19720     case DW_LANG_Mips_Assembler:
19721       cu->language = language_asm;
19722       break;
19723     case DW_LANG_Ada83:
19724     case DW_LANG_Ada95:
19725       cu->language = language_ada;
19726       break;
19727     case DW_LANG_Modula2:
19728       cu->language = language_m2;
19729       break;
19730     case DW_LANG_Pascal83:
19731       cu->language = language_pascal;
19732       break;
19733     case DW_LANG_ObjC:
19734       cu->language = language_objc;
19735       break;
19736     case DW_LANG_Rust:
19737     case DW_LANG_Rust_old:
19738       cu->language = language_rust;
19739       break;
19740     case DW_LANG_Cobol74:
19741     case DW_LANG_Cobol85:
19742     default:
19743       cu->language = language_minimal;
19744       break;
19745     }
19746   cu->language_defn = language_def (cu->language);
19747 }
19748
19749 /* Return the named attribute or NULL if not there.  */
19750
19751 static struct attribute *
19752 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19753 {
19754   for (;;)
19755     {
19756       unsigned int i;
19757       struct attribute *spec = NULL;
19758
19759       for (i = 0; i < die->num_attrs; ++i)
19760         {
19761           if (die->attrs[i].name == name)
19762             return &die->attrs[i];
19763           if (die->attrs[i].name == DW_AT_specification
19764               || die->attrs[i].name == DW_AT_abstract_origin)
19765             spec = &die->attrs[i];
19766         }
19767
19768       if (!spec)
19769         break;
19770
19771       die = follow_die_ref (die, spec, &cu);
19772     }
19773
19774   return NULL;
19775 }
19776
19777 /* Return the named attribute or NULL if not there,
19778    but do not follow DW_AT_specification, etc.
19779    This is for use in contexts where we're reading .debug_types dies.
19780    Following DW_AT_specification, DW_AT_abstract_origin will take us
19781    back up the chain, and we want to go down.  */
19782
19783 static struct attribute *
19784 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19785 {
19786   unsigned int i;
19787
19788   for (i = 0; i < die->num_attrs; ++i)
19789     if (die->attrs[i].name == name)
19790       return &die->attrs[i];
19791
19792   return NULL;
19793 }
19794
19795 /* Return the string associated with a string-typed attribute, or NULL if it
19796    is either not found or is of an incorrect type.  */
19797
19798 static const char *
19799 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19800 {
19801   struct attribute *attr;
19802   const char *str = NULL;
19803
19804   attr = dwarf2_attr (die, name, cu);
19805
19806   if (attr != NULL)
19807     {
19808       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19809           || attr->form == DW_FORM_string
19810           || attr->form == DW_FORM_GNU_str_index
19811           || attr->form == DW_FORM_GNU_strp_alt)
19812         str = DW_STRING (attr);
19813       else
19814         complaint (_("string type expected for attribute %s for "
19815                      "DIE at %s in module %s"),
19816                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19817                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19818     }
19819
19820   return str;
19821 }
19822
19823 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19824    and holds a non-zero value.  This function should only be used for
19825    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19826
19827 static int
19828 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19829 {
19830   struct attribute *attr = dwarf2_attr (die, name, cu);
19831
19832   return (attr && DW_UNSND (attr));
19833 }
19834
19835 static int
19836 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19837 {
19838   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19839      which value is non-zero.  However, we have to be careful with
19840      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19841      (via dwarf2_flag_true_p) follows this attribute.  So we may
19842      end up accidently finding a declaration attribute that belongs
19843      to a different DIE referenced by the specification attribute,
19844      even though the given DIE does not have a declaration attribute.  */
19845   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19846           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19847 }
19848
19849 /* Return the die giving the specification for DIE, if there is
19850    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19851    containing the return value on output.  If there is no
19852    specification, but there is an abstract origin, that is
19853    returned.  */
19854
19855 static struct die_info *
19856 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19857 {
19858   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19859                                              *spec_cu);
19860
19861   if (spec_attr == NULL)
19862     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19863
19864   if (spec_attr == NULL)
19865     return NULL;
19866   else
19867     return follow_die_ref (die, spec_attr, spec_cu);
19868 }
19869
19870 /* Stub for free_line_header to match void * callback types.  */
19871
19872 static void
19873 free_line_header_voidp (void *arg)
19874 {
19875   struct line_header *lh = (struct line_header *) arg;
19876
19877   delete lh;
19878 }
19879
19880 void
19881 line_header::add_include_dir (const char *include_dir)
19882 {
19883   if (dwarf_line_debug >= 2)
19884     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19885                         include_dirs.size () + 1, include_dir);
19886
19887   include_dirs.push_back (include_dir);
19888 }
19889
19890 void
19891 line_header::add_file_name (const char *name,
19892                             dir_index d_index,
19893                             unsigned int mod_time,
19894                             unsigned int length)
19895 {
19896   if (dwarf_line_debug >= 2)
19897     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19898                         (unsigned) file_names.size () + 1, name);
19899
19900   file_names.emplace_back (name, d_index, mod_time, length);
19901 }
19902
19903 /* A convenience function to find the proper .debug_line section for a CU.  */
19904
19905 static struct dwarf2_section_info *
19906 get_debug_line_section (struct dwarf2_cu *cu)
19907 {
19908   struct dwarf2_section_info *section;
19909   struct dwarf2_per_objfile *dwarf2_per_objfile
19910     = cu->per_cu->dwarf2_per_objfile;
19911
19912   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19913      DWO file.  */
19914   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19915     section = &cu->dwo_unit->dwo_file->sections.line;
19916   else if (cu->per_cu->is_dwz)
19917     {
19918       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19919
19920       section = &dwz->line;
19921     }
19922   else
19923     section = &dwarf2_per_objfile->line;
19924
19925   return section;
19926 }
19927
19928 /* Read directory or file name entry format, starting with byte of
19929    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19930    entries count and the entries themselves in the described entry
19931    format.  */
19932
19933 static void
19934 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
19935                         bfd *abfd, const gdb_byte **bufp,
19936                         struct line_header *lh,
19937                         const struct comp_unit_head *cu_header,
19938                         void (*callback) (struct line_header *lh,
19939                                           const char *name,
19940                                           dir_index d_index,
19941                                           unsigned int mod_time,
19942                                           unsigned int length))
19943 {
19944   gdb_byte format_count, formati;
19945   ULONGEST data_count, datai;
19946   const gdb_byte *buf = *bufp;
19947   const gdb_byte *format_header_data;
19948   unsigned int bytes_read;
19949
19950   format_count = read_1_byte (abfd, buf);
19951   buf += 1;
19952   format_header_data = buf;
19953   for (formati = 0; formati < format_count; formati++)
19954     {
19955       read_unsigned_leb128 (abfd, buf, &bytes_read);
19956       buf += bytes_read;
19957       read_unsigned_leb128 (abfd, buf, &bytes_read);
19958       buf += bytes_read;
19959     }
19960
19961   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
19962   buf += bytes_read;
19963   for (datai = 0; datai < data_count; datai++)
19964     {
19965       const gdb_byte *format = format_header_data;
19966       struct file_entry fe;
19967
19968       for (formati = 0; formati < format_count; formati++)
19969         {
19970           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
19971           format += bytes_read;
19972
19973           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
19974           format += bytes_read;
19975
19976           gdb::optional<const char *> string;
19977           gdb::optional<unsigned int> uint;
19978
19979           switch (form)
19980             {
19981             case DW_FORM_string:
19982               string.emplace (read_direct_string (abfd, buf, &bytes_read));
19983               buf += bytes_read;
19984               break;
19985
19986             case DW_FORM_line_strp:
19987               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
19988                                                          abfd, buf,
19989                                                          cu_header,
19990                                                          &bytes_read));
19991               buf += bytes_read;
19992               break;
19993
19994             case DW_FORM_data1:
19995               uint.emplace (read_1_byte (abfd, buf));
19996               buf += 1;
19997               break;
19998
19999             case DW_FORM_data2:
20000               uint.emplace (read_2_bytes (abfd, buf));
20001               buf += 2;
20002               break;
20003
20004             case DW_FORM_data4:
20005               uint.emplace (read_4_bytes (abfd, buf));
20006               buf += 4;
20007               break;
20008
20009             case DW_FORM_data8:
20010               uint.emplace (read_8_bytes (abfd, buf));
20011               buf += 8;
20012               break;
20013
20014             case DW_FORM_udata:
20015               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20016               buf += bytes_read;
20017               break;
20018
20019             case DW_FORM_block:
20020               /* It is valid only for DW_LNCT_timestamp which is ignored by
20021                  current GDB.  */
20022               break;
20023             }
20024
20025           switch (content_type)
20026             {
20027             case DW_LNCT_path:
20028               if (string.has_value ())
20029                 fe.name = *string;
20030               break;
20031             case DW_LNCT_directory_index:
20032               if (uint.has_value ())
20033                 fe.d_index = (dir_index) *uint;
20034               break;
20035             case DW_LNCT_timestamp:
20036               if (uint.has_value ())
20037                 fe.mod_time = *uint;
20038               break;
20039             case DW_LNCT_size:
20040               if (uint.has_value ())
20041                 fe.length = *uint;
20042               break;
20043             case DW_LNCT_MD5:
20044               break;
20045             default:
20046               complaint (_("Unknown format content type %s"),
20047                          pulongest (content_type));
20048             }
20049         }
20050
20051       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20052     }
20053
20054   *bufp = buf;
20055 }
20056
20057 /* Read the statement program header starting at OFFSET in
20058    .debug_line, or .debug_line.dwo.  Return a pointer
20059    to a struct line_header, allocated using xmalloc.
20060    Returns NULL if there is a problem reading the header, e.g., if it
20061    has a version we don't understand.
20062
20063    NOTE: the strings in the include directory and file name tables of
20064    the returned object point into the dwarf line section buffer,
20065    and must not be freed.  */
20066
20067 static line_header_up
20068 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20069 {
20070   const gdb_byte *line_ptr;
20071   unsigned int bytes_read, offset_size;
20072   int i;
20073   const char *cur_dir, *cur_file;
20074   struct dwarf2_section_info *section;
20075   bfd *abfd;
20076   struct dwarf2_per_objfile *dwarf2_per_objfile
20077     = cu->per_cu->dwarf2_per_objfile;
20078
20079   section = get_debug_line_section (cu);
20080   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20081   if (section->buffer == NULL)
20082     {
20083       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20084         complaint (_("missing .debug_line.dwo section"));
20085       else
20086         complaint (_("missing .debug_line section"));
20087       return 0;
20088     }
20089
20090   /* We can't do this until we know the section is non-empty.
20091      Only then do we know we have such a section.  */
20092   abfd = get_section_bfd_owner (section);
20093
20094   /* Make sure that at least there's room for the total_length field.
20095      That could be 12 bytes long, but we're just going to fudge that.  */
20096   if (to_underlying (sect_off) + 4 >= section->size)
20097     {
20098       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20099       return 0;
20100     }
20101
20102   line_header_up lh (new line_header ());
20103
20104   lh->sect_off = sect_off;
20105   lh->offset_in_dwz = cu->per_cu->is_dwz;
20106
20107   line_ptr = section->buffer + to_underlying (sect_off);
20108
20109   /* Read in the header.  */
20110   lh->total_length =
20111     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20112                                             &bytes_read, &offset_size);
20113   line_ptr += bytes_read;
20114   if (line_ptr + lh->total_length > (section->buffer + section->size))
20115     {
20116       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20117       return 0;
20118     }
20119   lh->statement_program_end = line_ptr + lh->total_length;
20120   lh->version = read_2_bytes (abfd, line_ptr);
20121   line_ptr += 2;
20122   if (lh->version > 5)
20123     {
20124       /* This is a version we don't understand.  The format could have
20125          changed in ways we don't handle properly so just punt.  */
20126       complaint (_("unsupported version in .debug_line section"));
20127       return NULL;
20128     }
20129   if (lh->version >= 5)
20130     {
20131       gdb_byte segment_selector_size;
20132
20133       /* Skip address size.  */
20134       read_1_byte (abfd, line_ptr);
20135       line_ptr += 1;
20136
20137       segment_selector_size = read_1_byte (abfd, line_ptr);
20138       line_ptr += 1;
20139       if (segment_selector_size != 0)
20140         {
20141           complaint (_("unsupported segment selector size %u "
20142                        "in .debug_line section"),
20143                      segment_selector_size);
20144           return NULL;
20145         }
20146     }
20147   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20148   line_ptr += offset_size;
20149   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20150   line_ptr += 1;
20151   if (lh->version >= 4)
20152     {
20153       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20154       line_ptr += 1;
20155     }
20156   else
20157     lh->maximum_ops_per_instruction = 1;
20158
20159   if (lh->maximum_ops_per_instruction == 0)
20160     {
20161       lh->maximum_ops_per_instruction = 1;
20162       complaint (_("invalid maximum_ops_per_instruction "
20163                    "in `.debug_line' section"));
20164     }
20165
20166   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20167   line_ptr += 1;
20168   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20169   line_ptr += 1;
20170   lh->line_range = read_1_byte (abfd, line_ptr);
20171   line_ptr += 1;
20172   lh->opcode_base = read_1_byte (abfd, line_ptr);
20173   line_ptr += 1;
20174   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20175
20176   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20177   for (i = 1; i < lh->opcode_base; ++i)
20178     {
20179       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20180       line_ptr += 1;
20181     }
20182
20183   if (lh->version >= 5)
20184     {
20185       /* Read directory table.  */
20186       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20187                               &cu->header,
20188                               [] (struct line_header *lh, const char *name,
20189                                   dir_index d_index, unsigned int mod_time,
20190                                   unsigned int length)
20191         {
20192           lh->add_include_dir (name);
20193         });
20194
20195       /* Read file name table.  */
20196       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20197                               &cu->header,
20198                               [] (struct line_header *lh, const char *name,
20199                                   dir_index d_index, unsigned int mod_time,
20200                                   unsigned int length)
20201         {
20202           lh->add_file_name (name, d_index, mod_time, length);
20203         });
20204     }
20205   else
20206     {
20207       /* Read directory table.  */
20208       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20209         {
20210           line_ptr += bytes_read;
20211           lh->add_include_dir (cur_dir);
20212         }
20213       line_ptr += bytes_read;
20214
20215       /* Read file name table.  */
20216       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20217         {
20218           unsigned int mod_time, length;
20219           dir_index d_index;
20220
20221           line_ptr += bytes_read;
20222           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20223           line_ptr += bytes_read;
20224           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20225           line_ptr += bytes_read;
20226           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20227           line_ptr += bytes_read;
20228
20229           lh->add_file_name (cur_file, d_index, mod_time, length);
20230         }
20231       line_ptr += bytes_read;
20232     }
20233   lh->statement_program_start = line_ptr;
20234
20235   if (line_ptr > (section->buffer + section->size))
20236     complaint (_("line number info header doesn't "
20237                  "fit in `.debug_line' section"));
20238
20239   return lh;
20240 }
20241
20242 /* Subroutine of dwarf_decode_lines to simplify it.
20243    Return the file name of the psymtab for included file FILE_INDEX
20244    in line header LH of PST.
20245    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20246    If space for the result is malloc'd, *NAME_HOLDER will be set.
20247    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20248
20249 static const char *
20250 psymtab_include_file_name (const struct line_header *lh, int file_index,
20251                            const struct partial_symtab *pst,
20252                            const char *comp_dir,
20253                            gdb::unique_xmalloc_ptr<char> *name_holder)
20254 {
20255   const file_entry &fe = lh->file_names[file_index];
20256   const char *include_name = fe.name;
20257   const char *include_name_to_compare = include_name;
20258   const char *pst_filename;
20259   int file_is_pst;
20260
20261   const char *dir_name = fe.include_dir (lh);
20262
20263   gdb::unique_xmalloc_ptr<char> hold_compare;
20264   if (!IS_ABSOLUTE_PATH (include_name)
20265       && (dir_name != NULL || comp_dir != NULL))
20266     {
20267       /* Avoid creating a duplicate psymtab for PST.
20268          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20269          Before we do the comparison, however, we need to account
20270          for DIR_NAME and COMP_DIR.
20271          First prepend dir_name (if non-NULL).  If we still don't
20272          have an absolute path prepend comp_dir (if non-NULL).
20273          However, the directory we record in the include-file's
20274          psymtab does not contain COMP_DIR (to match the
20275          corresponding symtab(s)).
20276
20277          Example:
20278
20279          bash$ cd /tmp
20280          bash$ gcc -g ./hello.c
20281          include_name = "hello.c"
20282          dir_name = "."
20283          DW_AT_comp_dir = comp_dir = "/tmp"
20284          DW_AT_name = "./hello.c"
20285
20286       */
20287
20288       if (dir_name != NULL)
20289         {
20290           name_holder->reset (concat (dir_name, SLASH_STRING,
20291                                       include_name, (char *) NULL));
20292           include_name = name_holder->get ();
20293           include_name_to_compare = include_name;
20294         }
20295       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20296         {
20297           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20298                                       include_name, (char *) NULL));
20299           include_name_to_compare = hold_compare.get ();
20300         }
20301     }
20302
20303   pst_filename = pst->filename;
20304   gdb::unique_xmalloc_ptr<char> copied_name;
20305   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20306     {
20307       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20308                                  pst_filename, (char *) NULL));
20309       pst_filename = copied_name.get ();
20310     }
20311
20312   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20313
20314   if (file_is_pst)
20315     return NULL;
20316   return include_name;
20317 }
20318
20319 /* State machine to track the state of the line number program.  */
20320
20321 class lnp_state_machine
20322 {
20323 public:
20324   /* Initialize a machine state for the start of a line number
20325      program.  */
20326   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20327
20328   file_entry *current_file ()
20329   {
20330     /* lh->file_names is 0-based, but the file name numbers in the
20331        statement program are 1-based.  */
20332     return m_line_header->file_name_at (m_file);
20333   }
20334
20335   /* Record the line in the state machine.  END_SEQUENCE is true if
20336      we're processing the end of a sequence.  */
20337   void record_line (bool end_sequence);
20338
20339   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20340      nop-out rest of the lines in this sequence.  */
20341   void check_line_address (struct dwarf2_cu *cu,
20342                            const gdb_byte *line_ptr,
20343                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20344
20345   void handle_set_discriminator (unsigned int discriminator)
20346   {
20347     m_discriminator = discriminator;
20348     m_line_has_non_zero_discriminator |= discriminator != 0;
20349   }
20350
20351   /* Handle DW_LNE_set_address.  */
20352   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20353   {
20354     m_op_index = 0;
20355     address += baseaddr;
20356     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20357   }
20358
20359   /* Handle DW_LNS_advance_pc.  */
20360   void handle_advance_pc (CORE_ADDR adjust);
20361
20362   /* Handle a special opcode.  */
20363   void handle_special_opcode (unsigned char op_code);
20364
20365   /* Handle DW_LNS_advance_line.  */
20366   void handle_advance_line (int line_delta)
20367   {
20368     advance_line (line_delta);
20369   }
20370
20371   /* Handle DW_LNS_set_file.  */
20372   void handle_set_file (file_name_index file);
20373
20374   /* Handle DW_LNS_negate_stmt.  */
20375   void handle_negate_stmt ()
20376   {
20377     m_is_stmt = !m_is_stmt;
20378   }
20379
20380   /* Handle DW_LNS_const_add_pc.  */
20381   void handle_const_add_pc ();
20382
20383   /* Handle DW_LNS_fixed_advance_pc.  */
20384   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20385   {
20386     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20387     m_op_index = 0;
20388   }
20389
20390   /* Handle DW_LNS_copy.  */
20391   void handle_copy ()
20392   {
20393     record_line (false);
20394     m_discriminator = 0;
20395   }
20396
20397   /* Handle DW_LNE_end_sequence.  */
20398   void handle_end_sequence ()
20399   {
20400     m_record_line_callback = ::record_line;
20401   }
20402
20403 private:
20404   /* Advance the line by LINE_DELTA.  */
20405   void advance_line (int line_delta)
20406   {
20407     m_line += line_delta;
20408
20409     if (line_delta != 0)
20410       m_line_has_non_zero_discriminator = m_discriminator != 0;
20411   }
20412
20413   gdbarch *m_gdbarch;
20414
20415   /* True if we're recording lines.
20416      Otherwise we're building partial symtabs and are just interested in
20417      finding include files mentioned by the line number program.  */
20418   bool m_record_lines_p;
20419
20420   /* The line number header.  */
20421   line_header *m_line_header;
20422
20423   /* These are part of the standard DWARF line number state machine,
20424      and initialized according to the DWARF spec.  */
20425
20426   unsigned char m_op_index = 0;
20427   /* The line table index (1-based) of the current file.  */
20428   file_name_index m_file = (file_name_index) 1;
20429   unsigned int m_line = 1;
20430
20431   /* These are initialized in the constructor.  */
20432
20433   CORE_ADDR m_address;
20434   bool m_is_stmt;
20435   unsigned int m_discriminator;
20436
20437   /* Additional bits of state we need to track.  */
20438
20439   /* The last file that we called dwarf2_start_subfile for.
20440      This is only used for TLLs.  */
20441   unsigned int m_last_file = 0;
20442   /* The last file a line number was recorded for.  */
20443   struct subfile *m_last_subfile = NULL;
20444
20445   /* The function to call to record a line.  */
20446   record_line_ftype *m_record_line_callback = NULL;
20447
20448   /* The last line number that was recorded, used to coalesce
20449      consecutive entries for the same line.  This can happen, for
20450      example, when discriminators are present.  PR 17276.  */
20451   unsigned int m_last_line = 0;
20452   bool m_line_has_non_zero_discriminator = false;
20453 };
20454
20455 void
20456 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20457 {
20458   CORE_ADDR addr_adj = (((m_op_index + adjust)
20459                          / m_line_header->maximum_ops_per_instruction)
20460                         * m_line_header->minimum_instruction_length);
20461   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20462   m_op_index = ((m_op_index + adjust)
20463                 % m_line_header->maximum_ops_per_instruction);
20464 }
20465
20466 void
20467 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20468 {
20469   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20470   CORE_ADDR addr_adj = (((m_op_index
20471                           + (adj_opcode / m_line_header->line_range))
20472                          / m_line_header->maximum_ops_per_instruction)
20473                         * m_line_header->minimum_instruction_length);
20474   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20475   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20476                 % m_line_header->maximum_ops_per_instruction);
20477
20478   int line_delta = (m_line_header->line_base
20479                     + (adj_opcode % m_line_header->line_range));
20480   advance_line (line_delta);
20481   record_line (false);
20482   m_discriminator = 0;
20483 }
20484
20485 void
20486 lnp_state_machine::handle_set_file (file_name_index file)
20487 {
20488   m_file = file;
20489
20490   const file_entry *fe = current_file ();
20491   if (fe == NULL)
20492     dwarf2_debug_line_missing_file_complaint ();
20493   else if (m_record_lines_p)
20494     {
20495       const char *dir = fe->include_dir (m_line_header);
20496
20497       m_last_subfile = current_subfile;
20498       m_line_has_non_zero_discriminator = m_discriminator != 0;
20499       dwarf2_start_subfile (fe->name, dir);
20500     }
20501 }
20502
20503 void
20504 lnp_state_machine::handle_const_add_pc ()
20505 {
20506   CORE_ADDR adjust
20507     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20508
20509   CORE_ADDR addr_adj
20510     = (((m_op_index + adjust)
20511         / m_line_header->maximum_ops_per_instruction)
20512        * m_line_header->minimum_instruction_length);
20513
20514   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20515   m_op_index = ((m_op_index + adjust)
20516                 % m_line_header->maximum_ops_per_instruction);
20517 }
20518
20519 /* Ignore this record_line request.  */
20520
20521 static void
20522 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20523 {
20524   return;
20525 }
20526
20527 /* Return non-zero if we should add LINE to the line number table.
20528    LINE is the line to add, LAST_LINE is the last line that was added,
20529    LAST_SUBFILE is the subfile for LAST_LINE.
20530    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20531    had a non-zero discriminator.
20532
20533    We have to be careful in the presence of discriminators.
20534    E.g., for this line:
20535
20536      for (i = 0; i < 100000; i++);
20537
20538    clang can emit four line number entries for that one line,
20539    each with a different discriminator.
20540    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20541
20542    However, we want gdb to coalesce all four entries into one.
20543    Otherwise the user could stepi into the middle of the line and
20544    gdb would get confused about whether the pc really was in the
20545    middle of the line.
20546
20547    Things are further complicated by the fact that two consecutive
20548    line number entries for the same line is a heuristic used by gcc
20549    to denote the end of the prologue.  So we can't just discard duplicate
20550    entries, we have to be selective about it.  The heuristic we use is
20551    that we only collapse consecutive entries for the same line if at least
20552    one of those entries has a non-zero discriminator.  PR 17276.
20553
20554    Note: Addresses in the line number state machine can never go backwards
20555    within one sequence, thus this coalescing is ok.  */
20556
20557 static int
20558 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20559                      int line_has_non_zero_discriminator,
20560                      struct subfile *last_subfile)
20561 {
20562   if (current_subfile != last_subfile)
20563     return 1;
20564   if (line != last_line)
20565     return 1;
20566   /* Same line for the same file that we've seen already.
20567      As a last check, for pr 17276, only record the line if the line
20568      has never had a non-zero discriminator.  */
20569   if (!line_has_non_zero_discriminator)
20570     return 1;
20571   return 0;
20572 }
20573
20574 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20575    in the line table of subfile SUBFILE.  */
20576
20577 static void
20578 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20579                      unsigned int line, CORE_ADDR address,
20580                      record_line_ftype p_record_line)
20581 {
20582   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20583
20584   if (dwarf_line_debug)
20585     {
20586       fprintf_unfiltered (gdb_stdlog,
20587                           "Recording line %u, file %s, address %s\n",
20588                           line, lbasename (subfile->name),
20589                           paddress (gdbarch, address));
20590     }
20591
20592   (*p_record_line) (subfile, line, addr);
20593 }
20594
20595 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20596    Mark the end of a set of line number records.
20597    The arguments are the same as for dwarf_record_line_1.
20598    If SUBFILE is NULL the request is ignored.  */
20599
20600 static void
20601 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20602                    CORE_ADDR address, record_line_ftype p_record_line)
20603 {
20604   if (subfile == NULL)
20605     return;
20606
20607   if (dwarf_line_debug)
20608     {
20609       fprintf_unfiltered (gdb_stdlog,
20610                           "Finishing current line, file %s, address %s\n",
20611                           lbasename (subfile->name),
20612                           paddress (gdbarch, address));
20613     }
20614
20615   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20616 }
20617
20618 void
20619 lnp_state_machine::record_line (bool end_sequence)
20620 {
20621   if (dwarf_line_debug)
20622     {
20623       fprintf_unfiltered (gdb_stdlog,
20624                           "Processing actual line %u: file %u,"
20625                           " address %s, is_stmt %u, discrim %u\n",
20626                           m_line, to_underlying (m_file),
20627                           paddress (m_gdbarch, m_address),
20628                           m_is_stmt, m_discriminator);
20629     }
20630
20631   file_entry *fe = current_file ();
20632
20633   if (fe == NULL)
20634     dwarf2_debug_line_missing_file_complaint ();
20635   /* For now we ignore lines not starting on an instruction boundary.
20636      But not when processing end_sequence for compatibility with the
20637      previous version of the code.  */
20638   else if (m_op_index == 0 || end_sequence)
20639     {
20640       fe->included_p = 1;
20641       if (m_record_lines_p && m_is_stmt)
20642         {
20643           if (m_last_subfile != current_subfile || end_sequence)
20644             {
20645               dwarf_finish_line (m_gdbarch, m_last_subfile,
20646                                  m_address, m_record_line_callback);
20647             }
20648
20649           if (!end_sequence)
20650             {
20651               if (dwarf_record_line_p (m_line, m_last_line,
20652                                        m_line_has_non_zero_discriminator,
20653                                        m_last_subfile))
20654                 {
20655                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20656                                        m_line, m_address,
20657                                        m_record_line_callback);
20658                 }
20659               m_last_subfile = current_subfile;
20660               m_last_line = m_line;
20661             }
20662         }
20663     }
20664 }
20665
20666 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20667                                       bool record_lines_p)
20668 {
20669   m_gdbarch = arch;
20670   m_record_lines_p = record_lines_p;
20671   m_line_header = lh;
20672
20673   m_record_line_callback = ::record_line;
20674
20675   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20676      was a line entry for it so that the backend has a chance to adjust it
20677      and also record it in case it needs it.  This is currently used by MIPS
20678      code, cf. `mips_adjust_dwarf2_line'.  */
20679   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20680   m_is_stmt = lh->default_is_stmt;
20681   m_discriminator = 0;
20682 }
20683
20684 void
20685 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20686                                        const gdb_byte *line_ptr,
20687                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20688 {
20689   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20690      the pc range of the CU.  However, we restrict the test to only ADDRESS
20691      values of zero to preserve GDB's previous behaviour which is to handle
20692      the specific case of a function being GC'd by the linker.  */
20693
20694   if (address == 0 && address < unrelocated_lowpc)
20695     {
20696       /* This line table is for a function which has been
20697          GCd by the linker.  Ignore it.  PR gdb/12528 */
20698
20699       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20700       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20701
20702       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20703                  line_offset, objfile_name (objfile));
20704       m_record_line_callback = noop_record_line;
20705       /* Note: record_line_callback is left as noop_record_line until
20706          we see DW_LNE_end_sequence.  */
20707     }
20708 }
20709
20710 /* Subroutine of dwarf_decode_lines to simplify it.
20711    Process the line number information in LH.
20712    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20713    program in order to set included_p for every referenced header.  */
20714
20715 static void
20716 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20717                       const int decode_for_pst_p, CORE_ADDR lowpc)
20718 {
20719   const gdb_byte *line_ptr, *extended_end;
20720   const gdb_byte *line_end;
20721   unsigned int bytes_read, extended_len;
20722   unsigned char op_code, extended_op;
20723   CORE_ADDR baseaddr;
20724   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20725   bfd *abfd = objfile->obfd;
20726   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20727   /* True if we're recording line info (as opposed to building partial
20728      symtabs and just interested in finding include files mentioned by
20729      the line number program).  */
20730   bool record_lines_p = !decode_for_pst_p;
20731
20732   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20733
20734   line_ptr = lh->statement_program_start;
20735   line_end = lh->statement_program_end;
20736
20737   /* Read the statement sequences until there's nothing left.  */
20738   while (line_ptr < line_end)
20739     {
20740       /* The DWARF line number program state machine.  Reset the state
20741          machine at the start of each sequence.  */
20742       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20743       bool end_sequence = false;
20744
20745       if (record_lines_p)
20746         {
20747           /* Start a subfile for the current file of the state
20748              machine.  */
20749           const file_entry *fe = state_machine.current_file ();
20750
20751           if (fe != NULL)
20752             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20753         }
20754
20755       /* Decode the table.  */
20756       while (line_ptr < line_end && !end_sequence)
20757         {
20758           op_code = read_1_byte (abfd, line_ptr);
20759           line_ptr += 1;
20760
20761           if (op_code >= lh->opcode_base)
20762             {
20763               /* Special opcode.  */
20764               state_machine.handle_special_opcode (op_code);
20765             }
20766           else switch (op_code)
20767             {
20768             case DW_LNS_extended_op:
20769               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20770                                                    &bytes_read);
20771               line_ptr += bytes_read;
20772               extended_end = line_ptr + extended_len;
20773               extended_op = read_1_byte (abfd, line_ptr);
20774               line_ptr += 1;
20775               switch (extended_op)
20776                 {
20777                 case DW_LNE_end_sequence:
20778                   state_machine.handle_end_sequence ();
20779                   end_sequence = true;
20780                   break;
20781                 case DW_LNE_set_address:
20782                   {
20783                     CORE_ADDR address
20784                       = read_address (abfd, line_ptr, cu, &bytes_read);
20785                     line_ptr += bytes_read;
20786
20787                     state_machine.check_line_address (cu, line_ptr,
20788                                                       lowpc - baseaddr, address);
20789                     state_machine.handle_set_address (baseaddr, address);
20790                   }
20791                   break;
20792                 case DW_LNE_define_file:
20793                   {
20794                     const char *cur_file;
20795                     unsigned int mod_time, length;
20796                     dir_index dindex;
20797
20798                     cur_file = read_direct_string (abfd, line_ptr,
20799                                                    &bytes_read);
20800                     line_ptr += bytes_read;
20801                     dindex = (dir_index)
20802                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20803                     line_ptr += bytes_read;
20804                     mod_time =
20805                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20806                     line_ptr += bytes_read;
20807                     length =
20808                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20809                     line_ptr += bytes_read;
20810                     lh->add_file_name (cur_file, dindex, mod_time, length);
20811                   }
20812                   break;
20813                 case DW_LNE_set_discriminator:
20814                   {
20815                     /* The discriminator is not interesting to the
20816                        debugger; just ignore it.  We still need to
20817                        check its value though:
20818                        if there are consecutive entries for the same
20819                        (non-prologue) line we want to coalesce them.
20820                        PR 17276.  */
20821                     unsigned int discr
20822                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20823                     line_ptr += bytes_read;
20824
20825                     state_machine.handle_set_discriminator (discr);
20826                   }
20827                   break;
20828                 default:
20829                   complaint (_("mangled .debug_line section"));
20830                   return;
20831                 }
20832               /* Make sure that we parsed the extended op correctly.  If e.g.
20833                  we expected a different address size than the producer used,
20834                  we may have read the wrong number of bytes.  */
20835               if (line_ptr != extended_end)
20836                 {
20837                   complaint (_("mangled .debug_line section"));
20838                   return;
20839                 }
20840               break;
20841             case DW_LNS_copy:
20842               state_machine.handle_copy ();
20843               break;
20844             case DW_LNS_advance_pc:
20845               {
20846                 CORE_ADDR adjust
20847                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20848                 line_ptr += bytes_read;
20849
20850                 state_machine.handle_advance_pc (adjust);
20851               }
20852               break;
20853             case DW_LNS_advance_line:
20854               {
20855                 int line_delta
20856                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20857                 line_ptr += bytes_read;
20858
20859                 state_machine.handle_advance_line (line_delta);
20860               }
20861               break;
20862             case DW_LNS_set_file:
20863               {
20864                 file_name_index file
20865                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20866                                                             &bytes_read);
20867                 line_ptr += bytes_read;
20868
20869                 state_machine.handle_set_file (file);
20870               }
20871               break;
20872             case DW_LNS_set_column:
20873               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20874               line_ptr += bytes_read;
20875               break;
20876             case DW_LNS_negate_stmt:
20877               state_machine.handle_negate_stmt ();
20878               break;
20879             case DW_LNS_set_basic_block:
20880               break;
20881             /* Add to the address register of the state machine the
20882                address increment value corresponding to special opcode
20883                255.  I.e., this value is scaled by the minimum
20884                instruction length since special opcode 255 would have
20885                scaled the increment.  */
20886             case DW_LNS_const_add_pc:
20887               state_machine.handle_const_add_pc ();
20888               break;
20889             case DW_LNS_fixed_advance_pc:
20890               {
20891                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20892                 line_ptr += 2;
20893
20894                 state_machine.handle_fixed_advance_pc (addr_adj);
20895               }
20896               break;
20897             default:
20898               {
20899                 /* Unknown standard opcode, ignore it.  */
20900                 int i;
20901
20902                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20903                   {
20904                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20905                     line_ptr += bytes_read;
20906                   }
20907               }
20908             }
20909         }
20910
20911       if (!end_sequence)
20912         dwarf2_debug_line_missing_end_sequence_complaint ();
20913
20914       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20915          in which case we still finish recording the last line).  */
20916       state_machine.record_line (true);
20917     }
20918 }
20919
20920 /* Decode the Line Number Program (LNP) for the given line_header
20921    structure and CU.  The actual information extracted and the type
20922    of structures created from the LNP depends on the value of PST.
20923
20924    1. If PST is NULL, then this procedure uses the data from the program
20925       to create all necessary symbol tables, and their linetables.
20926
20927    2. If PST is not NULL, this procedure reads the program to determine
20928       the list of files included by the unit represented by PST, and
20929       builds all the associated partial symbol tables.
20930
20931    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20932    It is used for relative paths in the line table.
20933    NOTE: When processing partial symtabs (pst != NULL),
20934    comp_dir == pst->dirname.
20935
20936    NOTE: It is important that psymtabs have the same file name (via strcmp)
20937    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20938    symtab we don't use it in the name of the psymtabs we create.
20939    E.g. expand_line_sal requires this when finding psymtabs to expand.
20940    A good testcase for this is mb-inline.exp.
20941
20942    LOWPC is the lowest address in CU (or 0 if not known).
20943
20944    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20945    for its PC<->lines mapping information.  Otherwise only the filename
20946    table is read in.  */
20947
20948 static void
20949 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20950                     struct dwarf2_cu *cu, struct partial_symtab *pst,
20951                     CORE_ADDR lowpc, int decode_mapping)
20952 {
20953   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20954   const int decode_for_pst_p = (pst != NULL);
20955
20956   if (decode_mapping)
20957     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
20958
20959   if (decode_for_pst_p)
20960     {
20961       int file_index;
20962
20963       /* Now that we're done scanning the Line Header Program, we can
20964          create the psymtab of each included file.  */
20965       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
20966         if (lh->file_names[file_index].included_p == 1)
20967           {
20968             gdb::unique_xmalloc_ptr<char> name_holder;
20969             const char *include_name =
20970               psymtab_include_file_name (lh, file_index, pst, comp_dir,
20971                                          &name_holder);
20972             if (include_name != NULL)
20973               dwarf2_create_include_psymtab (include_name, pst, objfile);
20974           }
20975     }
20976   else
20977     {
20978       /* Make sure a symtab is created for every file, even files
20979          which contain only variables (i.e. no code with associated
20980          line numbers).  */
20981       struct compunit_symtab *cust = buildsym_compunit_symtab ();
20982       int i;
20983
20984       for (i = 0; i < lh->file_names.size (); i++)
20985         {
20986           file_entry &fe = lh->file_names[i];
20987
20988           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
20989
20990           if (current_subfile->symtab == NULL)
20991             {
20992               current_subfile->symtab
20993                 = allocate_symtab (cust, current_subfile->name);
20994             }
20995           fe.symtab = current_subfile->symtab;
20996         }
20997     }
20998 }
20999
21000 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21001    DIRNAME the name of the source directory which contains FILENAME
21002    or NULL if not known.
21003    This routine tries to keep line numbers from identical absolute and
21004    relative file names in a common subfile.
21005
21006    Using the `list' example from the GDB testsuite, which resides in
21007    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21008    of /srcdir/list0.c yields the following debugging information for list0.c:
21009
21010    DW_AT_name:          /srcdir/list0.c
21011    DW_AT_comp_dir:      /compdir
21012    files.files[0].name: list0.h
21013    files.files[0].dir:  /srcdir
21014    files.files[1].name: list0.c
21015    files.files[1].dir:  /srcdir
21016
21017    The line number information for list0.c has to end up in a single
21018    subfile, so that `break /srcdir/list0.c:1' works as expected.
21019    start_subfile will ensure that this happens provided that we pass the
21020    concatenation of files.files[1].dir and files.files[1].name as the
21021    subfile's name.  */
21022
21023 static void
21024 dwarf2_start_subfile (const char *filename, const char *dirname)
21025 {
21026   char *copy = NULL;
21027
21028   /* In order not to lose the line information directory,
21029      we concatenate it to the filename when it makes sense.
21030      Note that the Dwarf3 standard says (speaking of filenames in line
21031      information): ``The directory index is ignored for file names
21032      that represent full path names''.  Thus ignoring dirname in the
21033      `else' branch below isn't an issue.  */
21034
21035   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21036     {
21037       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21038       filename = copy;
21039     }
21040
21041   start_subfile (filename);
21042
21043   if (copy != NULL)
21044     xfree (copy);
21045 }
21046
21047 /* Start a symtab for DWARF.
21048    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21049
21050 static struct compunit_symtab *
21051 dwarf2_start_symtab (struct dwarf2_cu *cu,
21052                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21053 {
21054   struct compunit_symtab *cust
21055     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21056                     low_pc, cu->language);
21057
21058   record_debugformat ("DWARF 2");
21059   record_producer (cu->producer);
21060
21061   /* We assume that we're processing GCC output.  */
21062   processing_gcc_compilation = 2;
21063
21064   cu->processing_has_namespace_info = 0;
21065
21066   return cust;
21067 }
21068
21069 static void
21070 var_decode_location (struct attribute *attr, struct symbol *sym,
21071                      struct dwarf2_cu *cu)
21072 {
21073   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21074   struct comp_unit_head *cu_header = &cu->header;
21075
21076   /* NOTE drow/2003-01-30: There used to be a comment and some special
21077      code here to turn a symbol with DW_AT_external and a
21078      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21079      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21080      with some versions of binutils) where shared libraries could have
21081      relocations against symbols in their debug information - the
21082      minimal symbol would have the right address, but the debug info
21083      would not.  It's no longer necessary, because we will explicitly
21084      apply relocations when we read in the debug information now.  */
21085
21086   /* A DW_AT_location attribute with no contents indicates that a
21087      variable has been optimized away.  */
21088   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21089     {
21090       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21091       return;
21092     }
21093
21094   /* Handle one degenerate form of location expression specially, to
21095      preserve GDB's previous behavior when section offsets are
21096      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21097      then mark this symbol as LOC_STATIC.  */
21098
21099   if (attr_form_is_block (attr)
21100       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21101            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21102           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21103               && (DW_BLOCK (attr)->size
21104                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21105     {
21106       unsigned int dummy;
21107
21108       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21109         SYMBOL_VALUE_ADDRESS (sym) =
21110           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21111       else
21112         SYMBOL_VALUE_ADDRESS (sym) =
21113           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21114       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21115       fixup_symbol_section (sym, objfile);
21116       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21117                                               SYMBOL_SECTION (sym));
21118       return;
21119     }
21120
21121   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21122      expression evaluator, and use LOC_COMPUTED only when necessary
21123      (i.e. when the value of a register or memory location is
21124      referenced, or a thread-local block, etc.).  Then again, it might
21125      not be worthwhile.  I'm assuming that it isn't unless performance
21126      or memory numbers show me otherwise.  */
21127
21128   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21129
21130   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21131     cu->has_loclist = 1;
21132 }
21133
21134 /* Given a pointer to a DWARF information entry, figure out if we need
21135    to make a symbol table entry for it, and if so, create a new entry
21136    and return a pointer to it.
21137    If TYPE is NULL, determine symbol type from the die, otherwise
21138    used the passed type.
21139    If SPACE is not NULL, use it to hold the new symbol.  If it is
21140    NULL, allocate a new symbol on the objfile's obstack.  */
21141
21142 static struct symbol *
21143 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21144             struct symbol *space)
21145 {
21146   struct dwarf2_per_objfile *dwarf2_per_objfile
21147     = cu->per_cu->dwarf2_per_objfile;
21148   struct objfile *objfile = dwarf2_per_objfile->objfile;
21149   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21150   struct symbol *sym = NULL;
21151   const char *name;
21152   struct attribute *attr = NULL;
21153   struct attribute *attr2 = NULL;
21154   CORE_ADDR baseaddr;
21155   struct pending **list_to_add = NULL;
21156
21157   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21158
21159   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21160
21161   name = dwarf2_name (die, cu);
21162   if (name)
21163     {
21164       const char *linkagename;
21165       int suppress_add = 0;
21166
21167       if (space)
21168         sym = space;
21169       else
21170         sym = allocate_symbol (objfile);
21171       OBJSTAT (objfile, n_syms++);
21172
21173       /* Cache this symbol's name and the name's demangled form (if any).  */
21174       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21175       linkagename = dwarf2_physname (name, die, cu);
21176       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21177
21178       /* Fortran does not have mangling standard and the mangling does differ
21179          between gfortran, iFort etc.  */
21180       if (cu->language == language_fortran
21181           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21182         symbol_set_demangled_name (&(sym->ginfo),
21183                                    dwarf2_full_name (name, die, cu),
21184                                    NULL);
21185
21186       /* Default assumptions.
21187          Use the passed type or decode it from the die.  */
21188       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21189       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21190       if (type != NULL)
21191         SYMBOL_TYPE (sym) = type;
21192       else
21193         SYMBOL_TYPE (sym) = die_type (die, cu);
21194       attr = dwarf2_attr (die,
21195                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21196                           cu);
21197       if (attr)
21198         {
21199           SYMBOL_LINE (sym) = DW_UNSND (attr);
21200         }
21201
21202       attr = dwarf2_attr (die,
21203                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21204                           cu);
21205       if (attr)
21206         {
21207           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21208           struct file_entry *fe;
21209
21210           if (cu->line_header != NULL)
21211             fe = cu->line_header->file_name_at (file_index);
21212           else
21213             fe = NULL;
21214
21215           if (fe == NULL)
21216             complaint (_("file index out of range"));
21217           else
21218             symbol_set_symtab (sym, fe->symtab);
21219         }
21220
21221       switch (die->tag)
21222         {
21223         case DW_TAG_label:
21224           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21225           if (attr)
21226             {
21227               CORE_ADDR addr;
21228
21229               addr = attr_value_as_address (attr);
21230               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21231               SYMBOL_VALUE_ADDRESS (sym) = addr;
21232             }
21233           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21234           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21235           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21236           dw2_add_symbol_to_list (sym, cu->list_in_scope);
21237           break;
21238         case DW_TAG_subprogram:
21239           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21240              finish_block.  */
21241           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21242           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21243           if ((attr2 && (DW_UNSND (attr2) != 0))
21244               || cu->language == language_ada)
21245             {
21246               /* Subprograms marked external are stored as a global symbol.
21247                  Ada subprograms, whether marked external or not, are always
21248                  stored as a global symbol, because we want to be able to
21249                  access them globally.  For instance, we want to be able
21250                  to break on a nested subprogram without having to
21251                  specify the context.  */
21252               list_to_add = &global_symbols;
21253             }
21254           else
21255             {
21256               list_to_add = cu->list_in_scope;
21257             }
21258           break;
21259         case DW_TAG_inlined_subroutine:
21260           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21261              finish_block.  */
21262           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21263           SYMBOL_INLINED (sym) = 1;
21264           list_to_add = cu->list_in_scope;
21265           break;
21266         case DW_TAG_template_value_param:
21267           suppress_add = 1;
21268           /* Fall through.  */
21269         case DW_TAG_constant:
21270         case DW_TAG_variable:
21271         case DW_TAG_member:
21272           /* Compilation with minimal debug info may result in
21273              variables with missing type entries.  Change the
21274              misleading `void' type to something sensible.  */
21275           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21276             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21277
21278           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21279           /* In the case of DW_TAG_member, we should only be called for
21280              static const members.  */
21281           if (die->tag == DW_TAG_member)
21282             {
21283               /* dwarf2_add_field uses die_is_declaration,
21284                  so we do the same.  */
21285               gdb_assert (die_is_declaration (die, cu));
21286               gdb_assert (attr);
21287             }
21288           if (attr)
21289             {
21290               dwarf2_const_value (attr, sym, cu);
21291               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21292               if (!suppress_add)
21293                 {
21294                   if (attr2 && (DW_UNSND (attr2) != 0))
21295                     list_to_add = &global_symbols;
21296                   else
21297                     list_to_add = cu->list_in_scope;
21298                 }
21299               break;
21300             }
21301           attr = dwarf2_attr (die, DW_AT_location, cu);
21302           if (attr)
21303             {
21304               var_decode_location (attr, sym, cu);
21305               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21306
21307               /* Fortran explicitly imports any global symbols to the local
21308                  scope by DW_TAG_common_block.  */
21309               if (cu->language == language_fortran && die->parent
21310                   && die->parent->tag == DW_TAG_common_block)
21311                 attr2 = NULL;
21312
21313               if (SYMBOL_CLASS (sym) == LOC_STATIC
21314                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21315                   && !dwarf2_per_objfile->has_section_at_zero)
21316                 {
21317                   /* When a static variable is eliminated by the linker,
21318                      the corresponding debug information is not stripped
21319                      out, but the variable address is set to null;
21320                      do not add such variables into symbol table.  */
21321                 }
21322               else if (attr2 && (DW_UNSND (attr2) != 0))
21323                 {
21324                   /* Workaround gfortran PR debug/40040 - it uses
21325                      DW_AT_location for variables in -fPIC libraries which may
21326                      get overriden by other libraries/executable and get
21327                      a different address.  Resolve it by the minimal symbol
21328                      which may come from inferior's executable using copy
21329                      relocation.  Make this workaround only for gfortran as for
21330                      other compilers GDB cannot guess the minimal symbol
21331                      Fortran mangling kind.  */
21332                   if (cu->language == language_fortran && die->parent
21333                       && die->parent->tag == DW_TAG_module
21334                       && cu->producer
21335                       && startswith (cu->producer, "GNU Fortran"))
21336                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21337
21338                   /* A variable with DW_AT_external is never static,
21339                      but it may be block-scoped.  */
21340                   list_to_add = (cu->list_in_scope == &file_symbols
21341                                  ? &global_symbols : cu->list_in_scope);
21342                 }
21343               else
21344                 list_to_add = cu->list_in_scope;
21345             }
21346           else
21347             {
21348               /* We do not know the address of this symbol.
21349                  If it is an external symbol and we have type information
21350                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21351                  The address of the variable will then be determined from
21352                  the minimal symbol table whenever the variable is
21353                  referenced.  */
21354               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21355
21356               /* Fortran explicitly imports any global symbols to the local
21357                  scope by DW_TAG_common_block.  */
21358               if (cu->language == language_fortran && die->parent
21359                   && die->parent->tag == DW_TAG_common_block)
21360                 {
21361                   /* SYMBOL_CLASS doesn't matter here because
21362                      read_common_block is going to reset it.  */
21363                   if (!suppress_add)
21364                     list_to_add = cu->list_in_scope;
21365                 }
21366               else if (attr2 && (DW_UNSND (attr2) != 0)
21367                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21368                 {
21369                   /* A variable with DW_AT_external is never static, but it
21370                      may be block-scoped.  */
21371                   list_to_add = (cu->list_in_scope == &file_symbols
21372                                  ? &global_symbols : cu->list_in_scope);
21373
21374                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21375                 }
21376               else if (!die_is_declaration (die, cu))
21377                 {
21378                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21379                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21380                   if (!suppress_add)
21381                     list_to_add = cu->list_in_scope;
21382                 }
21383             }
21384           break;
21385         case DW_TAG_formal_parameter:
21386           /* If we are inside a function, mark this as an argument.  If
21387              not, we might be looking at an argument to an inlined function
21388              when we do not have enough information to show inlined frames;
21389              pretend it's a local variable in that case so that the user can
21390              still see it.  */
21391           if (context_stack_depth > 0
21392               && context_stack[context_stack_depth - 1].name != NULL)
21393             SYMBOL_IS_ARGUMENT (sym) = 1;
21394           attr = dwarf2_attr (die, DW_AT_location, cu);
21395           if (attr)
21396             {
21397               var_decode_location (attr, sym, cu);
21398             }
21399           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21400           if (attr)
21401             {
21402               dwarf2_const_value (attr, sym, cu);
21403             }
21404
21405           list_to_add = cu->list_in_scope;
21406           break;
21407         case DW_TAG_unspecified_parameters:
21408           /* From varargs functions; gdb doesn't seem to have any
21409              interest in this information, so just ignore it for now.
21410              (FIXME?) */
21411           break;
21412         case DW_TAG_template_type_param:
21413           suppress_add = 1;
21414           /* Fall through.  */
21415         case DW_TAG_class_type:
21416         case DW_TAG_interface_type:
21417         case DW_TAG_structure_type:
21418         case DW_TAG_union_type:
21419         case DW_TAG_set_type:
21420         case DW_TAG_enumeration_type:
21421           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21422           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21423
21424           {
21425             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21426                really ever be static objects: otherwise, if you try
21427                to, say, break of a class's method and you're in a file
21428                which doesn't mention that class, it won't work unless
21429                the check for all static symbols in lookup_symbol_aux
21430                saves you.  See the OtherFileClass tests in
21431                gdb.c++/namespace.exp.  */
21432
21433             if (!suppress_add)
21434               {
21435                 list_to_add = (cu->list_in_scope == &file_symbols
21436                                && cu->language == language_cplus
21437                                ? &global_symbols : cu->list_in_scope);
21438
21439                 /* The semantics of C++ state that "struct foo {
21440                    ... }" also defines a typedef for "foo".  */
21441                 if (cu->language == language_cplus
21442                     || cu->language == language_ada
21443                     || cu->language == language_d
21444                     || cu->language == language_rust)
21445                   {
21446                     /* The symbol's name is already allocated along
21447                        with this objfile, so we don't need to
21448                        duplicate it for the type.  */
21449                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21450                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21451                   }
21452               }
21453           }
21454           break;
21455         case DW_TAG_typedef:
21456           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21457           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21458           list_to_add = cu->list_in_scope;
21459           break;
21460         case DW_TAG_base_type:
21461         case DW_TAG_subrange_type:
21462           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21463           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21464           list_to_add = cu->list_in_scope;
21465           break;
21466         case DW_TAG_enumerator:
21467           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21468           if (attr)
21469             {
21470               dwarf2_const_value (attr, sym, cu);
21471             }
21472           {
21473             /* NOTE: carlton/2003-11-10: See comment above in the
21474                DW_TAG_class_type, etc. block.  */
21475
21476             list_to_add = (cu->list_in_scope == &file_symbols
21477                            && cu->language == language_cplus
21478                            ? &global_symbols : cu->list_in_scope);
21479           }
21480           break;
21481         case DW_TAG_imported_declaration:
21482         case DW_TAG_namespace:
21483           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21484           list_to_add = &global_symbols;
21485           break;
21486         case DW_TAG_module:
21487           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21488           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21489           list_to_add = &global_symbols;
21490           break;
21491         case DW_TAG_common_block:
21492           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21493           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21494           dw2_add_symbol_to_list (sym, cu->list_in_scope);
21495           break;
21496         default:
21497           /* Not a tag we recognize.  Hopefully we aren't processing
21498              trash data, but since we must specifically ignore things
21499              we don't recognize, there is nothing else we should do at
21500              this point.  */
21501           complaint (_("unsupported tag: '%s'"),
21502                      dwarf_tag_name (die->tag));
21503           break;
21504         }
21505
21506       if (suppress_add)
21507         {
21508           sym->hash_next = objfile->template_symbols;
21509           objfile->template_symbols = sym;
21510           list_to_add = NULL;
21511         }
21512
21513       if (list_to_add != NULL)
21514         dw2_add_symbol_to_list (sym, list_to_add);
21515
21516       /* For the benefit of old versions of GCC, check for anonymous
21517          namespaces based on the demangled name.  */
21518       if (!cu->processing_has_namespace_info
21519           && cu->language == language_cplus)
21520         cp_scan_for_anonymous_namespaces (sym, objfile);
21521     }
21522   return (sym);
21523 }
21524
21525 /* Given an attr with a DW_FORM_dataN value in host byte order,
21526    zero-extend it as appropriate for the symbol's type.  The DWARF
21527    standard (v4) is not entirely clear about the meaning of using
21528    DW_FORM_dataN for a constant with a signed type, where the type is
21529    wider than the data.  The conclusion of a discussion on the DWARF
21530    list was that this is unspecified.  We choose to always zero-extend
21531    because that is the interpretation long in use by GCC.  */
21532
21533 static gdb_byte *
21534 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21535                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21536 {
21537   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21538   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21539                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21540   LONGEST l = DW_UNSND (attr);
21541
21542   if (bits < sizeof (*value) * 8)
21543     {
21544       l &= ((LONGEST) 1 << bits) - 1;
21545       *value = l;
21546     }
21547   else if (bits == sizeof (*value) * 8)
21548     *value = l;
21549   else
21550     {
21551       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21552       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21553       return bytes;
21554     }
21555
21556   return NULL;
21557 }
21558
21559 /* Read a constant value from an attribute.  Either set *VALUE, or if
21560    the value does not fit in *VALUE, set *BYTES - either already
21561    allocated on the objfile obstack, or newly allocated on OBSTACK,
21562    or, set *BATON, if we translated the constant to a location
21563    expression.  */
21564
21565 static void
21566 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21567                          const char *name, struct obstack *obstack,
21568                          struct dwarf2_cu *cu,
21569                          LONGEST *value, const gdb_byte **bytes,
21570                          struct dwarf2_locexpr_baton **baton)
21571 {
21572   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21573   struct comp_unit_head *cu_header = &cu->header;
21574   struct dwarf_block *blk;
21575   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21576                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21577
21578   *value = 0;
21579   *bytes = NULL;
21580   *baton = NULL;
21581
21582   switch (attr->form)
21583     {
21584     case DW_FORM_addr:
21585     case DW_FORM_GNU_addr_index:
21586       {
21587         gdb_byte *data;
21588
21589         if (TYPE_LENGTH (type) != cu_header->addr_size)
21590           dwarf2_const_value_length_mismatch_complaint (name,
21591                                                         cu_header->addr_size,
21592                                                         TYPE_LENGTH (type));
21593         /* Symbols of this form are reasonably rare, so we just
21594            piggyback on the existing location code rather than writing
21595            a new implementation of symbol_computed_ops.  */
21596         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21597         (*baton)->per_cu = cu->per_cu;
21598         gdb_assert ((*baton)->per_cu);
21599
21600         (*baton)->size = 2 + cu_header->addr_size;
21601         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21602         (*baton)->data = data;
21603
21604         data[0] = DW_OP_addr;
21605         store_unsigned_integer (&data[1], cu_header->addr_size,
21606                                 byte_order, DW_ADDR (attr));
21607         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21608       }
21609       break;
21610     case DW_FORM_string:
21611     case DW_FORM_strp:
21612     case DW_FORM_GNU_str_index:
21613     case DW_FORM_GNU_strp_alt:
21614       /* DW_STRING is already allocated on the objfile obstack, point
21615          directly to it.  */
21616       *bytes = (const gdb_byte *) DW_STRING (attr);
21617       break;
21618     case DW_FORM_block1:
21619     case DW_FORM_block2:
21620     case DW_FORM_block4:
21621     case DW_FORM_block:
21622     case DW_FORM_exprloc:
21623     case DW_FORM_data16:
21624       blk = DW_BLOCK (attr);
21625       if (TYPE_LENGTH (type) != blk->size)
21626         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21627                                                       TYPE_LENGTH (type));
21628       *bytes = blk->data;
21629       break;
21630
21631       /* The DW_AT_const_value attributes are supposed to carry the
21632          symbol's value "represented as it would be on the target
21633          architecture."  By the time we get here, it's already been
21634          converted to host endianness, so we just need to sign- or
21635          zero-extend it as appropriate.  */
21636     case DW_FORM_data1:
21637       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21638       break;
21639     case DW_FORM_data2:
21640       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21641       break;
21642     case DW_FORM_data4:
21643       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21644       break;
21645     case DW_FORM_data8:
21646       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21647       break;
21648
21649     case DW_FORM_sdata:
21650     case DW_FORM_implicit_const:
21651       *value = DW_SND (attr);
21652       break;
21653
21654     case DW_FORM_udata:
21655       *value = DW_UNSND (attr);
21656       break;
21657
21658     default:
21659       complaint (_("unsupported const value attribute form: '%s'"),
21660                  dwarf_form_name (attr->form));
21661       *value = 0;
21662       break;
21663     }
21664 }
21665
21666
21667 /* Copy constant value from an attribute to a symbol.  */
21668
21669 static void
21670 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21671                     struct dwarf2_cu *cu)
21672 {
21673   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21674   LONGEST value;
21675   const gdb_byte *bytes;
21676   struct dwarf2_locexpr_baton *baton;
21677
21678   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21679                            SYMBOL_PRINT_NAME (sym),
21680                            &objfile->objfile_obstack, cu,
21681                            &value, &bytes, &baton);
21682
21683   if (baton != NULL)
21684     {
21685       SYMBOL_LOCATION_BATON (sym) = baton;
21686       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21687     }
21688   else if (bytes != NULL)
21689      {
21690       SYMBOL_VALUE_BYTES (sym) = bytes;
21691       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21692     }
21693   else
21694     {
21695       SYMBOL_VALUE (sym) = value;
21696       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21697     }
21698 }
21699
21700 /* Return the type of the die in question using its DW_AT_type attribute.  */
21701
21702 static struct type *
21703 die_type (struct die_info *die, struct dwarf2_cu *cu)
21704 {
21705   struct attribute *type_attr;
21706
21707   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21708   if (!type_attr)
21709     {
21710       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21711       /* A missing DW_AT_type represents a void type.  */
21712       return objfile_type (objfile)->builtin_void;
21713     }
21714
21715   return lookup_die_type (die, type_attr, cu);
21716 }
21717
21718 /* True iff CU's producer generates GNAT Ada auxiliary information
21719    that allows to find parallel types through that information instead
21720    of having to do expensive parallel lookups by type name.  */
21721
21722 static int
21723 need_gnat_info (struct dwarf2_cu *cu)
21724 {
21725   /* Assume that the Ada compiler was GNAT, which always produces
21726      the auxiliary information.  */
21727   return (cu->language == language_ada);
21728 }
21729
21730 /* Return the auxiliary type of the die in question using its
21731    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21732    attribute is not present.  */
21733
21734 static struct type *
21735 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21736 {
21737   struct attribute *type_attr;
21738
21739   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21740   if (!type_attr)
21741     return NULL;
21742
21743   return lookup_die_type (die, type_attr, cu);
21744 }
21745
21746 /* If DIE has a descriptive_type attribute, then set the TYPE's
21747    descriptive type accordingly.  */
21748
21749 static void
21750 set_descriptive_type (struct type *type, struct die_info *die,
21751                       struct dwarf2_cu *cu)
21752 {
21753   struct type *descriptive_type = die_descriptive_type (die, cu);
21754
21755   if (descriptive_type)
21756     {
21757       ALLOCATE_GNAT_AUX_TYPE (type);
21758       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21759     }
21760 }
21761
21762 /* Return the containing type of the die in question using its
21763    DW_AT_containing_type attribute.  */
21764
21765 static struct type *
21766 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21767 {
21768   struct attribute *type_attr;
21769   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21770
21771   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21772   if (!type_attr)
21773     error (_("Dwarf Error: Problem turning containing type into gdb type "
21774              "[in module %s]"), objfile_name (objfile));
21775
21776   return lookup_die_type (die, type_attr, cu);
21777 }
21778
21779 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21780
21781 static struct type *
21782 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21783 {
21784   struct dwarf2_per_objfile *dwarf2_per_objfile
21785     = cu->per_cu->dwarf2_per_objfile;
21786   struct objfile *objfile = dwarf2_per_objfile->objfile;
21787   char *message, *saved;
21788
21789   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
21790                         objfile_name (objfile),
21791                         sect_offset_str (cu->header.sect_off),
21792                         sect_offset_str (die->sect_off));
21793   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21794                                   message, strlen (message));
21795   xfree (message);
21796
21797   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21798 }
21799
21800 /* Look up the type of DIE in CU using its type attribute ATTR.
21801    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21802    DW_AT_containing_type.
21803    If there is no type substitute an error marker.  */
21804
21805 static struct type *
21806 lookup_die_type (struct die_info *die, const struct attribute *attr,
21807                  struct dwarf2_cu *cu)
21808 {
21809   struct dwarf2_per_objfile *dwarf2_per_objfile
21810     = cu->per_cu->dwarf2_per_objfile;
21811   struct objfile *objfile = dwarf2_per_objfile->objfile;
21812   struct type *this_type;
21813
21814   gdb_assert (attr->name == DW_AT_type
21815               || attr->name == DW_AT_GNAT_descriptive_type
21816               || attr->name == DW_AT_containing_type);
21817
21818   /* First see if we have it cached.  */
21819
21820   if (attr->form == DW_FORM_GNU_ref_alt)
21821     {
21822       struct dwarf2_per_cu_data *per_cu;
21823       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21824
21825       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21826                                                  dwarf2_per_objfile);
21827       this_type = get_die_type_at_offset (sect_off, per_cu);
21828     }
21829   else if (attr_form_is_ref (attr))
21830     {
21831       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21832
21833       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21834     }
21835   else if (attr->form == DW_FORM_ref_sig8)
21836     {
21837       ULONGEST signature = DW_SIGNATURE (attr);
21838
21839       return get_signatured_type (die, signature, cu);
21840     }
21841   else
21842     {
21843       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
21844                    " at %s [in module %s]"),
21845                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21846                  objfile_name (objfile));
21847       return build_error_marker_type (cu, die);
21848     }
21849
21850   /* If not cached we need to read it in.  */
21851
21852   if (this_type == NULL)
21853     {
21854       struct die_info *type_die = NULL;
21855       struct dwarf2_cu *type_cu = cu;
21856
21857       if (attr_form_is_ref (attr))
21858         type_die = follow_die_ref (die, attr, &type_cu);
21859       if (type_die == NULL)
21860         return build_error_marker_type (cu, die);
21861       /* If we find the type now, it's probably because the type came
21862          from an inter-CU reference and the type's CU got expanded before
21863          ours.  */
21864       this_type = read_type_die (type_die, type_cu);
21865     }
21866
21867   /* If we still don't have a type use an error marker.  */
21868
21869   if (this_type == NULL)
21870     return build_error_marker_type (cu, die);
21871
21872   return this_type;
21873 }
21874
21875 /* Return the type in DIE, CU.
21876    Returns NULL for invalid types.
21877
21878    This first does a lookup in die_type_hash,
21879    and only reads the die in if necessary.
21880
21881    NOTE: This can be called when reading in partial or full symbols.  */
21882
21883 static struct type *
21884 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21885 {
21886   struct type *this_type;
21887
21888   this_type = get_die_type (die, cu);
21889   if (this_type)
21890     return this_type;
21891
21892   return read_type_die_1 (die, cu);
21893 }
21894
21895 /* Read the type in DIE, CU.
21896    Returns NULL for invalid types.  */
21897
21898 static struct type *
21899 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21900 {
21901   struct type *this_type = NULL;
21902
21903   switch (die->tag)
21904     {
21905     case DW_TAG_class_type:
21906     case DW_TAG_interface_type:
21907     case DW_TAG_structure_type:
21908     case DW_TAG_union_type:
21909       this_type = read_structure_type (die, cu);
21910       break;
21911     case DW_TAG_enumeration_type:
21912       this_type = read_enumeration_type (die, cu);
21913       break;
21914     case DW_TAG_subprogram:
21915     case DW_TAG_subroutine_type:
21916     case DW_TAG_inlined_subroutine:
21917       this_type = read_subroutine_type (die, cu);
21918       break;
21919     case DW_TAG_array_type:
21920       this_type = read_array_type (die, cu);
21921       break;
21922     case DW_TAG_set_type:
21923       this_type = read_set_type (die, cu);
21924       break;
21925     case DW_TAG_pointer_type:
21926       this_type = read_tag_pointer_type (die, cu);
21927       break;
21928     case DW_TAG_ptr_to_member_type:
21929       this_type = read_tag_ptr_to_member_type (die, cu);
21930       break;
21931     case DW_TAG_reference_type:
21932       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21933       break;
21934     case DW_TAG_rvalue_reference_type:
21935       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21936       break;
21937     case DW_TAG_const_type:
21938       this_type = read_tag_const_type (die, cu);
21939       break;
21940     case DW_TAG_volatile_type:
21941       this_type = read_tag_volatile_type (die, cu);
21942       break;
21943     case DW_TAG_restrict_type:
21944       this_type = read_tag_restrict_type (die, cu);
21945       break;
21946     case DW_TAG_string_type:
21947       this_type = read_tag_string_type (die, cu);
21948       break;
21949     case DW_TAG_typedef:
21950       this_type = read_typedef (die, cu);
21951       break;
21952     case DW_TAG_subrange_type:
21953       this_type = read_subrange_type (die, cu);
21954       break;
21955     case DW_TAG_base_type:
21956       this_type = read_base_type (die, cu);
21957       break;
21958     case DW_TAG_unspecified_type:
21959       this_type = read_unspecified_type (die, cu);
21960       break;
21961     case DW_TAG_namespace:
21962       this_type = read_namespace_type (die, cu);
21963       break;
21964     case DW_TAG_module:
21965       this_type = read_module_type (die, cu);
21966       break;
21967     case DW_TAG_atomic_type:
21968       this_type = read_tag_atomic_type (die, cu);
21969       break;
21970     default:
21971       complaint (_("unexpected tag in read_type_die: '%s'"),
21972                  dwarf_tag_name (die->tag));
21973       break;
21974     }
21975
21976   return this_type;
21977 }
21978
21979 /* See if we can figure out if the class lives in a namespace.  We do
21980    this by looking for a member function; its demangled name will
21981    contain namespace info, if there is any.
21982    Return the computed name or NULL.
21983    Space for the result is allocated on the objfile's obstack.
21984    This is the full-die version of guess_partial_die_structure_name.
21985    In this case we know DIE has no useful parent.  */
21986
21987 static char *
21988 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
21989 {
21990   struct die_info *spec_die;
21991   struct dwarf2_cu *spec_cu;
21992   struct die_info *child;
21993   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21994
21995   spec_cu = cu;
21996   spec_die = die_specification (die, &spec_cu);
21997   if (spec_die != NULL)
21998     {
21999       die = spec_die;
22000       cu = spec_cu;
22001     }
22002
22003   for (child = die->child;
22004        child != NULL;
22005        child = child->sibling)
22006     {
22007       if (child->tag == DW_TAG_subprogram)
22008         {
22009           const char *linkage_name = dw2_linkage_name (child, cu);
22010
22011           if (linkage_name != NULL)
22012             {
22013               char *actual_name
22014                 = language_class_name_from_physname (cu->language_defn,
22015                                                      linkage_name);
22016               char *name = NULL;
22017
22018               if (actual_name != NULL)
22019                 {
22020                   const char *die_name = dwarf2_name (die, cu);
22021
22022                   if (die_name != NULL
22023                       && strcmp (die_name, actual_name) != 0)
22024                     {
22025                       /* Strip off the class name from the full name.
22026                          We want the prefix.  */
22027                       int die_name_len = strlen (die_name);
22028                       int actual_name_len = strlen (actual_name);
22029
22030                       /* Test for '::' as a sanity check.  */
22031                       if (actual_name_len > die_name_len + 2
22032                           && actual_name[actual_name_len
22033                                          - die_name_len - 1] == ':')
22034                         name = (char *) obstack_copy0 (
22035                           &objfile->per_bfd->storage_obstack,
22036                           actual_name, actual_name_len - die_name_len - 2);
22037                     }
22038                 }
22039               xfree (actual_name);
22040               return name;
22041             }
22042         }
22043     }
22044
22045   return NULL;
22046 }
22047
22048 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22049    prefix part in such case.  See
22050    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22051
22052 static const char *
22053 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22054 {
22055   struct attribute *attr;
22056   const char *base;
22057
22058   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22059       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22060     return NULL;
22061
22062   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22063     return NULL;
22064
22065   attr = dw2_linkage_name_attr (die, cu);
22066   if (attr == NULL || DW_STRING (attr) == NULL)
22067     return NULL;
22068
22069   /* dwarf2_name had to be already called.  */
22070   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22071
22072   /* Strip the base name, keep any leading namespaces/classes.  */
22073   base = strrchr (DW_STRING (attr), ':');
22074   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22075     return "";
22076
22077   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22078   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22079                                  DW_STRING (attr),
22080                                  &base[-1] - DW_STRING (attr));
22081 }
22082
22083 /* Return the name of the namespace/class that DIE is defined within,
22084    or "" if we can't tell.  The caller should not xfree the result.
22085
22086    For example, if we're within the method foo() in the following
22087    code:
22088
22089    namespace N {
22090      class C {
22091        void foo () {
22092        }
22093      };
22094    }
22095
22096    then determine_prefix on foo's die will return "N::C".  */
22097
22098 static const char *
22099 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22100 {
22101   struct dwarf2_per_objfile *dwarf2_per_objfile
22102     = cu->per_cu->dwarf2_per_objfile;
22103   struct die_info *parent, *spec_die;
22104   struct dwarf2_cu *spec_cu;
22105   struct type *parent_type;
22106   const char *retval;
22107
22108   if (cu->language != language_cplus
22109       && cu->language != language_fortran && cu->language != language_d
22110       && cu->language != language_rust)
22111     return "";
22112
22113   retval = anonymous_struct_prefix (die, cu);
22114   if (retval)
22115     return retval;
22116
22117   /* We have to be careful in the presence of DW_AT_specification.
22118      For example, with GCC 3.4, given the code
22119
22120      namespace N {
22121        void foo() {
22122          // Definition of N::foo.
22123        }
22124      }
22125
22126      then we'll have a tree of DIEs like this:
22127
22128      1: DW_TAG_compile_unit
22129        2: DW_TAG_namespace        // N
22130          3: DW_TAG_subprogram     // declaration of N::foo
22131        4: DW_TAG_subprogram       // definition of N::foo
22132             DW_AT_specification   // refers to die #3
22133
22134      Thus, when processing die #4, we have to pretend that we're in
22135      the context of its DW_AT_specification, namely the contex of die
22136      #3.  */
22137   spec_cu = cu;
22138   spec_die = die_specification (die, &spec_cu);
22139   if (spec_die == NULL)
22140     parent = die->parent;
22141   else
22142     {
22143       parent = spec_die->parent;
22144       cu = spec_cu;
22145     }
22146
22147   if (parent == NULL)
22148     return "";
22149   else if (parent->building_fullname)
22150     {
22151       const char *name;
22152       const char *parent_name;
22153
22154       /* It has been seen on RealView 2.2 built binaries,
22155          DW_TAG_template_type_param types actually _defined_ as
22156          children of the parent class:
22157
22158          enum E {};
22159          template class <class Enum> Class{};
22160          Class<enum E> class_e;
22161
22162          1: DW_TAG_class_type (Class)
22163            2: DW_TAG_enumeration_type (E)
22164              3: DW_TAG_enumerator (enum1:0)
22165              3: DW_TAG_enumerator (enum2:1)
22166              ...
22167            2: DW_TAG_template_type_param
22168               DW_AT_type  DW_FORM_ref_udata (E)
22169
22170          Besides being broken debug info, it can put GDB into an
22171          infinite loop.  Consider:
22172
22173          When we're building the full name for Class<E>, we'll start
22174          at Class, and go look over its template type parameters,
22175          finding E.  We'll then try to build the full name of E, and
22176          reach here.  We're now trying to build the full name of E,
22177          and look over the parent DIE for containing scope.  In the
22178          broken case, if we followed the parent DIE of E, we'd again
22179          find Class, and once again go look at its template type
22180          arguments, etc., etc.  Simply don't consider such parent die
22181          as source-level parent of this die (it can't be, the language
22182          doesn't allow it), and break the loop here.  */
22183       name = dwarf2_name (die, cu);
22184       parent_name = dwarf2_name (parent, cu);
22185       complaint (_("template param type '%s' defined within parent '%s'"),
22186                  name ? name : "<unknown>",
22187                  parent_name ? parent_name : "<unknown>");
22188       return "";
22189     }
22190   else
22191     switch (parent->tag)
22192       {
22193       case DW_TAG_namespace:
22194         parent_type = read_type_die (parent, cu);
22195         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22196            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22197            Work around this problem here.  */
22198         if (cu->language == language_cplus
22199             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22200           return "";
22201         /* We give a name to even anonymous namespaces.  */
22202         return TYPE_NAME (parent_type);
22203       case DW_TAG_class_type:
22204       case DW_TAG_interface_type:
22205       case DW_TAG_structure_type:
22206       case DW_TAG_union_type:
22207       case DW_TAG_module:
22208         parent_type = read_type_die (parent, cu);
22209         if (TYPE_NAME (parent_type) != NULL)
22210           return TYPE_NAME (parent_type);
22211         else
22212           /* An anonymous structure is only allowed non-static data
22213              members; no typedefs, no member functions, et cetera.
22214              So it does not need a prefix.  */
22215           return "";
22216       case DW_TAG_compile_unit:
22217       case DW_TAG_partial_unit:
22218         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22219         if (cu->language == language_cplus
22220             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22221             && die->child != NULL
22222             && (die->tag == DW_TAG_class_type
22223                 || die->tag == DW_TAG_structure_type
22224                 || die->tag == DW_TAG_union_type))
22225           {
22226             char *name = guess_full_die_structure_name (die, cu);
22227             if (name != NULL)
22228               return name;
22229           }
22230         return "";
22231       case DW_TAG_enumeration_type:
22232         parent_type = read_type_die (parent, cu);
22233         if (TYPE_DECLARED_CLASS (parent_type))
22234           {
22235             if (TYPE_NAME (parent_type) != NULL)
22236               return TYPE_NAME (parent_type);
22237             return "";
22238           }
22239         /* Fall through.  */
22240       default:
22241         return determine_prefix (parent, cu);
22242       }
22243 }
22244
22245 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22246    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22247    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22248    an obconcat, otherwise allocate storage for the result.  The CU argument is
22249    used to determine the language and hence, the appropriate separator.  */
22250
22251 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22252
22253 static char *
22254 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22255                  int physname, struct dwarf2_cu *cu)
22256 {
22257   const char *lead = "";
22258   const char *sep;
22259
22260   if (suffix == NULL || suffix[0] == '\0'
22261       || prefix == NULL || prefix[0] == '\0')
22262     sep = "";
22263   else if (cu->language == language_d)
22264     {
22265       /* For D, the 'main' function could be defined in any module, but it
22266          should never be prefixed.  */
22267       if (strcmp (suffix, "D main") == 0)
22268         {
22269           prefix = "";
22270           sep = "";
22271         }
22272       else
22273         sep = ".";
22274     }
22275   else if (cu->language == language_fortran && physname)
22276     {
22277       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22278          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22279
22280       lead = "__";
22281       sep = "_MOD_";
22282     }
22283   else
22284     sep = "::";
22285
22286   if (prefix == NULL)
22287     prefix = "";
22288   if (suffix == NULL)
22289     suffix = "";
22290
22291   if (obs == NULL)
22292     {
22293       char *retval
22294         = ((char *)
22295            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22296
22297       strcpy (retval, lead);
22298       strcat (retval, prefix);
22299       strcat (retval, sep);
22300       strcat (retval, suffix);
22301       return retval;
22302     }
22303   else
22304     {
22305       /* We have an obstack.  */
22306       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22307     }
22308 }
22309
22310 /* Return sibling of die, NULL if no sibling.  */
22311
22312 static struct die_info *
22313 sibling_die (struct die_info *die)
22314 {
22315   return die->sibling;
22316 }
22317
22318 /* Get name of a die, return NULL if not found.  */
22319
22320 static const char *
22321 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22322                           struct obstack *obstack)
22323 {
22324   if (name && cu->language == language_cplus)
22325     {
22326       std::string canon_name = cp_canonicalize_string (name);
22327
22328       if (!canon_name.empty ())
22329         {
22330           if (canon_name != name)
22331             name = (const char *) obstack_copy0 (obstack,
22332                                                  canon_name.c_str (),
22333                                                  canon_name.length ());
22334         }
22335     }
22336
22337   return name;
22338 }
22339
22340 /* Get name of a die, return NULL if not found.
22341    Anonymous namespaces are converted to their magic string.  */
22342
22343 static const char *
22344 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22345 {
22346   struct attribute *attr;
22347   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22348
22349   attr = dwarf2_attr (die, DW_AT_name, cu);
22350   if ((!attr || !DW_STRING (attr))
22351       && die->tag != DW_TAG_namespace
22352       && die->tag != DW_TAG_class_type
22353       && die->tag != DW_TAG_interface_type
22354       && die->tag != DW_TAG_structure_type
22355       && die->tag != DW_TAG_union_type)
22356     return NULL;
22357
22358   switch (die->tag)
22359     {
22360     case DW_TAG_compile_unit:
22361     case DW_TAG_partial_unit:
22362       /* Compilation units have a DW_AT_name that is a filename, not
22363          a source language identifier.  */
22364     case DW_TAG_enumeration_type:
22365     case DW_TAG_enumerator:
22366       /* These tags always have simple identifiers already; no need
22367          to canonicalize them.  */
22368       return DW_STRING (attr);
22369
22370     case DW_TAG_namespace:
22371       if (attr != NULL && DW_STRING (attr) != NULL)
22372         return DW_STRING (attr);
22373       return CP_ANONYMOUS_NAMESPACE_STR;
22374
22375     case DW_TAG_class_type:
22376     case DW_TAG_interface_type:
22377     case DW_TAG_structure_type:
22378     case DW_TAG_union_type:
22379       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22380          structures or unions.  These were of the form "._%d" in GCC 4.1,
22381          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22382          and GCC 4.4.  We work around this problem by ignoring these.  */
22383       if (attr && DW_STRING (attr)
22384           && (startswith (DW_STRING (attr), "._")
22385               || startswith (DW_STRING (attr), "<anonymous")))
22386         return NULL;
22387
22388       /* GCC might emit a nameless typedef that has a linkage name.  See
22389          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22390       if (!attr || DW_STRING (attr) == NULL)
22391         {
22392           char *demangled = NULL;
22393
22394           attr = dw2_linkage_name_attr (die, cu);
22395           if (attr == NULL || DW_STRING (attr) == NULL)
22396             return NULL;
22397
22398           /* Avoid demangling DW_STRING (attr) the second time on a second
22399              call for the same DIE.  */
22400           if (!DW_STRING_IS_CANONICAL (attr))
22401             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22402
22403           if (demangled)
22404             {
22405               const char *base;
22406
22407               /* FIXME: we already did this for the partial symbol... */
22408               DW_STRING (attr)
22409                 = ((const char *)
22410                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22411                                   demangled, strlen (demangled)));
22412               DW_STRING_IS_CANONICAL (attr) = 1;
22413               xfree (demangled);
22414
22415               /* Strip any leading namespaces/classes, keep only the base name.
22416                  DW_AT_name for named DIEs does not contain the prefixes.  */
22417               base = strrchr (DW_STRING (attr), ':');
22418               if (base && base > DW_STRING (attr) && base[-1] == ':')
22419                 return &base[1];
22420               else
22421                 return DW_STRING (attr);
22422             }
22423         }
22424       break;
22425
22426     default:
22427       break;
22428     }
22429
22430   if (!DW_STRING_IS_CANONICAL (attr))
22431     {
22432       DW_STRING (attr)
22433         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22434                                     &objfile->per_bfd->storage_obstack);
22435       DW_STRING_IS_CANONICAL (attr) = 1;
22436     }
22437   return DW_STRING (attr);
22438 }
22439
22440 /* Return the die that this die in an extension of, or NULL if there
22441    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22442    containing the return value on output.  */
22443
22444 static struct die_info *
22445 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22446 {
22447   struct attribute *attr;
22448
22449   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22450   if (attr == NULL)
22451     return NULL;
22452
22453   return follow_die_ref (die, attr, ext_cu);
22454 }
22455
22456 /* Convert a DIE tag into its string name.  */
22457
22458 static const char *
22459 dwarf_tag_name (unsigned tag)
22460 {
22461   const char *name = get_DW_TAG_name (tag);
22462
22463   if (name == NULL)
22464     return "DW_TAG_<unknown>";
22465
22466   return name;
22467 }
22468
22469 /* Convert a DWARF attribute code into its string name.  */
22470
22471 static const char *
22472 dwarf_attr_name (unsigned attr)
22473 {
22474   const char *name;
22475
22476 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22477   if (attr == DW_AT_MIPS_fde)
22478     return "DW_AT_MIPS_fde";
22479 #else
22480   if (attr == DW_AT_HP_block_index)
22481     return "DW_AT_HP_block_index";
22482 #endif
22483
22484   name = get_DW_AT_name (attr);
22485
22486   if (name == NULL)
22487     return "DW_AT_<unknown>";
22488
22489   return name;
22490 }
22491
22492 /* Convert a DWARF value form code into its string name.  */
22493
22494 static const char *
22495 dwarf_form_name (unsigned form)
22496 {
22497   const char *name = get_DW_FORM_name (form);
22498
22499   if (name == NULL)
22500     return "DW_FORM_<unknown>";
22501
22502   return name;
22503 }
22504
22505 static const char *
22506 dwarf_bool_name (unsigned mybool)
22507 {
22508   if (mybool)
22509     return "TRUE";
22510   else
22511     return "FALSE";
22512 }
22513
22514 /* Convert a DWARF type code into its string name.  */
22515
22516 static const char *
22517 dwarf_type_encoding_name (unsigned enc)
22518 {
22519   const char *name = get_DW_ATE_name (enc);
22520
22521   if (name == NULL)
22522     return "DW_ATE_<unknown>";
22523
22524   return name;
22525 }
22526
22527 static void
22528 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22529 {
22530   unsigned int i;
22531
22532   print_spaces (indent, f);
22533   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22534                       dwarf_tag_name (die->tag), die->abbrev,
22535                       sect_offset_str (die->sect_off));
22536
22537   if (die->parent != NULL)
22538     {
22539       print_spaces (indent, f);
22540       fprintf_unfiltered (f, "  parent at offset: %s\n",
22541                           sect_offset_str (die->parent->sect_off));
22542     }
22543
22544   print_spaces (indent, f);
22545   fprintf_unfiltered (f, "  has children: %s\n",
22546            dwarf_bool_name (die->child != NULL));
22547
22548   print_spaces (indent, f);
22549   fprintf_unfiltered (f, "  attributes:\n");
22550
22551   for (i = 0; i < die->num_attrs; ++i)
22552     {
22553       print_spaces (indent, f);
22554       fprintf_unfiltered (f, "    %s (%s) ",
22555                dwarf_attr_name (die->attrs[i].name),
22556                dwarf_form_name (die->attrs[i].form));
22557
22558       switch (die->attrs[i].form)
22559         {
22560         case DW_FORM_addr:
22561         case DW_FORM_GNU_addr_index:
22562           fprintf_unfiltered (f, "address: ");
22563           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22564           break;
22565         case DW_FORM_block2:
22566         case DW_FORM_block4:
22567         case DW_FORM_block:
22568         case DW_FORM_block1:
22569           fprintf_unfiltered (f, "block: size %s",
22570                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22571           break;
22572         case DW_FORM_exprloc:
22573           fprintf_unfiltered (f, "expression: size %s",
22574                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22575           break;
22576         case DW_FORM_data16:
22577           fprintf_unfiltered (f, "constant of 16 bytes");
22578           break;
22579         case DW_FORM_ref_addr:
22580           fprintf_unfiltered (f, "ref address: ");
22581           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22582           break;
22583         case DW_FORM_GNU_ref_alt:
22584           fprintf_unfiltered (f, "alt ref address: ");
22585           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22586           break;
22587         case DW_FORM_ref1:
22588         case DW_FORM_ref2:
22589         case DW_FORM_ref4:
22590         case DW_FORM_ref8:
22591         case DW_FORM_ref_udata:
22592           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22593                               (long) (DW_UNSND (&die->attrs[i])));
22594           break;
22595         case DW_FORM_data1:
22596         case DW_FORM_data2:
22597         case DW_FORM_data4:
22598         case DW_FORM_data8:
22599         case DW_FORM_udata:
22600         case DW_FORM_sdata:
22601           fprintf_unfiltered (f, "constant: %s",
22602                               pulongest (DW_UNSND (&die->attrs[i])));
22603           break;
22604         case DW_FORM_sec_offset:
22605           fprintf_unfiltered (f, "section offset: %s",
22606                               pulongest (DW_UNSND (&die->attrs[i])));
22607           break;
22608         case DW_FORM_ref_sig8:
22609           fprintf_unfiltered (f, "signature: %s",
22610                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22611           break;
22612         case DW_FORM_string:
22613         case DW_FORM_strp:
22614         case DW_FORM_line_strp:
22615         case DW_FORM_GNU_str_index:
22616         case DW_FORM_GNU_strp_alt:
22617           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22618                    DW_STRING (&die->attrs[i])
22619                    ? DW_STRING (&die->attrs[i]) : "",
22620                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22621           break;
22622         case DW_FORM_flag:
22623           if (DW_UNSND (&die->attrs[i]))
22624             fprintf_unfiltered (f, "flag: TRUE");
22625           else
22626             fprintf_unfiltered (f, "flag: FALSE");
22627           break;
22628         case DW_FORM_flag_present:
22629           fprintf_unfiltered (f, "flag: TRUE");
22630           break;
22631         case DW_FORM_indirect:
22632           /* The reader will have reduced the indirect form to
22633              the "base form" so this form should not occur.  */
22634           fprintf_unfiltered (f, 
22635                               "unexpected attribute form: DW_FORM_indirect");
22636           break;
22637         case DW_FORM_implicit_const:
22638           fprintf_unfiltered (f, "constant: %s",
22639                               plongest (DW_SND (&die->attrs[i])));
22640           break;
22641         default:
22642           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22643                    die->attrs[i].form);
22644           break;
22645         }
22646       fprintf_unfiltered (f, "\n");
22647     }
22648 }
22649
22650 static void
22651 dump_die_for_error (struct die_info *die)
22652 {
22653   dump_die_shallow (gdb_stderr, 0, die);
22654 }
22655
22656 static void
22657 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22658 {
22659   int indent = level * 4;
22660
22661   gdb_assert (die != NULL);
22662
22663   if (level >= max_level)
22664     return;
22665
22666   dump_die_shallow (f, indent, die);
22667
22668   if (die->child != NULL)
22669     {
22670       print_spaces (indent, f);
22671       fprintf_unfiltered (f, "  Children:");
22672       if (level + 1 < max_level)
22673         {
22674           fprintf_unfiltered (f, "\n");
22675           dump_die_1 (f, level + 1, max_level, die->child);
22676         }
22677       else
22678         {
22679           fprintf_unfiltered (f,
22680                               " [not printed, max nesting level reached]\n");
22681         }
22682     }
22683
22684   if (die->sibling != NULL && level > 0)
22685     {
22686       dump_die_1 (f, level, max_level, die->sibling);
22687     }
22688 }
22689
22690 /* This is called from the pdie macro in gdbinit.in.
22691    It's not static so gcc will keep a copy callable from gdb.  */
22692
22693 void
22694 dump_die (struct die_info *die, int max_level)
22695 {
22696   dump_die_1 (gdb_stdlog, 0, max_level, die);
22697 }
22698
22699 static void
22700 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22701 {
22702   void **slot;
22703
22704   slot = htab_find_slot_with_hash (cu->die_hash, die,
22705                                    to_underlying (die->sect_off),
22706                                    INSERT);
22707
22708   *slot = die;
22709 }
22710
22711 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22712    required kind.  */
22713
22714 static sect_offset
22715 dwarf2_get_ref_die_offset (const struct attribute *attr)
22716 {
22717   if (attr_form_is_ref (attr))
22718     return (sect_offset) DW_UNSND (attr);
22719
22720   complaint (_("unsupported die ref attribute form: '%s'"),
22721              dwarf_form_name (attr->form));
22722   return {};
22723 }
22724
22725 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22726  * the value held by the attribute is not constant.  */
22727
22728 static LONGEST
22729 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22730 {
22731   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22732     return DW_SND (attr);
22733   else if (attr->form == DW_FORM_udata
22734            || attr->form == DW_FORM_data1
22735            || attr->form == DW_FORM_data2
22736            || attr->form == DW_FORM_data4
22737            || attr->form == DW_FORM_data8)
22738     return DW_UNSND (attr);
22739   else
22740     {
22741       /* For DW_FORM_data16 see attr_form_is_constant.  */
22742       complaint (_("Attribute value is not a constant (%s)"),
22743                  dwarf_form_name (attr->form));
22744       return default_value;
22745     }
22746 }
22747
22748 /* Follow reference or signature attribute ATTR of SRC_DIE.
22749    On entry *REF_CU is the CU of SRC_DIE.
22750    On exit *REF_CU is the CU of the result.  */
22751
22752 static struct die_info *
22753 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22754                        struct dwarf2_cu **ref_cu)
22755 {
22756   struct die_info *die;
22757
22758   if (attr_form_is_ref (attr))
22759     die = follow_die_ref (src_die, attr, ref_cu);
22760   else if (attr->form == DW_FORM_ref_sig8)
22761     die = follow_die_sig (src_die, attr, ref_cu);
22762   else
22763     {
22764       dump_die_for_error (src_die);
22765       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22766              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22767     }
22768
22769   return die;
22770 }
22771
22772 /* Follow reference OFFSET.
22773    On entry *REF_CU is the CU of the source die referencing OFFSET.
22774    On exit *REF_CU is the CU of the result.
22775    Returns NULL if OFFSET is invalid.  */
22776
22777 static struct die_info *
22778 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22779                    struct dwarf2_cu **ref_cu)
22780 {
22781   struct die_info temp_die;
22782   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22783   struct dwarf2_per_objfile *dwarf2_per_objfile
22784     = cu->per_cu->dwarf2_per_objfile;
22785
22786   gdb_assert (cu->per_cu != NULL);
22787
22788   target_cu = cu;
22789
22790   if (cu->per_cu->is_debug_types)
22791     {
22792       /* .debug_types CUs cannot reference anything outside their CU.
22793          If they need to, they have to reference a signatured type via
22794          DW_FORM_ref_sig8.  */
22795       if (!offset_in_cu_p (&cu->header, sect_off))
22796         return NULL;
22797     }
22798   else if (offset_in_dwz != cu->per_cu->is_dwz
22799            || !offset_in_cu_p (&cu->header, sect_off))
22800     {
22801       struct dwarf2_per_cu_data *per_cu;
22802
22803       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22804                                                  dwarf2_per_objfile);
22805
22806       /* If necessary, add it to the queue and load its DIEs.  */
22807       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22808         load_full_comp_unit (per_cu, false, cu->language);
22809
22810       target_cu = per_cu->cu;
22811     }
22812   else if (cu->dies == NULL)
22813     {
22814       /* We're loading full DIEs during partial symbol reading.  */
22815       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22816       load_full_comp_unit (cu->per_cu, false, language_minimal);
22817     }
22818
22819   *ref_cu = target_cu;
22820   temp_die.sect_off = sect_off;
22821   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22822                                                   &temp_die,
22823                                                   to_underlying (sect_off));
22824 }
22825
22826 /* Follow reference attribute ATTR of SRC_DIE.
22827    On entry *REF_CU is the CU of SRC_DIE.
22828    On exit *REF_CU is the CU of the result.  */
22829
22830 static struct die_info *
22831 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22832                 struct dwarf2_cu **ref_cu)
22833 {
22834   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22835   struct dwarf2_cu *cu = *ref_cu;
22836   struct die_info *die;
22837
22838   die = follow_die_offset (sect_off,
22839                            (attr->form == DW_FORM_GNU_ref_alt
22840                             || cu->per_cu->is_dwz),
22841                            ref_cu);
22842   if (!die)
22843     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22844            "at %s [in module %s]"),
22845            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22846            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22847
22848   return die;
22849 }
22850
22851 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22852    Returned value is intended for DW_OP_call*.  Returned
22853    dwarf2_locexpr_baton->data has lifetime of
22854    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22855
22856 struct dwarf2_locexpr_baton
22857 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22858                                struct dwarf2_per_cu_data *per_cu,
22859                                CORE_ADDR (*get_frame_pc) (void *baton),
22860                                void *baton)
22861 {
22862   struct dwarf2_cu *cu;
22863   struct die_info *die;
22864   struct attribute *attr;
22865   struct dwarf2_locexpr_baton retval;
22866   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22867   struct objfile *objfile = dwarf2_per_objfile->objfile;
22868
22869   if (per_cu->cu == NULL)
22870     load_cu (per_cu, false);
22871   cu = per_cu->cu;
22872   if (cu == NULL)
22873     {
22874       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22875          Instead just throw an error, not much else we can do.  */
22876       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22877              sect_offset_str (sect_off), objfile_name (objfile));
22878     }
22879
22880   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22881   if (!die)
22882     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22883            sect_offset_str (sect_off), objfile_name (objfile));
22884
22885   attr = dwarf2_attr (die, DW_AT_location, cu);
22886   if (!attr)
22887     {
22888       /* DWARF: "If there is no such attribute, then there is no effect.".
22889          DATA is ignored if SIZE is 0.  */
22890
22891       retval.data = NULL;
22892       retval.size = 0;
22893     }
22894   else if (attr_form_is_section_offset (attr))
22895     {
22896       struct dwarf2_loclist_baton loclist_baton;
22897       CORE_ADDR pc = (*get_frame_pc) (baton);
22898       size_t size;
22899
22900       fill_in_loclist_baton (cu, &loclist_baton, attr);
22901
22902       retval.data = dwarf2_find_location_expression (&loclist_baton,
22903                                                      &size, pc);
22904       retval.size = size;
22905     }
22906   else
22907     {
22908       if (!attr_form_is_block (attr))
22909         error (_("Dwarf Error: DIE at %s referenced in module %s "
22910                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22911                sect_offset_str (sect_off), objfile_name (objfile));
22912
22913       retval.data = DW_BLOCK (attr)->data;
22914       retval.size = DW_BLOCK (attr)->size;
22915     }
22916   retval.per_cu = cu->per_cu;
22917
22918   age_cached_comp_units (dwarf2_per_objfile);
22919
22920   return retval;
22921 }
22922
22923 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
22924    offset.  */
22925
22926 struct dwarf2_locexpr_baton
22927 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
22928                              struct dwarf2_per_cu_data *per_cu,
22929                              CORE_ADDR (*get_frame_pc) (void *baton),
22930                              void *baton)
22931 {
22932   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
22933
22934   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
22935 }
22936
22937 /* Write a constant of a given type as target-ordered bytes into
22938    OBSTACK.  */
22939
22940 static const gdb_byte *
22941 write_constant_as_bytes (struct obstack *obstack,
22942                          enum bfd_endian byte_order,
22943                          struct type *type,
22944                          ULONGEST value,
22945                          LONGEST *len)
22946 {
22947   gdb_byte *result;
22948
22949   *len = TYPE_LENGTH (type);
22950   result = (gdb_byte *) obstack_alloc (obstack, *len);
22951   store_unsigned_integer (result, *len, byte_order, value);
22952
22953   return result;
22954 }
22955
22956 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
22957    pointer to the constant bytes and set LEN to the length of the
22958    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
22959    does not have a DW_AT_const_value, return NULL.  */
22960
22961 const gdb_byte *
22962 dwarf2_fetch_constant_bytes (sect_offset sect_off,
22963                              struct dwarf2_per_cu_data *per_cu,
22964                              struct obstack *obstack,
22965                              LONGEST *len)
22966 {
22967   struct dwarf2_cu *cu;
22968   struct die_info *die;
22969   struct attribute *attr;
22970   const gdb_byte *result = NULL;
22971   struct type *type;
22972   LONGEST value;
22973   enum bfd_endian byte_order;
22974   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
22975
22976   if (per_cu->cu == NULL)
22977     load_cu (per_cu, false);
22978   cu = per_cu->cu;
22979   if (cu == NULL)
22980     {
22981       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22982          Instead just throw an error, not much else we can do.  */
22983       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22984              sect_offset_str (sect_off), objfile_name (objfile));
22985     }
22986
22987   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22988   if (!die)
22989     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22990            sect_offset_str (sect_off), objfile_name (objfile));
22991
22992   attr = dwarf2_attr (die, DW_AT_const_value, cu);
22993   if (attr == NULL)
22994     return NULL;
22995
22996   byte_order = (bfd_big_endian (objfile->obfd)
22997                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
22998
22999   switch (attr->form)
23000     {
23001     case DW_FORM_addr:
23002     case DW_FORM_GNU_addr_index:
23003       {
23004         gdb_byte *tem;
23005
23006         *len = cu->header.addr_size;
23007         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23008         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23009         result = tem;
23010       }
23011       break;
23012     case DW_FORM_string:
23013     case DW_FORM_strp:
23014     case DW_FORM_GNU_str_index:
23015     case DW_FORM_GNU_strp_alt:
23016       /* DW_STRING is already allocated on the objfile obstack, point
23017          directly to it.  */
23018       result = (const gdb_byte *) DW_STRING (attr);
23019       *len = strlen (DW_STRING (attr));
23020       break;
23021     case DW_FORM_block1:
23022     case DW_FORM_block2:
23023     case DW_FORM_block4:
23024     case DW_FORM_block:
23025     case DW_FORM_exprloc:
23026     case DW_FORM_data16:
23027       result = DW_BLOCK (attr)->data;
23028       *len = DW_BLOCK (attr)->size;
23029       break;
23030
23031       /* The DW_AT_const_value attributes are supposed to carry the
23032          symbol's value "represented as it would be on the target
23033          architecture."  By the time we get here, it's already been
23034          converted to host endianness, so we just need to sign- or
23035          zero-extend it as appropriate.  */
23036     case DW_FORM_data1:
23037       type = die_type (die, cu);
23038       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23039       if (result == NULL)
23040         result = write_constant_as_bytes (obstack, byte_order,
23041                                           type, value, len);
23042       break;
23043     case DW_FORM_data2:
23044       type = die_type (die, cu);
23045       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23046       if (result == NULL)
23047         result = write_constant_as_bytes (obstack, byte_order,
23048                                           type, value, len);
23049       break;
23050     case DW_FORM_data4:
23051       type = die_type (die, cu);
23052       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23053       if (result == NULL)
23054         result = write_constant_as_bytes (obstack, byte_order,
23055                                           type, value, len);
23056       break;
23057     case DW_FORM_data8:
23058       type = die_type (die, cu);
23059       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23060       if (result == NULL)
23061         result = write_constant_as_bytes (obstack, byte_order,
23062                                           type, value, len);
23063       break;
23064
23065     case DW_FORM_sdata:
23066     case DW_FORM_implicit_const:
23067       type = die_type (die, cu);
23068       result = write_constant_as_bytes (obstack, byte_order,
23069                                         type, DW_SND (attr), len);
23070       break;
23071
23072     case DW_FORM_udata:
23073       type = die_type (die, cu);
23074       result = write_constant_as_bytes (obstack, byte_order,
23075                                         type, DW_UNSND (attr), len);
23076       break;
23077
23078     default:
23079       complaint (_("unsupported const value attribute form: '%s'"),
23080                  dwarf_form_name (attr->form));
23081       break;
23082     }
23083
23084   return result;
23085 }
23086
23087 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23088    valid type for this die is found.  */
23089
23090 struct type *
23091 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23092                                 struct dwarf2_per_cu_data *per_cu)
23093 {
23094   struct dwarf2_cu *cu;
23095   struct die_info *die;
23096
23097   if (per_cu->cu == NULL)
23098     load_cu (per_cu, false);
23099   cu = per_cu->cu;
23100   if (!cu)
23101     return NULL;
23102
23103   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23104   if (!die)
23105     return NULL;
23106
23107   return die_type (die, cu);
23108 }
23109
23110 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23111    PER_CU.  */
23112
23113 struct type *
23114 dwarf2_get_die_type (cu_offset die_offset,
23115                      struct dwarf2_per_cu_data *per_cu)
23116 {
23117   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23118   return get_die_type_at_offset (die_offset_sect, per_cu);
23119 }
23120
23121 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23122    On entry *REF_CU is the CU of SRC_DIE.
23123    On exit *REF_CU is the CU of the result.
23124    Returns NULL if the referenced DIE isn't found.  */
23125
23126 static struct die_info *
23127 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23128                   struct dwarf2_cu **ref_cu)
23129 {
23130   struct die_info temp_die;
23131   struct dwarf2_cu *sig_cu;
23132   struct die_info *die;
23133
23134   /* While it might be nice to assert sig_type->type == NULL here,
23135      we can get here for DW_AT_imported_declaration where we need
23136      the DIE not the type.  */
23137
23138   /* If necessary, add it to the queue and load its DIEs.  */
23139
23140   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23141     read_signatured_type (sig_type);
23142
23143   sig_cu = sig_type->per_cu.cu;
23144   gdb_assert (sig_cu != NULL);
23145   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23146   temp_die.sect_off = sig_type->type_offset_in_section;
23147   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23148                                                  to_underlying (temp_die.sect_off));
23149   if (die)
23150     {
23151       struct dwarf2_per_objfile *dwarf2_per_objfile
23152         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23153
23154       /* For .gdb_index version 7 keep track of included TUs.
23155          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23156       if (dwarf2_per_objfile->index_table != NULL
23157           && dwarf2_per_objfile->index_table->version <= 7)
23158         {
23159           VEC_safe_push (dwarf2_per_cu_ptr,
23160                          (*ref_cu)->per_cu->imported_symtabs,
23161                          sig_cu->per_cu);
23162         }
23163
23164       *ref_cu = sig_cu;
23165       return die;
23166     }
23167
23168   return NULL;
23169 }
23170
23171 /* Follow signatured type referenced by ATTR in SRC_DIE.
23172    On entry *REF_CU is the CU of SRC_DIE.
23173    On exit *REF_CU is the CU of the result.
23174    The result is the DIE of the type.
23175    If the referenced type cannot be found an error is thrown.  */
23176
23177 static struct die_info *
23178 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23179                 struct dwarf2_cu **ref_cu)
23180 {
23181   ULONGEST signature = DW_SIGNATURE (attr);
23182   struct signatured_type *sig_type;
23183   struct die_info *die;
23184
23185   gdb_assert (attr->form == DW_FORM_ref_sig8);
23186
23187   sig_type = lookup_signatured_type (*ref_cu, signature);
23188   /* sig_type will be NULL if the signatured type is missing from
23189      the debug info.  */
23190   if (sig_type == NULL)
23191     {
23192       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23193                " from DIE at %s [in module %s]"),
23194              hex_string (signature), sect_offset_str (src_die->sect_off),
23195              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23196     }
23197
23198   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23199   if (die == NULL)
23200     {
23201       dump_die_for_error (src_die);
23202       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23203                " from DIE at %s [in module %s]"),
23204              hex_string (signature), sect_offset_str (src_die->sect_off),
23205              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23206     }
23207
23208   return die;
23209 }
23210
23211 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23212    reading in and processing the type unit if necessary.  */
23213
23214 static struct type *
23215 get_signatured_type (struct die_info *die, ULONGEST signature,
23216                      struct dwarf2_cu *cu)
23217 {
23218   struct dwarf2_per_objfile *dwarf2_per_objfile
23219     = cu->per_cu->dwarf2_per_objfile;
23220   struct signatured_type *sig_type;
23221   struct dwarf2_cu *type_cu;
23222   struct die_info *type_die;
23223   struct type *type;
23224
23225   sig_type = lookup_signatured_type (cu, signature);
23226   /* sig_type will be NULL if the signatured type is missing from
23227      the debug info.  */
23228   if (sig_type == NULL)
23229     {
23230       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23231                    " from DIE at %s [in module %s]"),
23232                  hex_string (signature), sect_offset_str (die->sect_off),
23233                  objfile_name (dwarf2_per_objfile->objfile));
23234       return build_error_marker_type (cu, die);
23235     }
23236
23237   /* If we already know the type we're done.  */
23238   if (sig_type->type != NULL)
23239     return sig_type->type;
23240
23241   type_cu = cu;
23242   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23243   if (type_die != NULL)
23244     {
23245       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23246          is created.  This is important, for example, because for c++ classes
23247          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23248       type = read_type_die (type_die, type_cu);
23249       if (type == NULL)
23250         {
23251           complaint (_("Dwarf Error: Cannot build signatured type %s"
23252                        " referenced from DIE at %s [in module %s]"),
23253                      hex_string (signature), sect_offset_str (die->sect_off),
23254                      objfile_name (dwarf2_per_objfile->objfile));
23255           type = build_error_marker_type (cu, die);
23256         }
23257     }
23258   else
23259     {
23260       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23261                    " from DIE at %s [in module %s]"),
23262                  hex_string (signature), sect_offset_str (die->sect_off),
23263                  objfile_name (dwarf2_per_objfile->objfile));
23264       type = build_error_marker_type (cu, die);
23265     }
23266   sig_type->type = type;
23267
23268   return type;
23269 }
23270
23271 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23272    reading in and processing the type unit if necessary.  */
23273
23274 static struct type *
23275 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23276                           struct dwarf2_cu *cu) /* ARI: editCase function */
23277 {
23278   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23279   if (attr_form_is_ref (attr))
23280     {
23281       struct dwarf2_cu *type_cu = cu;
23282       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23283
23284       return read_type_die (type_die, type_cu);
23285     }
23286   else if (attr->form == DW_FORM_ref_sig8)
23287     {
23288       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23289     }
23290   else
23291     {
23292       struct dwarf2_per_objfile *dwarf2_per_objfile
23293         = cu->per_cu->dwarf2_per_objfile;
23294
23295       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23296                    " at %s [in module %s]"),
23297                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23298                  objfile_name (dwarf2_per_objfile->objfile));
23299       return build_error_marker_type (cu, die);
23300     }
23301 }
23302
23303 /* Load the DIEs associated with type unit PER_CU into memory.  */
23304
23305 static void
23306 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23307 {
23308   struct signatured_type *sig_type;
23309
23310   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23311   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23312
23313   /* We have the per_cu, but we need the signatured_type.
23314      Fortunately this is an easy translation.  */
23315   gdb_assert (per_cu->is_debug_types);
23316   sig_type = (struct signatured_type *) per_cu;
23317
23318   gdb_assert (per_cu->cu == NULL);
23319
23320   read_signatured_type (sig_type);
23321
23322   gdb_assert (per_cu->cu != NULL);
23323 }
23324
23325 /* die_reader_func for read_signatured_type.
23326    This is identical to load_full_comp_unit_reader,
23327    but is kept separate for now.  */
23328
23329 static void
23330 read_signatured_type_reader (const struct die_reader_specs *reader,
23331                              const gdb_byte *info_ptr,
23332                              struct die_info *comp_unit_die,
23333                              int has_children,
23334                              void *data)
23335 {
23336   struct dwarf2_cu *cu = reader->cu;
23337
23338   gdb_assert (cu->die_hash == NULL);
23339   cu->die_hash =
23340     htab_create_alloc_ex (cu->header.length / 12,
23341                           die_hash,
23342                           die_eq,
23343                           NULL,
23344                           &cu->comp_unit_obstack,
23345                           hashtab_obstack_allocate,
23346                           dummy_obstack_deallocate);
23347
23348   if (has_children)
23349     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23350                                                   &info_ptr, comp_unit_die);
23351   cu->dies = comp_unit_die;
23352   /* comp_unit_die is not stored in die_hash, no need.  */
23353
23354   /* We try not to read any attributes in this function, because not
23355      all CUs needed for references have been loaded yet, and symbol
23356      table processing isn't initialized.  But we have to set the CU language,
23357      or we won't be able to build types correctly.
23358      Similarly, if we do not read the producer, we can not apply
23359      producer-specific interpretation.  */
23360   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23361 }
23362
23363 /* Read in a signatured type and build its CU and DIEs.
23364    If the type is a stub for the real type in a DWO file,
23365    read in the real type from the DWO file as well.  */
23366
23367 static void
23368 read_signatured_type (struct signatured_type *sig_type)
23369 {
23370   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23371
23372   gdb_assert (per_cu->is_debug_types);
23373   gdb_assert (per_cu->cu == NULL);
23374
23375   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23376                            read_signatured_type_reader, NULL);
23377   sig_type->per_cu.tu_read = 1;
23378 }
23379
23380 /* Decode simple location descriptions.
23381    Given a pointer to a dwarf block that defines a location, compute
23382    the location and return the value.
23383
23384    NOTE drow/2003-11-18: This function is called in two situations
23385    now: for the address of static or global variables (partial symbols
23386    only) and for offsets into structures which are expected to be
23387    (more or less) constant.  The partial symbol case should go away,
23388    and only the constant case should remain.  That will let this
23389    function complain more accurately.  A few special modes are allowed
23390    without complaint for global variables (for instance, global
23391    register values and thread-local values).
23392
23393    A location description containing no operations indicates that the
23394    object is optimized out.  The return value is 0 for that case.
23395    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23396    callers will only want a very basic result and this can become a
23397    complaint.
23398
23399    Note that stack[0] is unused except as a default error return.  */
23400
23401 static CORE_ADDR
23402 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23403 {
23404   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23405   size_t i;
23406   size_t size = blk->size;
23407   const gdb_byte *data = blk->data;
23408   CORE_ADDR stack[64];
23409   int stacki;
23410   unsigned int bytes_read, unsnd;
23411   gdb_byte op;
23412
23413   i = 0;
23414   stacki = 0;
23415   stack[stacki] = 0;
23416   stack[++stacki] = 0;
23417
23418   while (i < size)
23419     {
23420       op = data[i++];
23421       switch (op)
23422         {
23423         case DW_OP_lit0:
23424         case DW_OP_lit1:
23425         case DW_OP_lit2:
23426         case DW_OP_lit3:
23427         case DW_OP_lit4:
23428         case DW_OP_lit5:
23429         case DW_OP_lit6:
23430         case DW_OP_lit7:
23431         case DW_OP_lit8:
23432         case DW_OP_lit9:
23433         case DW_OP_lit10:
23434         case DW_OP_lit11:
23435         case DW_OP_lit12:
23436         case DW_OP_lit13:
23437         case DW_OP_lit14:
23438         case DW_OP_lit15:
23439         case DW_OP_lit16:
23440         case DW_OP_lit17:
23441         case DW_OP_lit18:
23442         case DW_OP_lit19:
23443         case DW_OP_lit20:
23444         case DW_OP_lit21:
23445         case DW_OP_lit22:
23446         case DW_OP_lit23:
23447         case DW_OP_lit24:
23448         case DW_OP_lit25:
23449         case DW_OP_lit26:
23450         case DW_OP_lit27:
23451         case DW_OP_lit28:
23452         case DW_OP_lit29:
23453         case DW_OP_lit30:
23454         case DW_OP_lit31:
23455           stack[++stacki] = op - DW_OP_lit0;
23456           break;
23457
23458         case DW_OP_reg0:
23459         case DW_OP_reg1:
23460         case DW_OP_reg2:
23461         case DW_OP_reg3:
23462         case DW_OP_reg4:
23463         case DW_OP_reg5:
23464         case DW_OP_reg6:
23465         case DW_OP_reg7:
23466         case DW_OP_reg8:
23467         case DW_OP_reg9:
23468         case DW_OP_reg10:
23469         case DW_OP_reg11:
23470         case DW_OP_reg12:
23471         case DW_OP_reg13:
23472         case DW_OP_reg14:
23473         case DW_OP_reg15:
23474         case DW_OP_reg16:
23475         case DW_OP_reg17:
23476         case DW_OP_reg18:
23477         case DW_OP_reg19:
23478         case DW_OP_reg20:
23479         case DW_OP_reg21:
23480         case DW_OP_reg22:
23481         case DW_OP_reg23:
23482         case DW_OP_reg24:
23483         case DW_OP_reg25:
23484         case DW_OP_reg26:
23485         case DW_OP_reg27:
23486         case DW_OP_reg28:
23487         case DW_OP_reg29:
23488         case DW_OP_reg30:
23489         case DW_OP_reg31:
23490           stack[++stacki] = op - DW_OP_reg0;
23491           if (i < size)
23492             dwarf2_complex_location_expr_complaint ();
23493           break;
23494
23495         case DW_OP_regx:
23496           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23497           i += bytes_read;
23498           stack[++stacki] = unsnd;
23499           if (i < size)
23500             dwarf2_complex_location_expr_complaint ();
23501           break;
23502
23503         case DW_OP_addr:
23504           stack[++stacki] = read_address (objfile->obfd, &data[i],
23505                                           cu, &bytes_read);
23506           i += bytes_read;
23507           break;
23508
23509         case DW_OP_const1u:
23510           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23511           i += 1;
23512           break;
23513
23514         case DW_OP_const1s:
23515           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23516           i += 1;
23517           break;
23518
23519         case DW_OP_const2u:
23520           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23521           i += 2;
23522           break;
23523
23524         case DW_OP_const2s:
23525           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23526           i += 2;
23527           break;
23528
23529         case DW_OP_const4u:
23530           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23531           i += 4;
23532           break;
23533
23534         case DW_OP_const4s:
23535           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23536           i += 4;
23537           break;
23538
23539         case DW_OP_const8u:
23540           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23541           i += 8;
23542           break;
23543
23544         case DW_OP_constu:
23545           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23546                                                   &bytes_read);
23547           i += bytes_read;
23548           break;
23549
23550         case DW_OP_consts:
23551           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23552           i += bytes_read;
23553           break;
23554
23555         case DW_OP_dup:
23556           stack[stacki + 1] = stack[stacki];
23557           stacki++;
23558           break;
23559
23560         case DW_OP_plus:
23561           stack[stacki - 1] += stack[stacki];
23562           stacki--;
23563           break;
23564
23565         case DW_OP_plus_uconst:
23566           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23567                                                  &bytes_read);
23568           i += bytes_read;
23569           break;
23570
23571         case DW_OP_minus:
23572           stack[stacki - 1] -= stack[stacki];
23573           stacki--;
23574           break;
23575
23576         case DW_OP_deref:
23577           /* If we're not the last op, then we definitely can't encode
23578              this using GDB's address_class enum.  This is valid for partial
23579              global symbols, although the variable's address will be bogus
23580              in the psymtab.  */
23581           if (i < size)
23582             dwarf2_complex_location_expr_complaint ();
23583           break;
23584
23585         case DW_OP_GNU_push_tls_address:
23586         case DW_OP_form_tls_address:
23587           /* The top of the stack has the offset from the beginning
23588              of the thread control block at which the variable is located.  */
23589           /* Nothing should follow this operator, so the top of stack would
23590              be returned.  */
23591           /* This is valid for partial global symbols, but the variable's
23592              address will be bogus in the psymtab.  Make it always at least
23593              non-zero to not look as a variable garbage collected by linker
23594              which have DW_OP_addr 0.  */
23595           if (i < size)
23596             dwarf2_complex_location_expr_complaint ();
23597           stack[stacki]++;
23598           break;
23599
23600         case DW_OP_GNU_uninit:
23601           break;
23602
23603         case DW_OP_GNU_addr_index:
23604         case DW_OP_GNU_const_index:
23605           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23606                                                          &bytes_read);
23607           i += bytes_read;
23608           break;
23609
23610         default:
23611           {
23612             const char *name = get_DW_OP_name (op);
23613
23614             if (name)
23615               complaint (_("unsupported stack op: '%s'"),
23616                          name);
23617             else
23618               complaint (_("unsupported stack op: '%02x'"),
23619                          op);
23620           }
23621
23622           return (stack[stacki]);
23623         }
23624
23625       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23626          outside of the allocated space.  Also enforce minimum>0.  */
23627       if (stacki >= ARRAY_SIZE (stack) - 1)
23628         {
23629           complaint (_("location description stack overflow"));
23630           return 0;
23631         }
23632
23633       if (stacki <= 0)
23634         {
23635           complaint (_("location description stack underflow"));
23636           return 0;
23637         }
23638     }
23639   return (stack[stacki]);
23640 }
23641
23642 /* memory allocation interface */
23643
23644 static struct dwarf_block *
23645 dwarf_alloc_block (struct dwarf2_cu *cu)
23646 {
23647   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23648 }
23649
23650 static struct die_info *
23651 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23652 {
23653   struct die_info *die;
23654   size_t size = sizeof (struct die_info);
23655
23656   if (num_attrs > 1)
23657     size += (num_attrs - 1) * sizeof (struct attribute);
23658
23659   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23660   memset (die, 0, sizeof (struct die_info));
23661   return (die);
23662 }
23663
23664 \f
23665 /* Macro support.  */
23666
23667 /* Return file name relative to the compilation directory of file number I in
23668    *LH's file name table.  The result is allocated using xmalloc; the caller is
23669    responsible for freeing it.  */
23670
23671 static char *
23672 file_file_name (int file, struct line_header *lh)
23673 {
23674   /* Is the file number a valid index into the line header's file name
23675      table?  Remember that file numbers start with one, not zero.  */
23676   if (1 <= file && file <= lh->file_names.size ())
23677     {
23678       const file_entry &fe = lh->file_names[file - 1];
23679
23680       if (!IS_ABSOLUTE_PATH (fe.name))
23681         {
23682           const char *dir = fe.include_dir (lh);
23683           if (dir != NULL)
23684             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23685         }
23686       return xstrdup (fe.name);
23687     }
23688   else
23689     {
23690       /* The compiler produced a bogus file number.  We can at least
23691          record the macro definitions made in the file, even if we
23692          won't be able to find the file by name.  */
23693       char fake_name[80];
23694
23695       xsnprintf (fake_name, sizeof (fake_name),
23696                  "<bad macro file number %d>", file);
23697
23698       complaint (_("bad file number in macro information (%d)"),
23699                  file);
23700
23701       return xstrdup (fake_name);
23702     }
23703 }
23704
23705 /* Return the full name of file number I in *LH's file name table.
23706    Use COMP_DIR as the name of the current directory of the
23707    compilation.  The result is allocated using xmalloc; the caller is
23708    responsible for freeing it.  */
23709 static char *
23710 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23711 {
23712   /* Is the file number a valid index into the line header's file name
23713      table?  Remember that file numbers start with one, not zero.  */
23714   if (1 <= file && file <= lh->file_names.size ())
23715     {
23716       char *relative = file_file_name (file, lh);
23717
23718       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23719         return relative;
23720       return reconcat (relative, comp_dir, SLASH_STRING,
23721                        relative, (char *) NULL);
23722     }
23723   else
23724     return file_file_name (file, lh);
23725 }
23726
23727
23728 static struct macro_source_file *
23729 macro_start_file (int file, int line,
23730                   struct macro_source_file *current_file,
23731                   struct line_header *lh)
23732 {
23733   /* File name relative to the compilation directory of this source file.  */
23734   char *file_name = file_file_name (file, lh);
23735
23736   if (! current_file)
23737     {
23738       /* Note: We don't create a macro table for this compilation unit
23739          at all until we actually get a filename.  */
23740       struct macro_table *macro_table = get_macro_table ();
23741
23742       /* If we have no current file, then this must be the start_file
23743          directive for the compilation unit's main source file.  */
23744       current_file = macro_set_main (macro_table, file_name);
23745       macro_define_special (macro_table);
23746     }
23747   else
23748     current_file = macro_include (current_file, line, file_name);
23749
23750   xfree (file_name);
23751
23752   return current_file;
23753 }
23754
23755 static const char *
23756 consume_improper_spaces (const char *p, const char *body)
23757 {
23758   if (*p == ' ')
23759     {
23760       complaint (_("macro definition contains spaces "
23761                    "in formal argument list:\n`%s'"),
23762                  body);
23763
23764       while (*p == ' ')
23765         p++;
23766     }
23767
23768   return p;
23769 }
23770
23771
23772 static void
23773 parse_macro_definition (struct macro_source_file *file, int line,
23774                         const char *body)
23775 {
23776   const char *p;
23777
23778   /* The body string takes one of two forms.  For object-like macro
23779      definitions, it should be:
23780
23781         <macro name> " " <definition>
23782
23783      For function-like macro definitions, it should be:
23784
23785         <macro name> "() " <definition>
23786      or
23787         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23788
23789      Spaces may appear only where explicitly indicated, and in the
23790      <definition>.
23791
23792      The Dwarf 2 spec says that an object-like macro's name is always
23793      followed by a space, but versions of GCC around March 2002 omit
23794      the space when the macro's definition is the empty string.
23795
23796      The Dwarf 2 spec says that there should be no spaces between the
23797      formal arguments in a function-like macro's formal argument list,
23798      but versions of GCC around March 2002 include spaces after the
23799      commas.  */
23800
23801
23802   /* Find the extent of the macro name.  The macro name is terminated
23803      by either a space or null character (for an object-like macro) or
23804      an opening paren (for a function-like macro).  */
23805   for (p = body; *p; p++)
23806     if (*p == ' ' || *p == '(')
23807       break;
23808
23809   if (*p == ' ' || *p == '\0')
23810     {
23811       /* It's an object-like macro.  */
23812       int name_len = p - body;
23813       char *name = savestring (body, name_len);
23814       const char *replacement;
23815
23816       if (*p == ' ')
23817         replacement = body + name_len + 1;
23818       else
23819         {
23820           dwarf2_macro_malformed_definition_complaint (body);
23821           replacement = body + name_len;
23822         }
23823
23824       macro_define_object (file, line, name, replacement);
23825
23826       xfree (name);
23827     }
23828   else if (*p == '(')
23829     {
23830       /* It's a function-like macro.  */
23831       char *name = savestring (body, p - body);
23832       int argc = 0;
23833       int argv_size = 1;
23834       char **argv = XNEWVEC (char *, argv_size);
23835
23836       p++;
23837
23838       p = consume_improper_spaces (p, body);
23839
23840       /* Parse the formal argument list.  */
23841       while (*p && *p != ')')
23842         {
23843           /* Find the extent of the current argument name.  */
23844           const char *arg_start = p;
23845
23846           while (*p && *p != ',' && *p != ')' && *p != ' ')
23847             p++;
23848
23849           if (! *p || p == arg_start)
23850             dwarf2_macro_malformed_definition_complaint (body);
23851           else
23852             {
23853               /* Make sure argv has room for the new argument.  */
23854               if (argc >= argv_size)
23855                 {
23856                   argv_size *= 2;
23857                   argv = XRESIZEVEC (char *, argv, argv_size);
23858                 }
23859
23860               argv[argc++] = savestring (arg_start, p - arg_start);
23861             }
23862
23863           p = consume_improper_spaces (p, body);
23864
23865           /* Consume the comma, if present.  */
23866           if (*p == ',')
23867             {
23868               p++;
23869
23870               p = consume_improper_spaces (p, body);
23871             }
23872         }
23873
23874       if (*p == ')')
23875         {
23876           p++;
23877
23878           if (*p == ' ')
23879             /* Perfectly formed definition, no complaints.  */
23880             macro_define_function (file, line, name,
23881                                    argc, (const char **) argv,
23882                                    p + 1);
23883           else if (*p == '\0')
23884             {
23885               /* Complain, but do define it.  */
23886               dwarf2_macro_malformed_definition_complaint (body);
23887               macro_define_function (file, line, name,
23888                                      argc, (const char **) argv,
23889                                      p);
23890             }
23891           else
23892             /* Just complain.  */
23893             dwarf2_macro_malformed_definition_complaint (body);
23894         }
23895       else
23896         /* Just complain.  */
23897         dwarf2_macro_malformed_definition_complaint (body);
23898
23899       xfree (name);
23900       {
23901         int i;
23902
23903         for (i = 0; i < argc; i++)
23904           xfree (argv[i]);
23905       }
23906       xfree (argv);
23907     }
23908   else
23909     dwarf2_macro_malformed_definition_complaint (body);
23910 }
23911
23912 /* Skip some bytes from BYTES according to the form given in FORM.
23913    Returns the new pointer.  */
23914
23915 static const gdb_byte *
23916 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23917                  enum dwarf_form form,
23918                  unsigned int offset_size,
23919                  struct dwarf2_section_info *section)
23920 {
23921   unsigned int bytes_read;
23922
23923   switch (form)
23924     {
23925     case DW_FORM_data1:
23926     case DW_FORM_flag:
23927       ++bytes;
23928       break;
23929
23930     case DW_FORM_data2:
23931       bytes += 2;
23932       break;
23933
23934     case DW_FORM_data4:
23935       bytes += 4;
23936       break;
23937
23938     case DW_FORM_data8:
23939       bytes += 8;
23940       break;
23941
23942     case DW_FORM_data16:
23943       bytes += 16;
23944       break;
23945
23946     case DW_FORM_string:
23947       read_direct_string (abfd, bytes, &bytes_read);
23948       bytes += bytes_read;
23949       break;
23950
23951     case DW_FORM_sec_offset:
23952     case DW_FORM_strp:
23953     case DW_FORM_GNU_strp_alt:
23954       bytes += offset_size;
23955       break;
23956
23957     case DW_FORM_block:
23958       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
23959       bytes += bytes_read;
23960       break;
23961
23962     case DW_FORM_block1:
23963       bytes += 1 + read_1_byte (abfd, bytes);
23964       break;
23965     case DW_FORM_block2:
23966       bytes += 2 + read_2_bytes (abfd, bytes);
23967       break;
23968     case DW_FORM_block4:
23969       bytes += 4 + read_4_bytes (abfd, bytes);
23970       break;
23971
23972     case DW_FORM_sdata:
23973     case DW_FORM_udata:
23974     case DW_FORM_GNU_addr_index:
23975     case DW_FORM_GNU_str_index:
23976       bytes = gdb_skip_leb128 (bytes, buffer_end);
23977       if (bytes == NULL)
23978         {
23979           dwarf2_section_buffer_overflow_complaint (section);
23980           return NULL;
23981         }
23982       break;
23983
23984     case DW_FORM_implicit_const:
23985       break;
23986
23987     default:
23988       {
23989         complaint (_("invalid form 0x%x in `%s'"),
23990                    form, get_section_name (section));
23991         return NULL;
23992       }
23993     }
23994
23995   return bytes;
23996 }
23997
23998 /* A helper for dwarf_decode_macros that handles skipping an unknown
23999    opcode.  Returns an updated pointer to the macro data buffer; or,
24000    on error, issues a complaint and returns NULL.  */
24001
24002 static const gdb_byte *
24003 skip_unknown_opcode (unsigned int opcode,
24004                      const gdb_byte **opcode_definitions,
24005                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24006                      bfd *abfd,
24007                      unsigned int offset_size,
24008                      struct dwarf2_section_info *section)
24009 {
24010   unsigned int bytes_read, i;
24011   unsigned long arg;
24012   const gdb_byte *defn;
24013
24014   if (opcode_definitions[opcode] == NULL)
24015     {
24016       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
24017                  opcode);
24018       return NULL;
24019     }
24020
24021   defn = opcode_definitions[opcode];
24022   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24023   defn += bytes_read;
24024
24025   for (i = 0; i < arg; ++i)
24026     {
24027       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24028                                  (enum dwarf_form) defn[i], offset_size,
24029                                  section);
24030       if (mac_ptr == NULL)
24031         {
24032           /* skip_form_bytes already issued the complaint.  */
24033           return NULL;
24034         }
24035     }
24036
24037   return mac_ptr;
24038 }
24039
24040 /* A helper function which parses the header of a macro section.
24041    If the macro section is the extended (for now called "GNU") type,
24042    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24043    the header, or issues a complaint and returns NULL on error.  */
24044
24045 static const gdb_byte *
24046 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24047                           bfd *abfd,
24048                           const gdb_byte *mac_ptr,
24049                           unsigned int *offset_size,
24050                           int section_is_gnu)
24051 {
24052   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24053
24054   if (section_is_gnu)
24055     {
24056       unsigned int version, flags;
24057
24058       version = read_2_bytes (abfd, mac_ptr);
24059       if (version != 4 && version != 5)
24060         {
24061           complaint (_("unrecognized version `%d' in .debug_macro section"),
24062                      version);
24063           return NULL;
24064         }
24065       mac_ptr += 2;
24066
24067       flags = read_1_byte (abfd, mac_ptr);
24068       ++mac_ptr;
24069       *offset_size = (flags & 1) ? 8 : 4;
24070
24071       if ((flags & 2) != 0)
24072         /* We don't need the line table offset.  */
24073         mac_ptr += *offset_size;
24074
24075       /* Vendor opcode descriptions.  */
24076       if ((flags & 4) != 0)
24077         {
24078           unsigned int i, count;
24079
24080           count = read_1_byte (abfd, mac_ptr);
24081           ++mac_ptr;
24082           for (i = 0; i < count; ++i)
24083             {
24084               unsigned int opcode, bytes_read;
24085               unsigned long arg;
24086
24087               opcode = read_1_byte (abfd, mac_ptr);
24088               ++mac_ptr;
24089               opcode_definitions[opcode] = mac_ptr;
24090               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24091               mac_ptr += bytes_read;
24092               mac_ptr += arg;
24093             }
24094         }
24095     }
24096
24097   return mac_ptr;
24098 }
24099
24100 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24101    including DW_MACRO_import.  */
24102
24103 static void
24104 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24105                           bfd *abfd,
24106                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24107                           struct macro_source_file *current_file,
24108                           struct line_header *lh,
24109                           struct dwarf2_section_info *section,
24110                           int section_is_gnu, int section_is_dwz,
24111                           unsigned int offset_size,
24112                           htab_t include_hash)
24113 {
24114   struct objfile *objfile = dwarf2_per_objfile->objfile;
24115   enum dwarf_macro_record_type macinfo_type;
24116   int at_commandline;
24117   const gdb_byte *opcode_definitions[256];
24118
24119   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24120                                       &offset_size, section_is_gnu);
24121   if (mac_ptr == NULL)
24122     {
24123       /* We already issued a complaint.  */
24124       return;
24125     }
24126
24127   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24128      GDB is still reading the definitions from command line.  First
24129      DW_MACINFO_start_file will need to be ignored as it was already executed
24130      to create CURRENT_FILE for the main source holding also the command line
24131      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24132      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24133
24134   at_commandline = 1;
24135
24136   do
24137     {
24138       /* Do we at least have room for a macinfo type byte?  */
24139       if (mac_ptr >= mac_end)
24140         {
24141           dwarf2_section_buffer_overflow_complaint (section);
24142           break;
24143         }
24144
24145       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24146       mac_ptr++;
24147
24148       /* Note that we rely on the fact that the corresponding GNU and
24149          DWARF constants are the same.  */
24150       DIAGNOSTIC_PUSH
24151       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24152       switch (macinfo_type)
24153         {
24154           /* A zero macinfo type indicates the end of the macro
24155              information.  */
24156         case 0:
24157           break;
24158
24159         case DW_MACRO_define:
24160         case DW_MACRO_undef:
24161         case DW_MACRO_define_strp:
24162         case DW_MACRO_undef_strp:
24163         case DW_MACRO_define_sup:
24164         case DW_MACRO_undef_sup:
24165           {
24166             unsigned int bytes_read;
24167             int line;
24168             const char *body;
24169             int is_define;
24170
24171             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24172             mac_ptr += bytes_read;
24173
24174             if (macinfo_type == DW_MACRO_define
24175                 || macinfo_type == DW_MACRO_undef)
24176               {
24177                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24178                 mac_ptr += bytes_read;
24179               }
24180             else
24181               {
24182                 LONGEST str_offset;
24183
24184                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24185                 mac_ptr += offset_size;
24186
24187                 if (macinfo_type == DW_MACRO_define_sup
24188                     || macinfo_type == DW_MACRO_undef_sup
24189                     || section_is_dwz)
24190                   {
24191                     struct dwz_file *dwz
24192                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24193
24194                     body = read_indirect_string_from_dwz (objfile,
24195                                                           dwz, str_offset);
24196                   }
24197                 else
24198                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24199                                                          abfd, str_offset);
24200               }
24201
24202             is_define = (macinfo_type == DW_MACRO_define
24203                          || macinfo_type == DW_MACRO_define_strp
24204                          || macinfo_type == DW_MACRO_define_sup);
24205             if (! current_file)
24206               {
24207                 /* DWARF violation as no main source is present.  */
24208                 complaint (_("debug info with no main source gives macro %s "
24209                              "on line %d: %s"),
24210                            is_define ? _("definition") : _("undefinition"),
24211                            line, body);
24212                 break;
24213               }
24214             if ((line == 0 && !at_commandline)
24215                 || (line != 0 && at_commandline))
24216               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24217                          at_commandline ? _("command-line") : _("in-file"),
24218                          is_define ? _("definition") : _("undefinition"),
24219                          line == 0 ? _("zero") : _("non-zero"), line, body);
24220
24221             if (is_define)
24222               parse_macro_definition (current_file, line, body);
24223             else
24224               {
24225                 gdb_assert (macinfo_type == DW_MACRO_undef
24226                             || macinfo_type == DW_MACRO_undef_strp
24227                             || macinfo_type == DW_MACRO_undef_sup);
24228                 macro_undef (current_file, line, body);
24229               }
24230           }
24231           break;
24232
24233         case DW_MACRO_start_file:
24234           {
24235             unsigned int bytes_read;
24236             int line, file;
24237
24238             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24239             mac_ptr += bytes_read;
24240             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24241             mac_ptr += bytes_read;
24242
24243             if ((line == 0 && !at_commandline)
24244                 || (line != 0 && at_commandline))
24245               complaint (_("debug info gives source %d included "
24246                            "from %s at %s line %d"),
24247                          file, at_commandline ? _("command-line") : _("file"),
24248                          line == 0 ? _("zero") : _("non-zero"), line);
24249
24250             if (at_commandline)
24251               {
24252                 /* This DW_MACRO_start_file was executed in the
24253                    pass one.  */
24254                 at_commandline = 0;
24255               }
24256             else
24257               current_file = macro_start_file (file, line, current_file, lh);
24258           }
24259           break;
24260
24261         case DW_MACRO_end_file:
24262           if (! current_file)
24263             complaint (_("macro debug info has an unmatched "
24264                          "`close_file' directive"));
24265           else
24266             {
24267               current_file = current_file->included_by;
24268               if (! current_file)
24269                 {
24270                   enum dwarf_macro_record_type next_type;
24271
24272                   /* GCC circa March 2002 doesn't produce the zero
24273                      type byte marking the end of the compilation
24274                      unit.  Complain if it's not there, but exit no
24275                      matter what.  */
24276
24277                   /* Do we at least have room for a macinfo type byte?  */
24278                   if (mac_ptr >= mac_end)
24279                     {
24280                       dwarf2_section_buffer_overflow_complaint (section);
24281                       return;
24282                     }
24283
24284                   /* We don't increment mac_ptr here, so this is just
24285                      a look-ahead.  */
24286                   next_type
24287                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24288                                                                   mac_ptr);
24289                   if (next_type != 0)
24290                     complaint (_("no terminating 0-type entry for "
24291                                  "macros in `.debug_macinfo' section"));
24292
24293                   return;
24294                 }
24295             }
24296           break;
24297
24298         case DW_MACRO_import:
24299         case DW_MACRO_import_sup:
24300           {
24301             LONGEST offset;
24302             void **slot;
24303             bfd *include_bfd = abfd;
24304             struct dwarf2_section_info *include_section = section;
24305             const gdb_byte *include_mac_end = mac_end;
24306             int is_dwz = section_is_dwz;
24307             const gdb_byte *new_mac_ptr;
24308
24309             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24310             mac_ptr += offset_size;
24311
24312             if (macinfo_type == DW_MACRO_import_sup)
24313               {
24314                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24315
24316                 dwarf2_read_section (objfile, &dwz->macro);
24317
24318                 include_section = &dwz->macro;
24319                 include_bfd = get_section_bfd_owner (include_section);
24320                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24321                 is_dwz = 1;
24322               }
24323
24324             new_mac_ptr = include_section->buffer + offset;
24325             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24326
24327             if (*slot != NULL)
24328               {
24329                 /* This has actually happened; see
24330                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24331                 complaint (_("recursive DW_MACRO_import in "
24332                              ".debug_macro section"));
24333               }
24334             else
24335               {
24336                 *slot = (void *) new_mac_ptr;
24337
24338                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24339                                           include_bfd, new_mac_ptr,
24340                                           include_mac_end, current_file, lh,
24341                                           section, section_is_gnu, is_dwz,
24342                                           offset_size, include_hash);
24343
24344                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24345               }
24346           }
24347           break;
24348
24349         case DW_MACINFO_vendor_ext:
24350           if (!section_is_gnu)
24351             {
24352               unsigned int bytes_read;
24353
24354               /* This reads the constant, but since we don't recognize
24355                  any vendor extensions, we ignore it.  */
24356               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24357               mac_ptr += bytes_read;
24358               read_direct_string (abfd, mac_ptr, &bytes_read);
24359               mac_ptr += bytes_read;
24360
24361               /* We don't recognize any vendor extensions.  */
24362               break;
24363             }
24364           /* FALLTHROUGH */
24365
24366         default:
24367           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24368                                          mac_ptr, mac_end, abfd, offset_size,
24369                                          section);
24370           if (mac_ptr == NULL)
24371             return;
24372           break;
24373         }
24374       DIAGNOSTIC_POP
24375     } while (macinfo_type != 0);
24376 }
24377
24378 static void
24379 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24380                      int section_is_gnu)
24381 {
24382   struct dwarf2_per_objfile *dwarf2_per_objfile
24383     = cu->per_cu->dwarf2_per_objfile;
24384   struct objfile *objfile = dwarf2_per_objfile->objfile;
24385   struct line_header *lh = cu->line_header;
24386   bfd *abfd;
24387   const gdb_byte *mac_ptr, *mac_end;
24388   struct macro_source_file *current_file = 0;
24389   enum dwarf_macro_record_type macinfo_type;
24390   unsigned int offset_size = cu->header.offset_size;
24391   const gdb_byte *opcode_definitions[256];
24392   void **slot;
24393   struct dwarf2_section_info *section;
24394   const char *section_name;
24395
24396   if (cu->dwo_unit != NULL)
24397     {
24398       if (section_is_gnu)
24399         {
24400           section = &cu->dwo_unit->dwo_file->sections.macro;
24401           section_name = ".debug_macro.dwo";
24402         }
24403       else
24404         {
24405           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24406           section_name = ".debug_macinfo.dwo";
24407         }
24408     }
24409   else
24410     {
24411       if (section_is_gnu)
24412         {
24413           section = &dwarf2_per_objfile->macro;
24414           section_name = ".debug_macro";
24415         }
24416       else
24417         {
24418           section = &dwarf2_per_objfile->macinfo;
24419           section_name = ".debug_macinfo";
24420         }
24421     }
24422
24423   dwarf2_read_section (objfile, section);
24424   if (section->buffer == NULL)
24425     {
24426       complaint (_("missing %s section"), section_name);
24427       return;
24428     }
24429   abfd = get_section_bfd_owner (section);
24430
24431   /* First pass: Find the name of the base filename.
24432      This filename is needed in order to process all macros whose definition
24433      (or undefinition) comes from the command line.  These macros are defined
24434      before the first DW_MACINFO_start_file entry, and yet still need to be
24435      associated to the base file.
24436
24437      To determine the base file name, we scan the macro definitions until we
24438      reach the first DW_MACINFO_start_file entry.  We then initialize
24439      CURRENT_FILE accordingly so that any macro definition found before the
24440      first DW_MACINFO_start_file can still be associated to the base file.  */
24441
24442   mac_ptr = section->buffer + offset;
24443   mac_end = section->buffer + section->size;
24444
24445   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24446                                       &offset_size, section_is_gnu);
24447   if (mac_ptr == NULL)
24448     {
24449       /* We already issued a complaint.  */
24450       return;
24451     }
24452
24453   do
24454     {
24455       /* Do we at least have room for a macinfo type byte?  */
24456       if (mac_ptr >= mac_end)
24457         {
24458           /* Complaint is printed during the second pass as GDB will probably
24459              stop the first pass earlier upon finding
24460              DW_MACINFO_start_file.  */
24461           break;
24462         }
24463
24464       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24465       mac_ptr++;
24466
24467       /* Note that we rely on the fact that the corresponding GNU and
24468          DWARF constants are the same.  */
24469       DIAGNOSTIC_PUSH
24470       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24471       switch (macinfo_type)
24472         {
24473           /* A zero macinfo type indicates the end of the macro
24474              information.  */
24475         case 0:
24476           break;
24477
24478         case DW_MACRO_define:
24479         case DW_MACRO_undef:
24480           /* Only skip the data by MAC_PTR.  */
24481           {
24482             unsigned int bytes_read;
24483
24484             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24485             mac_ptr += bytes_read;
24486             read_direct_string (abfd, mac_ptr, &bytes_read);
24487             mac_ptr += bytes_read;
24488           }
24489           break;
24490
24491         case DW_MACRO_start_file:
24492           {
24493             unsigned int bytes_read;
24494             int line, file;
24495
24496             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24497             mac_ptr += bytes_read;
24498             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24499             mac_ptr += bytes_read;
24500
24501             current_file = macro_start_file (file, line, current_file, lh);
24502           }
24503           break;
24504
24505         case DW_MACRO_end_file:
24506           /* No data to skip by MAC_PTR.  */
24507           break;
24508
24509         case DW_MACRO_define_strp:
24510         case DW_MACRO_undef_strp:
24511         case DW_MACRO_define_sup:
24512         case DW_MACRO_undef_sup:
24513           {
24514             unsigned int bytes_read;
24515
24516             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24517             mac_ptr += bytes_read;
24518             mac_ptr += offset_size;
24519           }
24520           break;
24521
24522         case DW_MACRO_import:
24523         case DW_MACRO_import_sup:
24524           /* Note that, according to the spec, a transparent include
24525              chain cannot call DW_MACRO_start_file.  So, we can just
24526              skip this opcode.  */
24527           mac_ptr += offset_size;
24528           break;
24529
24530         case DW_MACINFO_vendor_ext:
24531           /* Only skip the data by MAC_PTR.  */
24532           if (!section_is_gnu)
24533             {
24534               unsigned int bytes_read;
24535
24536               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24537               mac_ptr += bytes_read;
24538               read_direct_string (abfd, mac_ptr, &bytes_read);
24539               mac_ptr += bytes_read;
24540             }
24541           /* FALLTHROUGH */
24542
24543         default:
24544           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24545                                          mac_ptr, mac_end, abfd, offset_size,
24546                                          section);
24547           if (mac_ptr == NULL)
24548             return;
24549           break;
24550         }
24551       DIAGNOSTIC_POP
24552     } while (macinfo_type != 0 && current_file == NULL);
24553
24554   /* Second pass: Process all entries.
24555
24556      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24557      command-line macro definitions/undefinitions.  This flag is unset when we
24558      reach the first DW_MACINFO_start_file entry.  */
24559
24560   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24561                                            htab_eq_pointer,
24562                                            NULL, xcalloc, xfree));
24563   mac_ptr = section->buffer + offset;
24564   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24565   *slot = (void *) mac_ptr;
24566   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24567                             abfd, mac_ptr, mac_end,
24568                             current_file, lh, section,
24569                             section_is_gnu, 0, offset_size,
24570                             include_hash.get ());
24571 }
24572
24573 /* Check if the attribute's form is a DW_FORM_block*
24574    if so return true else false.  */
24575
24576 static int
24577 attr_form_is_block (const struct attribute *attr)
24578 {
24579   return (attr == NULL ? 0 :
24580       attr->form == DW_FORM_block1
24581       || attr->form == DW_FORM_block2
24582       || attr->form == DW_FORM_block4
24583       || attr->form == DW_FORM_block
24584       || attr->form == DW_FORM_exprloc);
24585 }
24586
24587 /* Return non-zero if ATTR's value is a section offset --- classes
24588    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24589    You may use DW_UNSND (attr) to retrieve such offsets.
24590
24591    Section 7.5.4, "Attribute Encodings", explains that no attribute
24592    may have a value that belongs to more than one of these classes; it
24593    would be ambiguous if we did, because we use the same forms for all
24594    of them.  */
24595
24596 static int
24597 attr_form_is_section_offset (const struct attribute *attr)
24598 {
24599   return (attr->form == DW_FORM_data4
24600           || attr->form == DW_FORM_data8
24601           || attr->form == DW_FORM_sec_offset);
24602 }
24603
24604 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24605    zero otherwise.  When this function returns true, you can apply
24606    dwarf2_get_attr_constant_value to it.
24607
24608    However, note that for some attributes you must check
24609    attr_form_is_section_offset before using this test.  DW_FORM_data4
24610    and DW_FORM_data8 are members of both the constant class, and of
24611    the classes that contain offsets into other debug sections
24612    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24613    that, if an attribute's can be either a constant or one of the
24614    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24615    taken as section offsets, not constants.
24616
24617    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24618    cannot handle that.  */
24619
24620 static int
24621 attr_form_is_constant (const struct attribute *attr)
24622 {
24623   switch (attr->form)
24624     {
24625     case DW_FORM_sdata:
24626     case DW_FORM_udata:
24627     case DW_FORM_data1:
24628     case DW_FORM_data2:
24629     case DW_FORM_data4:
24630     case DW_FORM_data8:
24631     case DW_FORM_implicit_const:
24632       return 1;
24633     default:
24634       return 0;
24635     }
24636 }
24637
24638
24639 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24640    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24641
24642 static int
24643 attr_form_is_ref (const struct attribute *attr)
24644 {
24645   switch (attr->form)
24646     {
24647     case DW_FORM_ref_addr:
24648     case DW_FORM_ref1:
24649     case DW_FORM_ref2:
24650     case DW_FORM_ref4:
24651     case DW_FORM_ref8:
24652     case DW_FORM_ref_udata:
24653     case DW_FORM_GNU_ref_alt:
24654       return 1;
24655     default:
24656       return 0;
24657     }
24658 }
24659
24660 /* Return the .debug_loc section to use for CU.
24661    For DWO files use .debug_loc.dwo.  */
24662
24663 static struct dwarf2_section_info *
24664 cu_debug_loc_section (struct dwarf2_cu *cu)
24665 {
24666   struct dwarf2_per_objfile *dwarf2_per_objfile
24667     = cu->per_cu->dwarf2_per_objfile;
24668
24669   if (cu->dwo_unit)
24670     {
24671       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24672       
24673       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24674     }
24675   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24676                                   : &dwarf2_per_objfile->loc);
24677 }
24678
24679 /* A helper function that fills in a dwarf2_loclist_baton.  */
24680
24681 static void
24682 fill_in_loclist_baton (struct dwarf2_cu *cu,
24683                        struct dwarf2_loclist_baton *baton,
24684                        const struct attribute *attr)
24685 {
24686   struct dwarf2_per_objfile *dwarf2_per_objfile
24687     = cu->per_cu->dwarf2_per_objfile;
24688   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24689
24690   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24691
24692   baton->per_cu = cu->per_cu;
24693   gdb_assert (baton->per_cu);
24694   /* We don't know how long the location list is, but make sure we
24695      don't run off the edge of the section.  */
24696   baton->size = section->size - DW_UNSND (attr);
24697   baton->data = section->buffer + DW_UNSND (attr);
24698   baton->base_address = cu->base_address;
24699   baton->from_dwo = cu->dwo_unit != NULL;
24700 }
24701
24702 static void
24703 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24704                              struct dwarf2_cu *cu, int is_block)
24705 {
24706   struct dwarf2_per_objfile *dwarf2_per_objfile
24707     = cu->per_cu->dwarf2_per_objfile;
24708   struct objfile *objfile = dwarf2_per_objfile->objfile;
24709   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24710
24711   if (attr_form_is_section_offset (attr)
24712       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24713          the section.  If so, fall through to the complaint in the
24714          other branch.  */
24715       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24716     {
24717       struct dwarf2_loclist_baton *baton;
24718
24719       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24720
24721       fill_in_loclist_baton (cu, baton, attr);
24722
24723       if (cu->base_known == 0)
24724         complaint (_("Location list used without "
24725                      "specifying the CU base address."));
24726
24727       SYMBOL_ACLASS_INDEX (sym) = (is_block
24728                                    ? dwarf2_loclist_block_index
24729                                    : dwarf2_loclist_index);
24730       SYMBOL_LOCATION_BATON (sym) = baton;
24731     }
24732   else
24733     {
24734       struct dwarf2_locexpr_baton *baton;
24735
24736       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24737       baton->per_cu = cu->per_cu;
24738       gdb_assert (baton->per_cu);
24739
24740       if (attr_form_is_block (attr))
24741         {
24742           /* Note that we're just copying the block's data pointer
24743              here, not the actual data.  We're still pointing into the
24744              info_buffer for SYM's objfile; right now we never release
24745              that buffer, but when we do clean up properly this may
24746              need to change.  */
24747           baton->size = DW_BLOCK (attr)->size;
24748           baton->data = DW_BLOCK (attr)->data;
24749         }
24750       else
24751         {
24752           dwarf2_invalid_attrib_class_complaint ("location description",
24753                                                  SYMBOL_NATURAL_NAME (sym));
24754           baton->size = 0;
24755         }
24756
24757       SYMBOL_ACLASS_INDEX (sym) = (is_block
24758                                    ? dwarf2_locexpr_block_index
24759                                    : dwarf2_locexpr_index);
24760       SYMBOL_LOCATION_BATON (sym) = baton;
24761     }
24762 }
24763
24764 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24765    came from a separate debuginfo file, then the master objfile is
24766    returned.  */
24767
24768 struct objfile *
24769 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24770 {
24771   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24772
24773   /* Return the master objfile, so that we can report and look up the
24774      correct file containing this variable.  */
24775   if (objfile->separate_debug_objfile_backlink)
24776     objfile = objfile->separate_debug_objfile_backlink;
24777
24778   return objfile;
24779 }
24780
24781 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24782    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24783    CU_HEADERP first.  */
24784
24785 static const struct comp_unit_head *
24786 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24787                        struct dwarf2_per_cu_data *per_cu)
24788 {
24789   const gdb_byte *info_ptr;
24790
24791   if (per_cu->cu)
24792     return &per_cu->cu->header;
24793
24794   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24795
24796   memset (cu_headerp, 0, sizeof (*cu_headerp));
24797   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24798                        rcuh_kind::COMPILE);
24799
24800   return cu_headerp;
24801 }
24802
24803 /* Return the address size given in the compilation unit header for CU.  */
24804
24805 int
24806 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24807 {
24808   struct comp_unit_head cu_header_local;
24809   const struct comp_unit_head *cu_headerp;
24810
24811   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24812
24813   return cu_headerp->addr_size;
24814 }
24815
24816 /* Return the offset size given in the compilation unit header for CU.  */
24817
24818 int
24819 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24820 {
24821   struct comp_unit_head cu_header_local;
24822   const struct comp_unit_head *cu_headerp;
24823
24824   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24825
24826   return cu_headerp->offset_size;
24827 }
24828
24829 /* See its dwarf2loc.h declaration.  */
24830
24831 int
24832 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24833 {
24834   struct comp_unit_head cu_header_local;
24835   const struct comp_unit_head *cu_headerp;
24836
24837   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24838
24839   if (cu_headerp->version == 2)
24840     return cu_headerp->addr_size;
24841   else
24842     return cu_headerp->offset_size;
24843 }
24844
24845 /* Return the text offset of the CU.  The returned offset comes from
24846    this CU's objfile.  If this objfile came from a separate debuginfo
24847    file, then the offset may be different from the corresponding
24848    offset in the parent objfile.  */
24849
24850 CORE_ADDR
24851 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24852 {
24853   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24854
24855   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24856 }
24857
24858 /* Return DWARF version number of PER_CU.  */
24859
24860 short
24861 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24862 {
24863   return per_cu->dwarf_version;
24864 }
24865
24866 /* Locate the .debug_info compilation unit from CU's objfile which contains
24867    the DIE at OFFSET.  Raises an error on failure.  */
24868
24869 static struct dwarf2_per_cu_data *
24870 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24871                                   unsigned int offset_in_dwz,
24872                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24873 {
24874   struct dwarf2_per_cu_data *this_cu;
24875   int low, high;
24876   const sect_offset *cu_off;
24877
24878   low = 0;
24879   high = dwarf2_per_objfile->all_comp_units.size () - 1;
24880   while (high > low)
24881     {
24882       struct dwarf2_per_cu_data *mid_cu;
24883       int mid = low + (high - low) / 2;
24884
24885       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24886       cu_off = &mid_cu->sect_off;
24887       if (mid_cu->is_dwz > offset_in_dwz
24888           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24889         high = mid;
24890       else
24891         low = mid + 1;
24892     }
24893   gdb_assert (low == high);
24894   this_cu = dwarf2_per_objfile->all_comp_units[low];
24895   cu_off = &this_cu->sect_off;
24896   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24897     {
24898       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24899         error (_("Dwarf Error: could not find partial DIE containing "
24900                "offset %s [in module %s]"),
24901                sect_offset_str (sect_off),
24902                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
24903
24904       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24905                   <= sect_off);
24906       return dwarf2_per_objfile->all_comp_units[low-1];
24907     }
24908   else
24909     {
24910       this_cu = dwarf2_per_objfile->all_comp_units[low];
24911       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
24912           && sect_off >= this_cu->sect_off + this_cu->length)
24913         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
24914       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24915       return this_cu;
24916     }
24917 }
24918
24919 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24920
24921 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
24922   : per_cu (per_cu_),
24923     mark (0),
24924     has_loclist (0),
24925     checked_producer (0),
24926     producer_is_gxx_lt_4_6 (0),
24927     producer_is_gcc_lt_4_3 (0),
24928     producer_is_icc_lt_14 (0),
24929     processing_has_namespace_info (0)
24930 {
24931   per_cu->cu = this;
24932 }
24933
24934 /* Destroy a dwarf2_cu.  */
24935
24936 dwarf2_cu::~dwarf2_cu ()
24937 {
24938   per_cu->cu = NULL;
24939 }
24940
24941 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24942
24943 static void
24944 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24945                        enum language pretend_language)
24946 {
24947   struct attribute *attr;
24948
24949   /* Set the language we're debugging.  */
24950   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24951   if (attr)
24952     set_cu_language (DW_UNSND (attr), cu);
24953   else
24954     {
24955       cu->language = pretend_language;
24956       cu->language_defn = language_def (cu->language);
24957     }
24958
24959   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24960 }
24961
24962 /* Increase the age counter on each cached compilation unit, and free
24963    any that are too old.  */
24964
24965 static void
24966 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
24967 {
24968   struct dwarf2_per_cu_data *per_cu, **last_chain;
24969
24970   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
24971   per_cu = dwarf2_per_objfile->read_in_chain;
24972   while (per_cu != NULL)
24973     {
24974       per_cu->cu->last_used ++;
24975       if (per_cu->cu->last_used <= dwarf_max_cache_age)
24976         dwarf2_mark (per_cu->cu);
24977       per_cu = per_cu->cu->read_in_chain;
24978     }
24979
24980   per_cu = dwarf2_per_objfile->read_in_chain;
24981   last_chain = &dwarf2_per_objfile->read_in_chain;
24982   while (per_cu != NULL)
24983     {
24984       struct dwarf2_per_cu_data *next_cu;
24985
24986       next_cu = per_cu->cu->read_in_chain;
24987
24988       if (!per_cu->cu->mark)
24989         {
24990           delete per_cu->cu;
24991           *last_chain = next_cu;
24992         }
24993       else
24994         last_chain = &per_cu->cu->read_in_chain;
24995
24996       per_cu = next_cu;
24997     }
24998 }
24999
25000 /* Remove a single compilation unit from the cache.  */
25001
25002 static void
25003 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25004 {
25005   struct dwarf2_per_cu_data *per_cu, **last_chain;
25006   struct dwarf2_per_objfile *dwarf2_per_objfile
25007     = target_per_cu->dwarf2_per_objfile;
25008
25009   per_cu = dwarf2_per_objfile->read_in_chain;
25010   last_chain = &dwarf2_per_objfile->read_in_chain;
25011   while (per_cu != NULL)
25012     {
25013       struct dwarf2_per_cu_data *next_cu;
25014
25015       next_cu = per_cu->cu->read_in_chain;
25016
25017       if (per_cu == target_per_cu)
25018         {
25019           delete per_cu->cu;
25020           per_cu->cu = NULL;
25021           *last_chain = next_cu;
25022           break;
25023         }
25024       else
25025         last_chain = &per_cu->cu->read_in_chain;
25026
25027       per_cu = next_cu;
25028     }
25029 }
25030
25031 /* Cleanup function for the dwarf2_per_objfile data.  */
25032
25033 static void
25034 dwarf2_free_objfile (struct objfile *objfile, void *datum)
25035 {
25036   struct dwarf2_per_objfile *dwarf2_per_objfile
25037     = static_cast<struct dwarf2_per_objfile *> (datum);
25038
25039   delete dwarf2_per_objfile;
25040 }
25041
25042 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25043    We store these in a hash table separate from the DIEs, and preserve them
25044    when the DIEs are flushed out of cache.
25045
25046    The CU "per_cu" pointer is needed because offset alone is not enough to
25047    uniquely identify the type.  A file may have multiple .debug_types sections,
25048    or the type may come from a DWO file.  Furthermore, while it's more logical
25049    to use per_cu->section+offset, with Fission the section with the data is in
25050    the DWO file but we don't know that section at the point we need it.
25051    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25052    because we can enter the lookup routine, get_die_type_at_offset, from
25053    outside this file, and thus won't necessarily have PER_CU->cu.
25054    Fortunately, PER_CU is stable for the life of the objfile.  */
25055
25056 struct dwarf2_per_cu_offset_and_type
25057 {
25058   const struct dwarf2_per_cu_data *per_cu;
25059   sect_offset sect_off;
25060   struct type *type;
25061 };
25062
25063 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25064
25065 static hashval_t
25066 per_cu_offset_and_type_hash (const void *item)
25067 {
25068   const struct dwarf2_per_cu_offset_and_type *ofs
25069     = (const struct dwarf2_per_cu_offset_and_type *) item;
25070
25071   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25072 }
25073
25074 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25075
25076 static int
25077 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25078 {
25079   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25080     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25081   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25082     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25083
25084   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25085           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25086 }
25087
25088 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25089    table if necessary.  For convenience, return TYPE.
25090
25091    The DIEs reading must have careful ordering to:
25092     * Not cause infite loops trying to read in DIEs as a prerequisite for
25093       reading current DIE.
25094     * Not trying to dereference contents of still incompletely read in types
25095       while reading in other DIEs.
25096     * Enable referencing still incompletely read in types just by a pointer to
25097       the type without accessing its fields.
25098
25099    Therefore caller should follow these rules:
25100      * Try to fetch any prerequisite types we may need to build this DIE type
25101        before building the type and calling set_die_type.
25102      * After building type call set_die_type for current DIE as soon as
25103        possible before fetching more types to complete the current type.
25104      * Make the type as complete as possible before fetching more types.  */
25105
25106 static struct type *
25107 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25108 {
25109   struct dwarf2_per_objfile *dwarf2_per_objfile
25110     = cu->per_cu->dwarf2_per_objfile;
25111   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25112   struct objfile *objfile = dwarf2_per_objfile->objfile;
25113   struct attribute *attr;
25114   struct dynamic_prop prop;
25115
25116   /* For Ada types, make sure that the gnat-specific data is always
25117      initialized (if not already set).  There are a few types where
25118      we should not be doing so, because the type-specific area is
25119      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25120      where the type-specific area is used to store the floatformat).
25121      But this is not a problem, because the gnat-specific information
25122      is actually not needed for these types.  */
25123   if (need_gnat_info (cu)
25124       && TYPE_CODE (type) != TYPE_CODE_FUNC
25125       && TYPE_CODE (type) != TYPE_CODE_FLT
25126       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25127       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25128       && TYPE_CODE (type) != TYPE_CODE_METHOD
25129       && !HAVE_GNAT_AUX_INFO (type))
25130     INIT_GNAT_SPECIFIC (type);
25131
25132   /* Read DW_AT_allocated and set in type.  */
25133   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25134   if (attr_form_is_block (attr))
25135     {
25136       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25137         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25138     }
25139   else if (attr != NULL)
25140     {
25141       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25142                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25143                  sect_offset_str (die->sect_off));
25144     }
25145
25146   /* Read DW_AT_associated and set in type.  */
25147   attr = dwarf2_attr (die, DW_AT_associated, cu);
25148   if (attr_form_is_block (attr))
25149     {
25150       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25151         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25152     }
25153   else if (attr != NULL)
25154     {
25155       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25156                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25157                  sect_offset_str (die->sect_off));
25158     }
25159
25160   /* Read DW_AT_data_location and set in type.  */
25161   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25162   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25163     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25164
25165   if (dwarf2_per_objfile->die_type_hash == NULL)
25166     {
25167       dwarf2_per_objfile->die_type_hash =
25168         htab_create_alloc_ex (127,
25169                               per_cu_offset_and_type_hash,
25170                               per_cu_offset_and_type_eq,
25171                               NULL,
25172                               &objfile->objfile_obstack,
25173                               hashtab_obstack_allocate,
25174                               dummy_obstack_deallocate);
25175     }
25176
25177   ofs.per_cu = cu->per_cu;
25178   ofs.sect_off = die->sect_off;
25179   ofs.type = type;
25180   slot = (struct dwarf2_per_cu_offset_and_type **)
25181     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25182   if (*slot)
25183     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25184                sect_offset_str (die->sect_off));
25185   *slot = XOBNEW (&objfile->objfile_obstack,
25186                   struct dwarf2_per_cu_offset_and_type);
25187   **slot = ofs;
25188   return type;
25189 }
25190
25191 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25192    or return NULL if the die does not have a saved type.  */
25193
25194 static struct type *
25195 get_die_type_at_offset (sect_offset sect_off,
25196                         struct dwarf2_per_cu_data *per_cu)
25197 {
25198   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25199   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25200
25201   if (dwarf2_per_objfile->die_type_hash == NULL)
25202     return NULL;
25203
25204   ofs.per_cu = per_cu;
25205   ofs.sect_off = sect_off;
25206   slot = ((struct dwarf2_per_cu_offset_and_type *)
25207           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25208   if (slot)
25209     return slot->type;
25210   else
25211     return NULL;
25212 }
25213
25214 /* Look up the type for DIE in CU in die_type_hash,
25215    or return NULL if DIE does not have a saved type.  */
25216
25217 static struct type *
25218 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25219 {
25220   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25221 }
25222
25223 /* Add a dependence relationship from CU to REF_PER_CU.  */
25224
25225 static void
25226 dwarf2_add_dependence (struct dwarf2_cu *cu,
25227                        struct dwarf2_per_cu_data *ref_per_cu)
25228 {
25229   void **slot;
25230
25231   if (cu->dependencies == NULL)
25232     cu->dependencies
25233       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25234                               NULL, &cu->comp_unit_obstack,
25235                               hashtab_obstack_allocate,
25236                               dummy_obstack_deallocate);
25237
25238   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25239   if (*slot == NULL)
25240     *slot = ref_per_cu;
25241 }
25242
25243 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25244    Set the mark field in every compilation unit in the
25245    cache that we must keep because we are keeping CU.  */
25246
25247 static int
25248 dwarf2_mark_helper (void **slot, void *data)
25249 {
25250   struct dwarf2_per_cu_data *per_cu;
25251
25252   per_cu = (struct dwarf2_per_cu_data *) *slot;
25253
25254   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25255      reading of the chain.  As such dependencies remain valid it is not much
25256      useful to track and undo them during QUIT cleanups.  */
25257   if (per_cu->cu == NULL)
25258     return 1;
25259
25260   if (per_cu->cu->mark)
25261     return 1;
25262   per_cu->cu->mark = 1;
25263
25264   if (per_cu->cu->dependencies != NULL)
25265     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25266
25267   return 1;
25268 }
25269
25270 /* Set the mark field in CU and in every other compilation unit in the
25271    cache that we must keep because we are keeping CU.  */
25272
25273 static void
25274 dwarf2_mark (struct dwarf2_cu *cu)
25275 {
25276   if (cu->mark)
25277     return;
25278   cu->mark = 1;
25279   if (cu->dependencies != NULL)
25280     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25281 }
25282
25283 static void
25284 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25285 {
25286   while (per_cu)
25287     {
25288       per_cu->cu->mark = 0;
25289       per_cu = per_cu->cu->read_in_chain;
25290     }
25291 }
25292
25293 /* Trivial hash function for partial_die_info: the hash value of a DIE
25294    is its offset in .debug_info for this objfile.  */
25295
25296 static hashval_t
25297 partial_die_hash (const void *item)
25298 {
25299   const struct partial_die_info *part_die
25300     = (const struct partial_die_info *) item;
25301
25302   return to_underlying (part_die->sect_off);
25303 }
25304
25305 /* Trivial comparison function for partial_die_info structures: two DIEs
25306    are equal if they have the same offset.  */
25307
25308 static int
25309 partial_die_eq (const void *item_lhs, const void *item_rhs)
25310 {
25311   const struct partial_die_info *part_die_lhs
25312     = (const struct partial_die_info *) item_lhs;
25313   const struct partial_die_info *part_die_rhs
25314     = (const struct partial_die_info *) item_rhs;
25315
25316   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25317 }
25318
25319 static struct cmd_list_element *set_dwarf_cmdlist;
25320 static struct cmd_list_element *show_dwarf_cmdlist;
25321
25322 static void
25323 set_dwarf_cmd (const char *args, int from_tty)
25324 {
25325   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25326              gdb_stdout);
25327 }
25328
25329 static void
25330 show_dwarf_cmd (const char *args, int from_tty)
25331 {
25332   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25333 }
25334
25335 int dwarf_always_disassemble;
25336
25337 static void
25338 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25339                                struct cmd_list_element *c, const char *value)
25340 {
25341   fprintf_filtered (file,
25342                     _("Whether to always disassemble "
25343                       "DWARF expressions is %s.\n"),
25344                     value);
25345 }
25346
25347 static void
25348 show_check_physname (struct ui_file *file, int from_tty,
25349                      struct cmd_list_element *c, const char *value)
25350 {
25351   fprintf_filtered (file,
25352                     _("Whether to check \"physname\" is %s.\n"),
25353                     value);
25354 }
25355
25356 void
25357 _initialize_dwarf2_read (void)
25358 {
25359   dwarf2_objfile_data_key
25360     = register_objfile_data_with_cleanup (nullptr, dwarf2_free_objfile);
25361
25362   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25363 Set DWARF specific variables.\n\
25364 Configure DWARF variables such as the cache size"),
25365                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25366                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25367
25368   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25369 Show DWARF specific variables\n\
25370 Show DWARF variables such as the cache size"),
25371                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25372                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25373
25374   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25375                             &dwarf_max_cache_age, _("\
25376 Set the upper bound on the age of cached DWARF compilation units."), _("\
25377 Show the upper bound on the age of cached DWARF compilation units."), _("\
25378 A higher limit means that cached compilation units will be stored\n\
25379 in memory longer, and more total memory will be used.  Zero disables\n\
25380 caching, which can slow down startup."),
25381                             NULL,
25382                             show_dwarf_max_cache_age,
25383                             &set_dwarf_cmdlist,
25384                             &show_dwarf_cmdlist);
25385
25386   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25387                            &dwarf_always_disassemble, _("\
25388 Set whether `info address' always disassembles DWARF expressions."), _("\
25389 Show whether `info address' always disassembles DWARF expressions."), _("\
25390 When enabled, DWARF expressions are always printed in an assembly-like\n\
25391 syntax.  When disabled, expressions will be printed in a more\n\
25392 conversational style, when possible."),
25393                            NULL,
25394                            show_dwarf_always_disassemble,
25395                            &set_dwarf_cmdlist,
25396                            &show_dwarf_cmdlist);
25397
25398   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25399 Set debugging of the DWARF reader."), _("\
25400 Show debugging of the DWARF reader."), _("\
25401 When enabled (non-zero), debugging messages are printed during DWARF\n\
25402 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25403 information.  A value greater than 1 provides more verbose information."),
25404                             NULL,
25405                             NULL,
25406                             &setdebuglist, &showdebuglist);
25407
25408   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25409 Set debugging of the DWARF DIE reader."), _("\
25410 Show debugging of the DWARF DIE reader."), _("\
25411 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25412 The value is the maximum depth to print."),
25413                              NULL,
25414                              NULL,
25415                              &setdebuglist, &showdebuglist);
25416
25417   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25418 Set debugging of the dwarf line reader."), _("\
25419 Show debugging of the dwarf line reader."), _("\
25420 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25421 A value of 1 (one) provides basic information.\n\
25422 A value greater than 1 provides more verbose information."),
25423                              NULL,
25424                              NULL,
25425                              &setdebuglist, &showdebuglist);
25426
25427   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25428 Set cross-checking of \"physname\" code against demangler."), _("\
25429 Show cross-checking of \"physname\" code against demangler."), _("\
25430 When enabled, GDB's internal \"physname\" code is checked against\n\
25431 the demangler."),
25432                            NULL, show_check_physname,
25433                            &setdebuglist, &showdebuglist);
25434
25435   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25436                            no_class, &use_deprecated_index_sections, _("\
25437 Set whether to use deprecated gdb_index sections."), _("\
25438 Show whether to use deprecated gdb_index sections."), _("\
25439 When enabled, deprecated .gdb_index sections are used anyway.\n\
25440 Normally they are ignored either because of a missing feature or\n\
25441 performance issue.\n\
25442 Warning: This option must be enabled before gdb reads the file."),
25443                            NULL,
25444                            NULL,
25445                            &setlist, &showlist);
25446
25447   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25448                                                         &dwarf2_locexpr_funcs);
25449   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25450                                                         &dwarf2_loclist_funcs);
25451
25452   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25453                                         &dwarf2_block_frame_base_locexpr_funcs);
25454   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25455                                         &dwarf2_block_frame_base_loclist_funcs);
25456
25457 #if GDB_SELF_TEST
25458   selftests::register_test ("dw2_expand_symtabs_matching",
25459                             selftests::dw2_expand_symtabs_matching::run_test);
25460 #endif
25461 }