Make index reading functions more modular
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "dwarf2read.h"
33 #include "dwarf-index-common.h"
34 #include "bfd.h"
35 #include "elf-bfd.h"
36 #include "symtab.h"
37 #include "gdbtypes.h"
38 #include "objfiles.h"
39 #include "dwarf2.h"
40 #include "buildsym.h"
41 #include "demangle.h"
42 #include "gdb-demangle.h"
43 #include "expression.h"
44 #include "filenames.h"  /* for DOSish file names */
45 #include "macrotab.h"
46 #include "language.h"
47 #include "complaints.h"
48 #include "bcache.h"
49 #include "dwarf2expr.h"
50 #include "dwarf2loc.h"
51 #include "cp-support.h"
52 #include "hashtab.h"
53 #include "command.h"
54 #include "gdbcmd.h"
55 #include "block.h"
56 #include "addrmap.h"
57 #include "typeprint.h"
58 #include "psympriv.h"
59 #include <sys/stat.h>
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "filestuff.h"
72 #include "build-id.h"
73 #include "namespace.h"
74 #include "common/gdb_unlinker.h"
75 #include "common/function-view.h"
76 #include "common/gdb_optional.h"
77 #include "common/underlying.h"
78 #include "common/byte-vector.h"
79 #include "common/hash_enum.h"
80 #include "filename-seen-cache.h"
81 #include "producer.h"
82 #include <fcntl.h>
83 #include <sys/types.h>
84 #include <algorithm>
85 #include <unordered_set>
86 #include <unordered_map>
87 #include "selftest.h"
88 #include <cmath>
89 #include <set>
90 #include <forward_list>
91 #include "rust-lang.h"
92 #include "common/pathstuff.h"
93
94 /* When == 1, print basic high level tracing messages.
95    When > 1, be more verbose.
96    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
97 static unsigned int dwarf_read_debug = 0;
98
99 /* When non-zero, dump DIEs after they are read in.  */
100 static unsigned int dwarf_die_debug = 0;
101
102 /* When non-zero, dump line number entries as they are read in.  */
103 static unsigned int dwarf_line_debug = 0;
104
105 /* When non-zero, cross-check physname against demangler.  */
106 static int check_physname = 0;
107
108 /* When non-zero, do not reject deprecated .gdb_index sections.  */
109 static int use_deprecated_index_sections = 0;
110
111 static const struct objfile_data *dwarf2_objfile_data_key;
112
113 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
114
115 static int dwarf2_locexpr_index;
116 static int dwarf2_loclist_index;
117 static int dwarf2_locexpr_block_index;
118 static int dwarf2_loclist_block_index;
119
120 /* An index into a (C++) symbol name component in a symbol name as
121    recorded in the mapped_index's symbol table.  For each C++ symbol
122    in the symbol table, we record one entry for the start of each
123    component in the symbol in a table of name components, and then
124    sort the table, in order to be able to binary search symbol names,
125    ignoring leading namespaces, both completion and regular look up.
126    For example, for symbol "A::B::C", we'll have an entry that points
127    to "A::B::C", another that points to "B::C", and another for "C".
128    Note that function symbols in GDB index have no parameter
129    information, just the function/method names.  You can convert a
130    name_component to a "const char *" using the
131    'mapped_index::symbol_name_at(offset_type)' method.  */
132
133 struct name_component
134 {
135   /* Offset in the symbol name where the component starts.  Stored as
136      a (32-bit) offset instead of a pointer to save memory and improve
137      locality on 64-bit architectures.  */
138   offset_type name_offset;
139
140   /* The symbol's index in the symbol and constant pool tables of a
141      mapped_index.  */
142   offset_type idx;
143 };
144
145 /* Base class containing bits shared by both .gdb_index and
146    .debug_name indexes.  */
147
148 struct mapped_index_base
149 {
150   mapped_index_base () = default;
151   DISABLE_COPY_AND_ASSIGN (mapped_index_base);
152
153   /* The name_component table (a sorted vector).  See name_component's
154      description above.  */
155   std::vector<name_component> name_components;
156
157   /* How NAME_COMPONENTS is sorted.  */
158   enum case_sensitivity name_components_casing;
159
160   /* Return the number of names in the symbol table.  */
161   virtual size_t symbol_name_count () const = 0;
162
163   /* Get the name of the symbol at IDX in the symbol table.  */
164   virtual const char *symbol_name_at (offset_type idx) const = 0;
165
166   /* Return whether the name at IDX in the symbol table should be
167      ignored.  */
168   virtual bool symbol_name_slot_invalid (offset_type idx) const
169   {
170     return false;
171   }
172
173   /* Build the symbol name component sorted vector, if we haven't
174      yet.  */
175   void build_name_components ();
176
177   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
178      possible matches for LN_NO_PARAMS in the name component
179      vector.  */
180   std::pair<std::vector<name_component>::const_iterator,
181             std::vector<name_component>::const_iterator>
182     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
183
184   /* Prevent deleting/destroying via a base class pointer.  */
185 protected:
186   ~mapped_index_base() = default;
187 };
188
189 /* A description of the mapped index.  The file format is described in
190    a comment by the code that writes the index.  */
191 struct mapped_index final : public mapped_index_base
192 {
193   /* A slot/bucket in the symbol table hash.  */
194   struct symbol_table_slot
195   {
196     const offset_type name;
197     const offset_type vec;
198   };
199
200   /* Index data format version.  */
201   int version = 0;
202
203   /* The address table data.  */
204   gdb::array_view<const gdb_byte> address_table;
205
206   /* The symbol table, implemented as a hash table.  */
207   gdb::array_view<symbol_table_slot> symbol_table;
208
209   /* A pointer to the constant pool.  */
210   const char *constant_pool = nullptr;
211
212   bool symbol_name_slot_invalid (offset_type idx) const override
213   {
214     const auto &bucket = this->symbol_table[idx];
215     return bucket.name == 0 && bucket.vec;
216   }
217
218   /* Convenience method to get at the name of the symbol at IDX in the
219      symbol table.  */
220   const char *symbol_name_at (offset_type idx) const override
221   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
222
223   size_t symbol_name_count () const override
224   { return this->symbol_table.size (); }
225 };
226
227 /* A description of the mapped .debug_names.
228    Uninitialized map has CU_COUNT 0.  */
229 struct mapped_debug_names final : public mapped_index_base
230 {
231   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
232   : dwarf2_per_objfile (dwarf2_per_objfile_)
233   {}
234
235   struct dwarf2_per_objfile *dwarf2_per_objfile;
236   bfd_endian dwarf5_byte_order;
237   bool dwarf5_is_dwarf64;
238   bool augmentation_is_gdb;
239   uint8_t offset_size;
240   uint32_t cu_count = 0;
241   uint32_t tu_count, bucket_count, name_count;
242   const gdb_byte *cu_table_reordered, *tu_table_reordered;
243   const uint32_t *bucket_table_reordered, *hash_table_reordered;
244   const gdb_byte *name_table_string_offs_reordered;
245   const gdb_byte *name_table_entry_offs_reordered;
246   const gdb_byte *entry_pool;
247
248   struct index_val
249   {
250     ULONGEST dwarf_tag;
251     struct attr
252     {
253       /* Attribute name DW_IDX_*.  */
254       ULONGEST dw_idx;
255
256       /* Attribute form DW_FORM_*.  */
257       ULONGEST form;
258
259       /* Value if FORM is DW_FORM_implicit_const.  */
260       LONGEST implicit_const;
261     };
262     std::vector<attr> attr_vec;
263   };
264
265   std::unordered_map<ULONGEST, index_val> abbrev_map;
266
267   const char *namei_to_name (uint32_t namei) const;
268
269   /* Implementation of the mapped_index_base virtual interface, for
270      the name_components cache.  */
271
272   const char *symbol_name_at (offset_type idx) const override
273   { return namei_to_name (idx); }
274
275   size_t symbol_name_count () const override
276   { return this->name_count; }
277 };
278
279 /* See dwarf2read.h.  */
280
281 dwarf2_per_objfile *
282 get_dwarf2_per_objfile (struct objfile *objfile)
283 {
284   return ((struct dwarf2_per_objfile *)
285           objfile_data (objfile, dwarf2_objfile_data_key));
286 }
287
288 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
289
290 void
291 set_dwarf2_per_objfile (struct objfile *objfile,
292                         struct dwarf2_per_objfile *dwarf2_per_objfile)
293 {
294   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
295   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
296 }
297
298 /* Default names of the debugging sections.  */
299
300 /* Note that if the debugging section has been compressed, it might
301    have a name like .zdebug_info.  */
302
303 static const struct dwarf2_debug_sections dwarf2_elf_names =
304 {
305   { ".debug_info", ".zdebug_info" },
306   { ".debug_abbrev", ".zdebug_abbrev" },
307   { ".debug_line", ".zdebug_line" },
308   { ".debug_loc", ".zdebug_loc" },
309   { ".debug_loclists", ".zdebug_loclists" },
310   { ".debug_macinfo", ".zdebug_macinfo" },
311   { ".debug_macro", ".zdebug_macro" },
312   { ".debug_str", ".zdebug_str" },
313   { ".debug_line_str", ".zdebug_line_str" },
314   { ".debug_ranges", ".zdebug_ranges" },
315   { ".debug_rnglists", ".zdebug_rnglists" },
316   { ".debug_types", ".zdebug_types" },
317   { ".debug_addr", ".zdebug_addr" },
318   { ".debug_frame", ".zdebug_frame" },
319   { ".eh_frame", NULL },
320   { ".gdb_index", ".zgdb_index" },
321   { ".debug_names", ".zdebug_names" },
322   { ".debug_aranges", ".zdebug_aranges" },
323   23
324 };
325
326 /* List of DWO/DWP sections.  */
327
328 static const struct dwop_section_names
329 {
330   struct dwarf2_section_names abbrev_dwo;
331   struct dwarf2_section_names info_dwo;
332   struct dwarf2_section_names line_dwo;
333   struct dwarf2_section_names loc_dwo;
334   struct dwarf2_section_names loclists_dwo;
335   struct dwarf2_section_names macinfo_dwo;
336   struct dwarf2_section_names macro_dwo;
337   struct dwarf2_section_names str_dwo;
338   struct dwarf2_section_names str_offsets_dwo;
339   struct dwarf2_section_names types_dwo;
340   struct dwarf2_section_names cu_index;
341   struct dwarf2_section_names tu_index;
342 }
343 dwop_section_names =
344 {
345   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
346   { ".debug_info.dwo", ".zdebug_info.dwo" },
347   { ".debug_line.dwo", ".zdebug_line.dwo" },
348   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
349   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
350   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
351   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
352   { ".debug_str.dwo", ".zdebug_str.dwo" },
353   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
354   { ".debug_types.dwo", ".zdebug_types.dwo" },
355   { ".debug_cu_index", ".zdebug_cu_index" },
356   { ".debug_tu_index", ".zdebug_tu_index" },
357 };
358
359 /* local data types */
360
361 /* The data in a compilation unit header, after target2host
362    translation, looks like this.  */
363 struct comp_unit_head
364 {
365   unsigned int length;
366   short version;
367   unsigned char addr_size;
368   unsigned char signed_addr_p;
369   sect_offset abbrev_sect_off;
370
371   /* Size of file offsets; either 4 or 8.  */
372   unsigned int offset_size;
373
374   /* Size of the length field; either 4 or 12.  */
375   unsigned int initial_length_size;
376
377   enum dwarf_unit_type unit_type;
378
379   /* Offset to the first byte of this compilation unit header in the
380      .debug_info section, for resolving relative reference dies.  */
381   sect_offset sect_off;
382
383   /* Offset to first die in this cu from the start of the cu.
384      This will be the first byte following the compilation unit header.  */
385   cu_offset first_die_cu_offset;
386
387   /* 64-bit signature of this type unit - it is valid only for
388      UNIT_TYPE DW_UT_type.  */
389   ULONGEST signature;
390
391   /* For types, offset in the type's DIE of the type defined by this TU.  */
392   cu_offset type_cu_offset_in_tu;
393 };
394
395 /* Type used for delaying computation of method physnames.
396    See comments for compute_delayed_physnames.  */
397 struct delayed_method_info
398 {
399   /* The type to which the method is attached, i.e., its parent class.  */
400   struct type *type;
401
402   /* The index of the method in the type's function fieldlists.  */
403   int fnfield_index;
404
405   /* The index of the method in the fieldlist.  */
406   int index;
407
408   /* The name of the DIE.  */
409   const char *name;
410
411   /*  The DIE associated with this method.  */
412   struct die_info *die;
413 };
414
415 /* Internal state when decoding a particular compilation unit.  */
416 struct dwarf2_cu
417 {
418   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
419   ~dwarf2_cu ();
420
421   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
422
423   /* The header of the compilation unit.  */
424   struct comp_unit_head header {};
425
426   /* Base address of this compilation unit.  */
427   CORE_ADDR base_address = 0;
428
429   /* Non-zero if base_address has been set.  */
430   int base_known = 0;
431
432   /* The language we are debugging.  */
433   enum language language = language_unknown;
434   const struct language_defn *language_defn = nullptr;
435
436   const char *producer = nullptr;
437
438   /* The symtab builder for this CU.  This is only non-NULL when full
439      symbols are being read.  */
440   std::unique_ptr<buildsym_compunit> builder;
441
442   /* The generic symbol table building routines have separate lists for
443      file scope symbols and all all other scopes (local scopes).  So
444      we need to select the right one to pass to add_symbol_to_list().
445      We do it by keeping a pointer to the correct list in list_in_scope.
446
447      FIXME: The original dwarf code just treated the file scope as the
448      first local scope, and all other local scopes as nested local
449      scopes, and worked fine.  Check to see if we really need to
450      distinguish these in buildsym.c.  */
451   struct pending **list_in_scope = nullptr;
452
453   /* Hash table holding all the loaded partial DIEs
454      with partial_die->offset.SECT_OFF as hash.  */
455   htab_t partial_dies = nullptr;
456
457   /* Storage for things with the same lifetime as this read-in compilation
458      unit, including partial DIEs.  */
459   auto_obstack comp_unit_obstack;
460
461   /* When multiple dwarf2_cu structures are living in memory, this field
462      chains them all together, so that they can be released efficiently.
463      We will probably also want a generation counter so that most-recently-used
464      compilation units are cached...  */
465   struct dwarf2_per_cu_data *read_in_chain = nullptr;
466
467   /* Backlink to our per_cu entry.  */
468   struct dwarf2_per_cu_data *per_cu;
469
470   /* How many compilation units ago was this CU last referenced?  */
471   int last_used = 0;
472
473   /* A hash table of DIE cu_offset for following references with
474      die_info->offset.sect_off as hash.  */
475   htab_t die_hash = nullptr;
476
477   /* Full DIEs if read in.  */
478   struct die_info *dies = nullptr;
479
480   /* A set of pointers to dwarf2_per_cu_data objects for compilation
481      units referenced by this one.  Only set during full symbol processing;
482      partial symbol tables do not have dependencies.  */
483   htab_t dependencies = nullptr;
484
485   /* Header data from the line table, during full symbol processing.  */
486   struct line_header *line_header = nullptr;
487   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
488      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
489      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
490      to the line header as long as this DIE is being processed.  See
491      process_die_scope.  */
492   die_info *line_header_die_owner = nullptr;
493
494   /* A list of methods which need to have physnames computed
495      after all type information has been read.  */
496   std::vector<delayed_method_info> method_list;
497
498   /* To be copied to symtab->call_site_htab.  */
499   htab_t call_site_htab = nullptr;
500
501   /* Non-NULL if this CU came from a DWO file.
502      There is an invariant here that is important to remember:
503      Except for attributes copied from the top level DIE in the "main"
504      (or "stub") file in preparation for reading the DWO file
505      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
506      Either there isn't a DWO file (in which case this is NULL and the point
507      is moot), or there is and either we're not going to read it (in which
508      case this is NULL) or there is and we are reading it (in which case this
509      is non-NULL).  */
510   struct dwo_unit *dwo_unit = nullptr;
511
512   /* The DW_AT_addr_base attribute if present, zero otherwise
513      (zero is a valid value though).
514      Note this value comes from the Fission stub CU/TU's DIE.  */
515   ULONGEST addr_base = 0;
516
517   /* The DW_AT_ranges_base attribute if present, zero otherwise
518      (zero is a valid value though).
519      Note this value comes from the Fission stub CU/TU's DIE.
520      Also note that the value is zero in the non-DWO case so this value can
521      be used without needing to know whether DWO files are in use or not.
522      N.B. This does not apply to DW_AT_ranges appearing in
523      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
524      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
525      DW_AT_ranges_base *would* have to be applied, and we'd have to care
526      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
527   ULONGEST ranges_base = 0;
528
529   /* When reading debug info generated by older versions of rustc, we
530      have to rewrite some union types to be struct types with a
531      variant part.  This rewriting must be done after the CU is fully
532      read in, because otherwise at the point of rewriting some struct
533      type might not have been fully processed.  So, we keep a list of
534      all such types here and process them after expansion.  */
535   std::vector<struct type *> rust_unions;
536
537   /* Mark used when releasing cached dies.  */
538   unsigned int mark : 1;
539
540   /* This CU references .debug_loc.  See the symtab->locations_valid field.
541      This test is imperfect as there may exist optimized debug code not using
542      any location list and still facing inlining issues if handled as
543      unoptimized code.  For a future better test see GCC PR other/32998.  */
544   unsigned int has_loclist : 1;
545
546   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
547      if all the producer_is_* fields are valid.  This information is cached
548      because profiling CU expansion showed excessive time spent in
549      producer_is_gxx_lt_4_6.  */
550   unsigned int checked_producer : 1;
551   unsigned int producer_is_gxx_lt_4_6 : 1;
552   unsigned int producer_is_gcc_lt_4_3 : 1;
553   unsigned int producer_is_icc_lt_14 : 1;
554
555   /* When set, the file that we're processing is known to have
556      debugging info for C++ namespaces.  GCC 3.3.x did not produce
557      this information, but later versions do.  */
558
559   unsigned int processing_has_namespace_info : 1;
560
561   struct partial_die_info *find_partial_die (sect_offset sect_off);
562 };
563
564 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
565    This includes type_unit_group and quick_file_names.  */
566
567 struct stmt_list_hash
568 {
569   /* The DWO unit this table is from or NULL if there is none.  */
570   struct dwo_unit *dwo_unit;
571
572   /* Offset in .debug_line or .debug_line.dwo.  */
573   sect_offset line_sect_off;
574 };
575
576 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
577    an object of this type.  */
578
579 struct type_unit_group
580 {
581   /* dwarf2read.c's main "handle" on a TU symtab.
582      To simplify things we create an artificial CU that "includes" all the
583      type units using this stmt_list so that the rest of the code still has
584      a "per_cu" handle on the symtab.
585      This PER_CU is recognized by having no section.  */
586 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
587   struct dwarf2_per_cu_data per_cu;
588
589   /* The TUs that share this DW_AT_stmt_list entry.
590      This is added to while parsing type units to build partial symtabs,
591      and is deleted afterwards and not used again.  */
592   VEC (sig_type_ptr) *tus;
593
594   /* The compunit symtab.
595      Type units in a group needn't all be defined in the same source file,
596      so we create an essentially anonymous symtab as the compunit symtab.  */
597   struct compunit_symtab *compunit_symtab;
598
599   /* The data used to construct the hash key.  */
600   struct stmt_list_hash hash;
601
602   /* The number of symtabs from the line header.
603      The value here must match line_header.num_file_names.  */
604   unsigned int num_symtabs;
605
606   /* The symbol tables for this TU (obtained from the files listed in
607      DW_AT_stmt_list).
608      WARNING: The order of entries here must match the order of entries
609      in the line header.  After the first TU using this type_unit_group, the
610      line header for the subsequent TUs is recreated from this.  This is done
611      because we need to use the same symtabs for each TU using the same
612      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
613      there's no guarantee the line header doesn't have duplicate entries.  */
614   struct symtab **symtabs;
615 };
616
617 /* These sections are what may appear in a (real or virtual) DWO file.  */
618
619 struct dwo_sections
620 {
621   struct dwarf2_section_info abbrev;
622   struct dwarf2_section_info line;
623   struct dwarf2_section_info loc;
624   struct dwarf2_section_info loclists;
625   struct dwarf2_section_info macinfo;
626   struct dwarf2_section_info macro;
627   struct dwarf2_section_info str;
628   struct dwarf2_section_info str_offsets;
629   /* In the case of a virtual DWO file, these two are unused.  */
630   struct dwarf2_section_info info;
631   VEC (dwarf2_section_info_def) *types;
632 };
633
634 /* CUs/TUs in DWP/DWO files.  */
635
636 struct dwo_unit
637 {
638   /* Backlink to the containing struct dwo_file.  */
639   struct dwo_file *dwo_file;
640
641   /* The "id" that distinguishes this CU/TU.
642      .debug_info calls this "dwo_id", .debug_types calls this "signature".
643      Since signatures came first, we stick with it for consistency.  */
644   ULONGEST signature;
645
646   /* The section this CU/TU lives in, in the DWO file.  */
647   struct dwarf2_section_info *section;
648
649   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
650   sect_offset sect_off;
651   unsigned int length;
652
653   /* For types, offset in the type's DIE of the type defined by this TU.  */
654   cu_offset type_offset_in_tu;
655 };
656
657 /* include/dwarf2.h defines the DWP section codes.
658    It defines a max value but it doesn't define a min value, which we
659    use for error checking, so provide one.  */
660
661 enum dwp_v2_section_ids
662 {
663   DW_SECT_MIN = 1
664 };
665
666 /* Data for one DWO file.
667
668    This includes virtual DWO files (a virtual DWO file is a DWO file as it
669    appears in a DWP file).  DWP files don't really have DWO files per se -
670    comdat folding of types "loses" the DWO file they came from, and from
671    a high level view DWP files appear to contain a mass of random types.
672    However, to maintain consistency with the non-DWP case we pretend DWP
673    files contain virtual DWO files, and we assign each TU with one virtual
674    DWO file (generally based on the line and abbrev section offsets -
675    a heuristic that seems to work in practice).  */
676
677 struct dwo_file
678 {
679   /* The DW_AT_GNU_dwo_name attribute.
680      For virtual DWO files the name is constructed from the section offsets
681      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
682      from related CU+TUs.  */
683   const char *dwo_name;
684
685   /* The DW_AT_comp_dir attribute.  */
686   const char *comp_dir;
687
688   /* The bfd, when the file is open.  Otherwise this is NULL.
689      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
690   bfd *dbfd;
691
692   /* The sections that make up this DWO file.
693      Remember that for virtual DWO files in DWP V2, these are virtual
694      sections (for lack of a better name).  */
695   struct dwo_sections sections;
696
697   /* The CUs in the file.
698      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
699      an extension to handle LLVM's Link Time Optimization output (where
700      multiple source files may be compiled into a single object/dwo pair). */
701   htab_t cus;
702
703   /* Table of TUs in the file.
704      Each element is a struct dwo_unit.  */
705   htab_t tus;
706 };
707
708 /* These sections are what may appear in a DWP file.  */
709
710 struct dwp_sections
711 {
712   /* These are used by both DWP version 1 and 2.  */
713   struct dwarf2_section_info str;
714   struct dwarf2_section_info cu_index;
715   struct dwarf2_section_info tu_index;
716
717   /* These are only used by DWP version 2 files.
718      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
719      sections are referenced by section number, and are not recorded here.
720      In DWP version 2 there is at most one copy of all these sections, each
721      section being (effectively) comprised of the concatenation of all of the
722      individual sections that exist in the version 1 format.
723      To keep the code simple we treat each of these concatenated pieces as a
724      section itself (a virtual section?).  */
725   struct dwarf2_section_info abbrev;
726   struct dwarf2_section_info info;
727   struct dwarf2_section_info line;
728   struct dwarf2_section_info loc;
729   struct dwarf2_section_info macinfo;
730   struct dwarf2_section_info macro;
731   struct dwarf2_section_info str_offsets;
732   struct dwarf2_section_info types;
733 };
734
735 /* These sections are what may appear in a virtual DWO file in DWP version 1.
736    A virtual DWO file is a DWO file as it appears in a DWP file.  */
737
738 struct virtual_v1_dwo_sections
739 {
740   struct dwarf2_section_info abbrev;
741   struct dwarf2_section_info line;
742   struct dwarf2_section_info loc;
743   struct dwarf2_section_info macinfo;
744   struct dwarf2_section_info macro;
745   struct dwarf2_section_info str_offsets;
746   /* Each DWP hash table entry records one CU or one TU.
747      That is recorded here, and copied to dwo_unit.section.  */
748   struct dwarf2_section_info info_or_types;
749 };
750
751 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
752    In version 2, the sections of the DWO files are concatenated together
753    and stored in one section of that name.  Thus each ELF section contains
754    several "virtual" sections.  */
755
756 struct virtual_v2_dwo_sections
757 {
758   bfd_size_type abbrev_offset;
759   bfd_size_type abbrev_size;
760
761   bfd_size_type line_offset;
762   bfd_size_type line_size;
763
764   bfd_size_type loc_offset;
765   bfd_size_type loc_size;
766
767   bfd_size_type macinfo_offset;
768   bfd_size_type macinfo_size;
769
770   bfd_size_type macro_offset;
771   bfd_size_type macro_size;
772
773   bfd_size_type str_offsets_offset;
774   bfd_size_type str_offsets_size;
775
776   /* Each DWP hash table entry records one CU or one TU.
777      That is recorded here, and copied to dwo_unit.section.  */
778   bfd_size_type info_or_types_offset;
779   bfd_size_type info_or_types_size;
780 };
781
782 /* Contents of DWP hash tables.  */
783
784 struct dwp_hash_table
785 {
786   uint32_t version, nr_columns;
787   uint32_t nr_units, nr_slots;
788   const gdb_byte *hash_table, *unit_table;
789   union
790   {
791     struct
792     {
793       const gdb_byte *indices;
794     } v1;
795     struct
796     {
797       /* This is indexed by column number and gives the id of the section
798          in that column.  */
799 #define MAX_NR_V2_DWO_SECTIONS \
800   (1 /* .debug_info or .debug_types */ \
801    + 1 /* .debug_abbrev */ \
802    + 1 /* .debug_line */ \
803    + 1 /* .debug_loc */ \
804    + 1 /* .debug_str_offsets */ \
805    + 1 /* .debug_macro or .debug_macinfo */)
806       int section_ids[MAX_NR_V2_DWO_SECTIONS];
807       const gdb_byte *offsets;
808       const gdb_byte *sizes;
809     } v2;
810   } section_pool;
811 };
812
813 /* Data for one DWP file.  */
814
815 struct dwp_file
816 {
817   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
818     : name (name_),
819       dbfd (std::move (abfd))
820   {
821   }
822
823   /* Name of the file.  */
824   const char *name;
825
826   /* File format version.  */
827   int version = 0;
828
829   /* The bfd.  */
830   gdb_bfd_ref_ptr dbfd;
831
832   /* Section info for this file.  */
833   struct dwp_sections sections {};
834
835   /* Table of CUs in the file.  */
836   const struct dwp_hash_table *cus = nullptr;
837
838   /* Table of TUs in the file.  */
839   const struct dwp_hash_table *tus = nullptr;
840
841   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
842   htab_t loaded_cus {};
843   htab_t loaded_tus {};
844
845   /* Table to map ELF section numbers to their sections.
846      This is only needed for the DWP V1 file format.  */
847   unsigned int num_sections = 0;
848   asection **elf_sections = nullptr;
849 };
850
851 /* This represents a '.dwz' file.  */
852
853 struct dwz_file
854 {
855   dwz_file (gdb_bfd_ref_ptr &&bfd)
856     : dwz_bfd (std::move (bfd))
857   {
858   }
859
860   /* A dwz file can only contain a few sections.  */
861   struct dwarf2_section_info abbrev {};
862   struct dwarf2_section_info info {};
863   struct dwarf2_section_info str {};
864   struct dwarf2_section_info line {};
865   struct dwarf2_section_info macro {};
866   struct dwarf2_section_info gdb_index {};
867   struct dwarf2_section_info debug_names {};
868
869   /* The dwz's BFD.  */
870   gdb_bfd_ref_ptr dwz_bfd;
871 };
872
873 /* Struct used to pass misc. parameters to read_die_and_children, et
874    al.  which are used for both .debug_info and .debug_types dies.
875    All parameters here are unchanging for the life of the call.  This
876    struct exists to abstract away the constant parameters of die reading.  */
877
878 struct die_reader_specs
879 {
880   /* The bfd of die_section.  */
881   bfd* abfd;
882
883   /* The CU of the DIE we are parsing.  */
884   struct dwarf2_cu *cu;
885
886   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
887   struct dwo_file *dwo_file;
888
889   /* The section the die comes from.
890      This is either .debug_info or .debug_types, or the .dwo variants.  */
891   struct dwarf2_section_info *die_section;
892
893   /* die_section->buffer.  */
894   const gdb_byte *buffer;
895
896   /* The end of the buffer.  */
897   const gdb_byte *buffer_end;
898
899   /* The value of the DW_AT_comp_dir attribute.  */
900   const char *comp_dir;
901
902   /* The abbreviation table to use when reading the DIEs.  */
903   struct abbrev_table *abbrev_table;
904 };
905
906 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
907 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
908                                       const gdb_byte *info_ptr,
909                                       struct die_info *comp_unit_die,
910                                       int has_children,
911                                       void *data);
912
913 /* A 1-based directory index.  This is a strong typedef to prevent
914    accidentally using a directory index as a 0-based index into an
915    array/vector.  */
916 enum class dir_index : unsigned int {};
917
918 /* Likewise, a 1-based file name index.  */
919 enum class file_name_index : unsigned int {};
920
921 struct file_entry
922 {
923   file_entry () = default;
924
925   file_entry (const char *name_, dir_index d_index_,
926               unsigned int mod_time_, unsigned int length_)
927     : name (name_),
928       d_index (d_index_),
929       mod_time (mod_time_),
930       length (length_)
931   {}
932
933   /* Return the include directory at D_INDEX stored in LH.  Returns
934      NULL if D_INDEX is out of bounds.  */
935   const char *include_dir (const line_header *lh) const;
936
937   /* The file name.  Note this is an observing pointer.  The memory is
938      owned by debug_line_buffer.  */
939   const char *name {};
940
941   /* The directory index (1-based).  */
942   dir_index d_index {};
943
944   unsigned int mod_time {};
945
946   unsigned int length {};
947
948   /* True if referenced by the Line Number Program.  */
949   bool included_p {};
950
951   /* The associated symbol table, if any.  */
952   struct symtab *symtab {};
953 };
954
955 /* The line number information for a compilation unit (found in the
956    .debug_line section) begins with a "statement program header",
957    which contains the following information.  */
958 struct line_header
959 {
960   line_header ()
961     : offset_in_dwz {}
962   {}
963
964   /* Add an entry to the include directory table.  */
965   void add_include_dir (const char *include_dir);
966
967   /* Add an entry to the file name table.  */
968   void add_file_name (const char *name, dir_index d_index,
969                       unsigned int mod_time, unsigned int length);
970
971   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
972      is out of bounds.  */
973   const char *include_dir_at (dir_index index) const
974   {
975     /* Convert directory index number (1-based) to vector index
976        (0-based).  */
977     size_t vec_index = to_underlying (index) - 1;
978
979     if (vec_index >= include_dirs.size ())
980       return NULL;
981     return include_dirs[vec_index];
982   }
983
984   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
985      is out of bounds.  */
986   file_entry *file_name_at (file_name_index index)
987   {
988     /* Convert file name index number (1-based) to vector index
989        (0-based).  */
990     size_t vec_index = to_underlying (index) - 1;
991
992     if (vec_index >= file_names.size ())
993       return NULL;
994     return &file_names[vec_index];
995   }
996
997   /* Const version of the above.  */
998   const file_entry *file_name_at (unsigned int index) const
999   {
1000     if (index >= file_names.size ())
1001       return NULL;
1002     return &file_names[index];
1003   }
1004
1005   /* Offset of line number information in .debug_line section.  */
1006   sect_offset sect_off {};
1007
1008   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1009   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1010
1011   unsigned int total_length {};
1012   unsigned short version {};
1013   unsigned int header_length {};
1014   unsigned char minimum_instruction_length {};
1015   unsigned char maximum_ops_per_instruction {};
1016   unsigned char default_is_stmt {};
1017   int line_base {};
1018   unsigned char line_range {};
1019   unsigned char opcode_base {};
1020
1021   /* standard_opcode_lengths[i] is the number of operands for the
1022      standard opcode whose value is i.  This means that
1023      standard_opcode_lengths[0] is unused, and the last meaningful
1024      element is standard_opcode_lengths[opcode_base - 1].  */
1025   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1026
1027   /* The include_directories table.  Note these are observing
1028      pointers.  The memory is owned by debug_line_buffer.  */
1029   std::vector<const char *> include_dirs;
1030
1031   /* The file_names table.  */
1032   std::vector<file_entry> file_names;
1033
1034   /* The start and end of the statement program following this
1035      header.  These point into dwarf2_per_objfile->line_buffer.  */
1036   const gdb_byte *statement_program_start {}, *statement_program_end {};
1037 };
1038
1039 typedef std::unique_ptr<line_header> line_header_up;
1040
1041 const char *
1042 file_entry::include_dir (const line_header *lh) const
1043 {
1044   return lh->include_dir_at (d_index);
1045 }
1046
1047 /* When we construct a partial symbol table entry we only
1048    need this much information.  */
1049 struct partial_die_info : public allocate_on_obstack
1050   {
1051     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1052
1053     /* Disable assign but still keep copy ctor, which is needed
1054        load_partial_dies.   */
1055     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1056
1057     /* Adjust the partial die before generating a symbol for it.  This
1058        function may set the is_external flag or change the DIE's
1059        name.  */
1060     void fixup (struct dwarf2_cu *cu);
1061
1062     /* Read a minimal amount of information into the minimal die
1063        structure.  */
1064     const gdb_byte *read (const struct die_reader_specs *reader,
1065                           const struct abbrev_info &abbrev,
1066                           const gdb_byte *info_ptr);
1067
1068     /* Offset of this DIE.  */
1069     const sect_offset sect_off;
1070
1071     /* DWARF-2 tag for this DIE.  */
1072     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1073
1074     /* Assorted flags describing the data found in this DIE.  */
1075     const unsigned int has_children : 1;
1076
1077     unsigned int is_external : 1;
1078     unsigned int is_declaration : 1;
1079     unsigned int has_type : 1;
1080     unsigned int has_specification : 1;
1081     unsigned int has_pc_info : 1;
1082     unsigned int may_be_inlined : 1;
1083
1084     /* This DIE has been marked DW_AT_main_subprogram.  */
1085     unsigned int main_subprogram : 1;
1086
1087     /* Flag set if the SCOPE field of this structure has been
1088        computed.  */
1089     unsigned int scope_set : 1;
1090
1091     /* Flag set if the DIE has a byte_size attribute.  */
1092     unsigned int has_byte_size : 1;
1093
1094     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1095     unsigned int has_const_value : 1;
1096
1097     /* Flag set if any of the DIE's children are template arguments.  */
1098     unsigned int has_template_arguments : 1;
1099
1100     /* Flag set if fixup has been called on this die.  */
1101     unsigned int fixup_called : 1;
1102
1103     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1104     unsigned int is_dwz : 1;
1105
1106     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1107     unsigned int spec_is_dwz : 1;
1108
1109     /* The name of this DIE.  Normally the value of DW_AT_name, but
1110        sometimes a default name for unnamed DIEs.  */
1111     const char *name = nullptr;
1112
1113     /* The linkage name, if present.  */
1114     const char *linkage_name = nullptr;
1115
1116     /* The scope to prepend to our children.  This is generally
1117        allocated on the comp_unit_obstack, so will disappear
1118        when this compilation unit leaves the cache.  */
1119     const char *scope = nullptr;
1120
1121     /* Some data associated with the partial DIE.  The tag determines
1122        which field is live.  */
1123     union
1124     {
1125       /* The location description associated with this DIE, if any.  */
1126       struct dwarf_block *locdesc;
1127       /* The offset of an import, for DW_TAG_imported_unit.  */
1128       sect_offset sect_off;
1129     } d {};
1130
1131     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1132     CORE_ADDR lowpc = 0;
1133     CORE_ADDR highpc = 0;
1134
1135     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1136        DW_AT_sibling, if any.  */
1137     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1138        could return DW_AT_sibling values to its caller load_partial_dies.  */
1139     const gdb_byte *sibling = nullptr;
1140
1141     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1142        DW_AT_specification (or DW_AT_abstract_origin or
1143        DW_AT_extension).  */
1144     sect_offset spec_offset {};
1145
1146     /* Pointers to this DIE's parent, first child, and next sibling,
1147        if any.  */
1148     struct partial_die_info *die_parent = nullptr;
1149     struct partial_die_info *die_child = nullptr;
1150     struct partial_die_info *die_sibling = nullptr;
1151
1152     friend struct partial_die_info *
1153     dwarf2_cu::find_partial_die (sect_offset sect_off);
1154
1155   private:
1156     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1157     partial_die_info (sect_offset sect_off)
1158       : partial_die_info (sect_off, DW_TAG_padding, 0)
1159     {
1160     }
1161
1162     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1163                       int has_children_)
1164       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1165     {
1166       is_external = 0;
1167       is_declaration = 0;
1168       has_type = 0;
1169       has_specification = 0;
1170       has_pc_info = 0;
1171       may_be_inlined = 0;
1172       main_subprogram = 0;
1173       scope_set = 0;
1174       has_byte_size = 0;
1175       has_const_value = 0;
1176       has_template_arguments = 0;
1177       fixup_called = 0;
1178       is_dwz = 0;
1179       spec_is_dwz = 0;
1180     }
1181   };
1182
1183 /* This data structure holds the information of an abbrev.  */
1184 struct abbrev_info
1185   {
1186     unsigned int number;        /* number identifying abbrev */
1187     enum dwarf_tag tag;         /* dwarf tag */
1188     unsigned short has_children;                /* boolean */
1189     unsigned short num_attrs;   /* number of attributes */
1190     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1191     struct abbrev_info *next;   /* next in chain */
1192   };
1193
1194 struct attr_abbrev
1195   {
1196     ENUM_BITFIELD(dwarf_attribute) name : 16;
1197     ENUM_BITFIELD(dwarf_form) form : 16;
1198
1199     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1200     LONGEST implicit_const;
1201   };
1202
1203 /* Size of abbrev_table.abbrev_hash_table.  */
1204 #define ABBREV_HASH_SIZE 121
1205
1206 /* Top level data structure to contain an abbreviation table.  */
1207
1208 struct abbrev_table
1209 {
1210   explicit abbrev_table (sect_offset off)
1211     : sect_off (off)
1212   {
1213     m_abbrevs =
1214       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1215     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1216   }
1217
1218   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1219
1220   /* Allocate space for a struct abbrev_info object in
1221      ABBREV_TABLE.  */
1222   struct abbrev_info *alloc_abbrev ();
1223
1224   /* Add an abbreviation to the table.  */
1225   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1226
1227   /* Look up an abbrev in the table.
1228      Returns NULL if the abbrev is not found.  */
1229
1230   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1231
1232
1233   /* Where the abbrev table came from.
1234      This is used as a sanity check when the table is used.  */
1235   const sect_offset sect_off;
1236
1237   /* Storage for the abbrev table.  */
1238   auto_obstack abbrev_obstack;
1239
1240 private:
1241
1242   /* Hash table of abbrevs.
1243      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1244      It could be statically allocated, but the previous code didn't so we
1245      don't either.  */
1246   struct abbrev_info **m_abbrevs;
1247 };
1248
1249 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1250
1251 /* Attributes have a name and a value.  */
1252 struct attribute
1253   {
1254     ENUM_BITFIELD(dwarf_attribute) name : 16;
1255     ENUM_BITFIELD(dwarf_form) form : 15;
1256
1257     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1258        field should be in u.str (existing only for DW_STRING) but it is kept
1259        here for better struct attribute alignment.  */
1260     unsigned int string_is_canonical : 1;
1261
1262     union
1263       {
1264         const char *str;
1265         struct dwarf_block *blk;
1266         ULONGEST unsnd;
1267         LONGEST snd;
1268         CORE_ADDR addr;
1269         ULONGEST signature;
1270       }
1271     u;
1272   };
1273
1274 /* This data structure holds a complete die structure.  */
1275 struct die_info
1276   {
1277     /* DWARF-2 tag for this DIE.  */
1278     ENUM_BITFIELD(dwarf_tag) tag : 16;
1279
1280     /* Number of attributes */
1281     unsigned char num_attrs;
1282
1283     /* True if we're presently building the full type name for the
1284        type derived from this DIE.  */
1285     unsigned char building_fullname : 1;
1286
1287     /* True if this die is in process.  PR 16581.  */
1288     unsigned char in_process : 1;
1289
1290     /* Abbrev number */
1291     unsigned int abbrev;
1292
1293     /* Offset in .debug_info or .debug_types section.  */
1294     sect_offset sect_off;
1295
1296     /* The dies in a compilation unit form an n-ary tree.  PARENT
1297        points to this die's parent; CHILD points to the first child of
1298        this node; and all the children of a given node are chained
1299        together via their SIBLING fields.  */
1300     struct die_info *child;     /* Its first child, if any.  */
1301     struct die_info *sibling;   /* Its next sibling, if any.  */
1302     struct die_info *parent;    /* Its parent, if any.  */
1303
1304     /* An array of attributes, with NUM_ATTRS elements.  There may be
1305        zero, but it's not common and zero-sized arrays are not
1306        sufficiently portable C.  */
1307     struct attribute attrs[1];
1308   };
1309
1310 /* Get at parts of an attribute structure.  */
1311
1312 #define DW_STRING(attr)    ((attr)->u.str)
1313 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1314 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1315 #define DW_BLOCK(attr)     ((attr)->u.blk)
1316 #define DW_SND(attr)       ((attr)->u.snd)
1317 #define DW_ADDR(attr)      ((attr)->u.addr)
1318 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1319
1320 /* Blocks are a bunch of untyped bytes.  */
1321 struct dwarf_block
1322   {
1323     size_t size;
1324
1325     /* Valid only if SIZE is not zero.  */
1326     const gdb_byte *data;
1327   };
1328
1329 #ifndef ATTR_ALLOC_CHUNK
1330 #define ATTR_ALLOC_CHUNK 4
1331 #endif
1332
1333 /* Allocate fields for structs, unions and enums in this size.  */
1334 #ifndef DW_FIELD_ALLOC_CHUNK
1335 #define DW_FIELD_ALLOC_CHUNK 4
1336 #endif
1337
1338 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1339    but this would require a corresponding change in unpack_field_as_long
1340    and friends.  */
1341 static int bits_per_byte = 8;
1342
1343 /* When reading a variant or variant part, we track a bit more
1344    information about the field, and store it in an object of this
1345    type.  */
1346
1347 struct variant_field
1348 {
1349   /* If we see a DW_TAG_variant, then this will be the discriminant
1350      value.  */
1351   ULONGEST discriminant_value;
1352   /* If we see a DW_TAG_variant, then this will be set if this is the
1353      default branch.  */
1354   bool default_branch;
1355   /* While reading a DW_TAG_variant_part, this will be set if this
1356      field is the discriminant.  */
1357   bool is_discriminant;
1358 };
1359
1360 struct nextfield
1361 {
1362   int accessibility = 0;
1363   int virtuality = 0;
1364   /* Extra information to describe a variant or variant part.  */
1365   struct variant_field variant {};
1366   struct field field {};
1367 };
1368
1369 struct fnfieldlist
1370 {
1371   const char *name = nullptr;
1372   std::vector<struct fn_field> fnfields;
1373 };
1374
1375 /* The routines that read and process dies for a C struct or C++ class
1376    pass lists of data member fields and lists of member function fields
1377    in an instance of a field_info structure, as defined below.  */
1378 struct field_info
1379   {
1380     /* List of data member and baseclasses fields.  */
1381     std::vector<struct nextfield> fields;
1382     std::vector<struct nextfield> baseclasses;
1383
1384     /* Number of fields (including baseclasses).  */
1385     int nfields = 0;
1386
1387     /* Set if the accesibility of one of the fields is not public.  */
1388     int non_public_fields = 0;
1389
1390     /* Member function fieldlist array, contains name of possibly overloaded
1391        member function, number of overloaded member functions and a pointer
1392        to the head of the member function field chain.  */
1393     std::vector<struct fnfieldlist> fnfieldlists;
1394
1395     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1396        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1397     std::vector<struct decl_field> typedef_field_list;
1398
1399     /* Nested types defined by this class and the number of elements in this
1400        list.  */
1401     std::vector<struct decl_field> nested_types_list;
1402   };
1403
1404 /* One item on the queue of compilation units to read in full symbols
1405    for.  */
1406 struct dwarf2_queue_item
1407 {
1408   struct dwarf2_per_cu_data *per_cu;
1409   enum language pretend_language;
1410   struct dwarf2_queue_item *next;
1411 };
1412
1413 /* The current queue.  */
1414 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1415
1416 /* Loaded secondary compilation units are kept in memory until they
1417    have not been referenced for the processing of this many
1418    compilation units.  Set this to zero to disable caching.  Cache
1419    sizes of up to at least twenty will improve startup time for
1420    typical inter-CU-reference binaries, at an obvious memory cost.  */
1421 static int dwarf_max_cache_age = 5;
1422 static void
1423 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1424                           struct cmd_list_element *c, const char *value)
1425 {
1426   fprintf_filtered (file, _("The upper bound on the age of cached "
1427                             "DWARF compilation units is %s.\n"),
1428                     value);
1429 }
1430 \f
1431 /* local function prototypes */
1432
1433 static const char *get_section_name (const struct dwarf2_section_info *);
1434
1435 static const char *get_section_file_name (const struct dwarf2_section_info *);
1436
1437 static void dwarf2_find_base_address (struct die_info *die,
1438                                       struct dwarf2_cu *cu);
1439
1440 static struct partial_symtab *create_partial_symtab
1441   (struct dwarf2_per_cu_data *per_cu, const char *name);
1442
1443 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1444                                         const gdb_byte *info_ptr,
1445                                         struct die_info *type_unit_die,
1446                                         int has_children, void *data);
1447
1448 static void dwarf2_build_psymtabs_hard
1449   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1450
1451 static void scan_partial_symbols (struct partial_die_info *,
1452                                   CORE_ADDR *, CORE_ADDR *,
1453                                   int, struct dwarf2_cu *);
1454
1455 static void add_partial_symbol (struct partial_die_info *,
1456                                 struct dwarf2_cu *);
1457
1458 static void add_partial_namespace (struct partial_die_info *pdi,
1459                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1460                                    int set_addrmap, struct dwarf2_cu *cu);
1461
1462 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1463                                 CORE_ADDR *highpc, int set_addrmap,
1464                                 struct dwarf2_cu *cu);
1465
1466 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1467                                      struct dwarf2_cu *cu);
1468
1469 static void add_partial_subprogram (struct partial_die_info *pdi,
1470                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1471                                     int need_pc, struct dwarf2_cu *cu);
1472
1473 static void dwarf2_read_symtab (struct partial_symtab *,
1474                                 struct objfile *);
1475
1476 static void psymtab_to_symtab_1 (struct partial_symtab *);
1477
1478 static abbrev_table_up abbrev_table_read_table
1479   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1480    sect_offset);
1481
1482 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1483
1484 static struct partial_die_info *load_partial_dies
1485   (const struct die_reader_specs *, const gdb_byte *, int);
1486
1487 static struct partial_die_info *find_partial_die (sect_offset, int,
1488                                                   struct dwarf2_cu *);
1489
1490 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1491                                        struct attribute *, struct attr_abbrev *,
1492                                        const gdb_byte *);
1493
1494 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1495
1496 static int read_1_signed_byte (bfd *, const gdb_byte *);
1497
1498 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1499
1500 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1501
1502 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1503
1504 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1505                                unsigned int *);
1506
1507 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1508
1509 static LONGEST read_checked_initial_length_and_offset
1510   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1511    unsigned int *, unsigned int *);
1512
1513 static LONGEST read_offset (bfd *, const gdb_byte *,
1514                             const struct comp_unit_head *,
1515                             unsigned int *);
1516
1517 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1518
1519 static sect_offset read_abbrev_offset
1520   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1521    struct dwarf2_section_info *, sect_offset);
1522
1523 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1524
1525 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1526
1527 static const char *read_indirect_string
1528   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1529    const struct comp_unit_head *, unsigned int *);
1530
1531 static const char *read_indirect_line_string
1532   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1533    const struct comp_unit_head *, unsigned int *);
1534
1535 static const char *read_indirect_string_at_offset
1536   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1537    LONGEST str_offset);
1538
1539 static const char *read_indirect_string_from_dwz
1540   (struct objfile *objfile, struct dwz_file *, LONGEST);
1541
1542 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1543
1544 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1545                                               const gdb_byte *,
1546                                               unsigned int *);
1547
1548 static const char *read_str_index (const struct die_reader_specs *reader,
1549                                    ULONGEST str_index);
1550
1551 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1552
1553 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1554                                       struct dwarf2_cu *);
1555
1556 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1557                                                 unsigned int);
1558
1559 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1560                                        struct dwarf2_cu *cu);
1561
1562 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1563                                struct dwarf2_cu *cu);
1564
1565 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1566
1567 static struct die_info *die_specification (struct die_info *die,
1568                                            struct dwarf2_cu **);
1569
1570 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1571                                                 struct dwarf2_cu *cu);
1572
1573 static void dwarf_decode_lines (struct line_header *, const char *,
1574                                 struct dwarf2_cu *, struct partial_symtab *,
1575                                 CORE_ADDR, int decode_mapping);
1576
1577 static void dwarf2_start_subfile (struct dwarf2_cu *, const char *,
1578                                   const char *);
1579
1580 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1581                                                     const char *, const char *,
1582                                                     CORE_ADDR);
1583
1584 static struct symbol *new_symbol (struct die_info *, struct type *,
1585                                   struct dwarf2_cu *, struct symbol * = NULL);
1586
1587 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1588                                 struct dwarf2_cu *);
1589
1590 static void dwarf2_const_value_attr (const struct attribute *attr,
1591                                      struct type *type,
1592                                      const char *name,
1593                                      struct obstack *obstack,
1594                                      struct dwarf2_cu *cu, LONGEST *value,
1595                                      const gdb_byte **bytes,
1596                                      struct dwarf2_locexpr_baton **baton);
1597
1598 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1599
1600 static int need_gnat_info (struct dwarf2_cu *);
1601
1602 static struct type *die_descriptive_type (struct die_info *,
1603                                           struct dwarf2_cu *);
1604
1605 static void set_descriptive_type (struct type *, struct die_info *,
1606                                   struct dwarf2_cu *);
1607
1608 static struct type *die_containing_type (struct die_info *,
1609                                          struct dwarf2_cu *);
1610
1611 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1612                                      struct dwarf2_cu *);
1613
1614 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1615
1616 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1617
1618 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1619
1620 static char *typename_concat (struct obstack *obs, const char *prefix,
1621                               const char *suffix, int physname,
1622                               struct dwarf2_cu *cu);
1623
1624 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1625
1626 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1627
1628 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1629
1630 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1631
1632 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1633
1634 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1635
1636 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1637                                struct dwarf2_cu *, struct partial_symtab *);
1638
1639 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1640    values.  Keep the items ordered with increasing constraints compliance.  */
1641 enum pc_bounds_kind
1642 {
1643   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1644   PC_BOUNDS_NOT_PRESENT,
1645
1646   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1647      were present but they do not form a valid range of PC addresses.  */
1648   PC_BOUNDS_INVALID,
1649
1650   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1651   PC_BOUNDS_RANGES,
1652
1653   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1654   PC_BOUNDS_HIGH_LOW,
1655 };
1656
1657 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1658                                                  CORE_ADDR *, CORE_ADDR *,
1659                                                  struct dwarf2_cu *,
1660                                                  struct partial_symtab *);
1661
1662 static void get_scope_pc_bounds (struct die_info *,
1663                                  CORE_ADDR *, CORE_ADDR *,
1664                                  struct dwarf2_cu *);
1665
1666 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1667                                         CORE_ADDR, struct dwarf2_cu *);
1668
1669 static void dwarf2_add_field (struct field_info *, struct die_info *,
1670                               struct dwarf2_cu *);
1671
1672 static void dwarf2_attach_fields_to_type (struct field_info *,
1673                                           struct type *, struct dwarf2_cu *);
1674
1675 static void dwarf2_add_member_fn (struct field_info *,
1676                                   struct die_info *, struct type *,
1677                                   struct dwarf2_cu *);
1678
1679 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1680                                              struct type *,
1681                                              struct dwarf2_cu *);
1682
1683 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1684
1685 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1686
1687 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1688
1689 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1690
1691 static struct using_direct **using_directives (struct dwarf2_cu *cu);
1692
1693 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1694
1695 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1696
1697 static struct type *read_module_type (struct die_info *die,
1698                                       struct dwarf2_cu *cu);
1699
1700 static const char *namespace_name (struct die_info *die,
1701                                    int *is_anonymous, struct dwarf2_cu *);
1702
1703 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1704
1705 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1706
1707 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1708                                                        struct dwarf2_cu *);
1709
1710 static struct die_info *read_die_and_siblings_1
1711   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1712    struct die_info *);
1713
1714 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1715                                                const gdb_byte *info_ptr,
1716                                                const gdb_byte **new_info_ptr,
1717                                                struct die_info *parent);
1718
1719 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1720                                         struct die_info **, const gdb_byte *,
1721                                         int *, int);
1722
1723 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1724                                       struct die_info **, const gdb_byte *,
1725                                       int *);
1726
1727 static void process_die (struct die_info *, struct dwarf2_cu *);
1728
1729 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1730                                              struct obstack *);
1731
1732 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1733
1734 static const char *dwarf2_full_name (const char *name,
1735                                      struct die_info *die,
1736                                      struct dwarf2_cu *cu);
1737
1738 static const char *dwarf2_physname (const char *name, struct die_info *die,
1739                                     struct dwarf2_cu *cu);
1740
1741 static struct die_info *dwarf2_extension (struct die_info *die,
1742                                           struct dwarf2_cu **);
1743
1744 static const char *dwarf_tag_name (unsigned int);
1745
1746 static const char *dwarf_attr_name (unsigned int);
1747
1748 static const char *dwarf_form_name (unsigned int);
1749
1750 static const char *dwarf_bool_name (unsigned int);
1751
1752 static const char *dwarf_type_encoding_name (unsigned int);
1753
1754 static struct die_info *sibling_die (struct die_info *);
1755
1756 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1757
1758 static void dump_die_for_error (struct die_info *);
1759
1760 static void dump_die_1 (struct ui_file *, int level, int max_level,
1761                         struct die_info *);
1762
1763 /*static*/ void dump_die (struct die_info *, int max_level);
1764
1765 static void store_in_ref_table (struct die_info *,
1766                                 struct dwarf2_cu *);
1767
1768 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1769
1770 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1771
1772 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1773                                                const struct attribute *,
1774                                                struct dwarf2_cu **);
1775
1776 static struct die_info *follow_die_ref (struct die_info *,
1777                                         const struct attribute *,
1778                                         struct dwarf2_cu **);
1779
1780 static struct die_info *follow_die_sig (struct die_info *,
1781                                         const struct attribute *,
1782                                         struct dwarf2_cu **);
1783
1784 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1785                                          struct dwarf2_cu *);
1786
1787 static struct type *get_DW_AT_signature_type (struct die_info *,
1788                                               const struct attribute *,
1789                                               struct dwarf2_cu *);
1790
1791 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1792
1793 static void read_signatured_type (struct signatured_type *);
1794
1795 static int attr_to_dynamic_prop (const struct attribute *attr,
1796                                  struct die_info *die, struct dwarf2_cu *cu,
1797                                  struct dynamic_prop *prop);
1798
1799 /* memory allocation interface */
1800
1801 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1802
1803 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1804
1805 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1806
1807 static int attr_form_is_block (const struct attribute *);
1808
1809 static int attr_form_is_section_offset (const struct attribute *);
1810
1811 static int attr_form_is_constant (const struct attribute *);
1812
1813 static int attr_form_is_ref (const struct attribute *);
1814
1815 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1816                                    struct dwarf2_loclist_baton *baton,
1817                                    const struct attribute *attr);
1818
1819 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1820                                          struct symbol *sym,
1821                                          struct dwarf2_cu *cu,
1822                                          int is_block);
1823
1824 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1825                                      const gdb_byte *info_ptr,
1826                                      struct abbrev_info *abbrev);
1827
1828 static hashval_t partial_die_hash (const void *item);
1829
1830 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1831
1832 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1833   (sect_offset sect_off, unsigned int offset_in_dwz,
1834    struct dwarf2_per_objfile *dwarf2_per_objfile);
1835
1836 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1837                                    struct die_info *comp_unit_die,
1838                                    enum language pretend_language);
1839
1840 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1841
1842 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1843
1844 static struct type *set_die_type (struct die_info *, struct type *,
1845                                   struct dwarf2_cu *);
1846
1847 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1848
1849 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1850
1851 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1852                                  enum language);
1853
1854 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1855                                     enum language);
1856
1857 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1858                                     enum language);
1859
1860 static void dwarf2_add_dependence (struct dwarf2_cu *,
1861                                    struct dwarf2_per_cu_data *);
1862
1863 static void dwarf2_mark (struct dwarf2_cu *);
1864
1865 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1866
1867 static struct type *get_die_type_at_offset (sect_offset,
1868                                             struct dwarf2_per_cu_data *);
1869
1870 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1871
1872 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1873                              enum language pretend_language);
1874
1875 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1876
1877 /* Class, the destructor of which frees all allocated queue entries.  This
1878    will only have work to do if an error was thrown while processing the
1879    dwarf.  If no error was thrown then the queue entries should have all
1880    been processed, and freed, as we went along.  */
1881
1882 class dwarf2_queue_guard
1883 {
1884 public:
1885   dwarf2_queue_guard () = default;
1886
1887   /* Free any entries remaining on the queue.  There should only be
1888      entries left if we hit an error while processing the dwarf.  */
1889   ~dwarf2_queue_guard ()
1890   {
1891     struct dwarf2_queue_item *item, *last;
1892
1893     item = dwarf2_queue;
1894     while (item)
1895       {
1896         /* Anything still marked queued is likely to be in an
1897            inconsistent state, so discard it.  */
1898         if (item->per_cu->queued)
1899           {
1900             if (item->per_cu->cu != NULL)
1901               free_one_cached_comp_unit (item->per_cu);
1902             item->per_cu->queued = 0;
1903           }
1904
1905         last = item;
1906         item = item->next;
1907         xfree (last);
1908       }
1909
1910     dwarf2_queue = dwarf2_queue_tail = NULL;
1911   }
1912 };
1913
1914 /* The return type of find_file_and_directory.  Note, the enclosed
1915    string pointers are only valid while this object is valid.  */
1916
1917 struct file_and_directory
1918 {
1919   /* The filename.  This is never NULL.  */
1920   const char *name;
1921
1922   /* The compilation directory.  NULL if not known.  If we needed to
1923      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1924      points directly to the DW_AT_comp_dir string attribute owned by
1925      the obstack that owns the DIE.  */
1926   const char *comp_dir;
1927
1928   /* If we needed to build a new string for comp_dir, this is what
1929      owns the storage.  */
1930   std::string comp_dir_storage;
1931 };
1932
1933 static file_and_directory find_file_and_directory (struct die_info *die,
1934                                                    struct dwarf2_cu *cu);
1935
1936 static char *file_full_name (int file, struct line_header *lh,
1937                              const char *comp_dir);
1938
1939 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1940 enum class rcuh_kind { COMPILE, TYPE };
1941
1942 static const gdb_byte *read_and_check_comp_unit_head
1943   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1944    struct comp_unit_head *header,
1945    struct dwarf2_section_info *section,
1946    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1947    rcuh_kind section_kind);
1948
1949 static void init_cutu_and_read_dies
1950   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1951    int use_existing_cu, int keep, bool skip_partial,
1952    die_reader_func_ftype *die_reader_func, void *data);
1953
1954 static void init_cutu_and_read_dies_simple
1955   (struct dwarf2_per_cu_data *this_cu,
1956    die_reader_func_ftype *die_reader_func, void *data);
1957
1958 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1959
1960 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1961
1962 static struct dwo_unit *lookup_dwo_unit_in_dwp
1963   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1964    struct dwp_file *dwp_file, const char *comp_dir,
1965    ULONGEST signature, int is_debug_types);
1966
1967 static struct dwp_file *get_dwp_file
1968   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1969
1970 static struct dwo_unit *lookup_dwo_comp_unit
1971   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1972
1973 static struct dwo_unit *lookup_dwo_type_unit
1974   (struct signatured_type *, const char *, const char *);
1975
1976 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1977
1978 static void free_dwo_file (struct dwo_file *);
1979
1980 /* A unique_ptr helper to free a dwo_file.  */
1981
1982 struct dwo_file_deleter
1983 {
1984   void operator() (struct dwo_file *df) const
1985   {
1986     free_dwo_file (df);
1987   }
1988 };
1989
1990 /* A unique pointer to a dwo_file.  */
1991
1992 typedef std::unique_ptr<struct dwo_file, dwo_file_deleter> dwo_file_up;
1993
1994 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
1995
1996 static void check_producer (struct dwarf2_cu *cu);
1997
1998 static void free_line_header_voidp (void *arg);
1999 \f
2000 /* Various complaints about symbol reading that don't abort the process.  */
2001
2002 static void
2003 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2004 {
2005   complaint (_("statement list doesn't fit in .debug_line section"));
2006 }
2007
2008 static void
2009 dwarf2_debug_line_missing_file_complaint (void)
2010 {
2011   complaint (_(".debug_line section has line data without a file"));
2012 }
2013
2014 static void
2015 dwarf2_debug_line_missing_end_sequence_complaint (void)
2016 {
2017   complaint (_(".debug_line section has line "
2018                "program sequence without an end"));
2019 }
2020
2021 static void
2022 dwarf2_complex_location_expr_complaint (void)
2023 {
2024   complaint (_("location expression too complex"));
2025 }
2026
2027 static void
2028 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2029                                               int arg3)
2030 {
2031   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
2032              arg1, arg2, arg3);
2033 }
2034
2035 static void
2036 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2037 {
2038   complaint (_("debug info runs off end of %s section"
2039                " [in module %s]"),
2040              get_section_name (section),
2041              get_section_file_name (section));
2042 }
2043
2044 static void
2045 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2046 {
2047   complaint (_("macro debug info contains a "
2048                "malformed macro definition:\n`%s'"),
2049              arg1);
2050 }
2051
2052 static void
2053 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2054 {
2055   complaint (_("invalid attribute class or form for '%s' in '%s'"),
2056              arg1, arg2);
2057 }
2058
2059 /* Hash function for line_header_hash.  */
2060
2061 static hashval_t
2062 line_header_hash (const struct line_header *ofs)
2063 {
2064   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2065 }
2066
2067 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2068
2069 static hashval_t
2070 line_header_hash_voidp (const void *item)
2071 {
2072   const struct line_header *ofs = (const struct line_header *) item;
2073
2074   return line_header_hash (ofs);
2075 }
2076
2077 /* Equality function for line_header_hash.  */
2078
2079 static int
2080 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2081 {
2082   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2083   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2084
2085   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2086           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2087 }
2088
2089 \f
2090
2091 /* Read the given attribute value as an address, taking the attribute's
2092    form into account.  */
2093
2094 static CORE_ADDR
2095 attr_value_as_address (struct attribute *attr)
2096 {
2097   CORE_ADDR addr;
2098
2099   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2100     {
2101       /* Aside from a few clearly defined exceptions, attributes that
2102          contain an address must always be in DW_FORM_addr form.
2103          Unfortunately, some compilers happen to be violating this
2104          requirement by encoding addresses using other forms, such
2105          as DW_FORM_data4 for example.  For those broken compilers,
2106          we try to do our best, without any guarantee of success,
2107          to interpret the address correctly.  It would also be nice
2108          to generate a complaint, but that would require us to maintain
2109          a list of legitimate cases where a non-address form is allowed,
2110          as well as update callers to pass in at least the CU's DWARF
2111          version.  This is more overhead than what we're willing to
2112          expand for a pretty rare case.  */
2113       addr = DW_UNSND (attr);
2114     }
2115   else
2116     addr = DW_ADDR (attr);
2117
2118   return addr;
2119 }
2120
2121 /* See declaration.  */
2122
2123 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2124                                         const dwarf2_debug_sections *names)
2125   : objfile (objfile_)
2126 {
2127   if (names == NULL)
2128     names = &dwarf2_elf_names;
2129
2130   bfd *obfd = objfile->obfd;
2131
2132   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2133     locate_sections (obfd, sec, *names);
2134 }
2135
2136 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2137
2138 dwarf2_per_objfile::~dwarf2_per_objfile ()
2139 {
2140   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2141   free_cached_comp_units ();
2142
2143   if (quick_file_names_table)
2144     htab_delete (quick_file_names_table);
2145
2146   if (line_header_hash)
2147     htab_delete (line_header_hash);
2148
2149   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2150     VEC_free (dwarf2_per_cu_ptr, per_cu->imported_symtabs);
2151
2152   for (signatured_type *sig_type : all_type_units)
2153     VEC_free (dwarf2_per_cu_ptr, sig_type->per_cu.imported_symtabs);
2154
2155   VEC_free (dwarf2_section_info_def, types);
2156
2157   if (dwo_files != NULL)
2158     free_dwo_files (dwo_files, objfile);
2159
2160   /* Everything else should be on the objfile obstack.  */
2161 }
2162
2163 /* See declaration.  */
2164
2165 void
2166 dwarf2_per_objfile::free_cached_comp_units ()
2167 {
2168   dwarf2_per_cu_data *per_cu = read_in_chain;
2169   dwarf2_per_cu_data **last_chain = &read_in_chain;
2170   while (per_cu != NULL)
2171     {
2172       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2173
2174       delete per_cu->cu;
2175       *last_chain = next_cu;
2176       per_cu = next_cu;
2177     }
2178 }
2179
2180 /* A helper class that calls free_cached_comp_units on
2181    destruction.  */
2182
2183 class free_cached_comp_units
2184 {
2185 public:
2186
2187   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2188     : m_per_objfile (per_objfile)
2189   {
2190   }
2191
2192   ~free_cached_comp_units ()
2193   {
2194     m_per_objfile->free_cached_comp_units ();
2195   }
2196
2197   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2198
2199 private:
2200
2201   dwarf2_per_objfile *m_per_objfile;
2202 };
2203
2204 /* Try to locate the sections we need for DWARF 2 debugging
2205    information and return true if we have enough to do something.
2206    NAMES points to the dwarf2 section names, or is NULL if the standard
2207    ELF names are used.  */
2208
2209 int
2210 dwarf2_has_info (struct objfile *objfile,
2211                  const struct dwarf2_debug_sections *names)
2212 {
2213   if (objfile->flags & OBJF_READNEVER)
2214     return 0;
2215
2216   struct dwarf2_per_objfile *dwarf2_per_objfile
2217     = get_dwarf2_per_objfile (objfile);
2218
2219   if (dwarf2_per_objfile == NULL)
2220     {
2221       /* Initialize per-objfile state.  */
2222       dwarf2_per_objfile
2223         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2224                                                                      names);
2225       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2226     }
2227   return (!dwarf2_per_objfile->info.is_virtual
2228           && dwarf2_per_objfile->info.s.section != NULL
2229           && !dwarf2_per_objfile->abbrev.is_virtual
2230           && dwarf2_per_objfile->abbrev.s.section != NULL);
2231 }
2232
2233 /* Return the containing section of virtual section SECTION.  */
2234
2235 static struct dwarf2_section_info *
2236 get_containing_section (const struct dwarf2_section_info *section)
2237 {
2238   gdb_assert (section->is_virtual);
2239   return section->s.containing_section;
2240 }
2241
2242 /* Return the bfd owner of SECTION.  */
2243
2244 static struct bfd *
2245 get_section_bfd_owner (const struct dwarf2_section_info *section)
2246 {
2247   if (section->is_virtual)
2248     {
2249       section = get_containing_section (section);
2250       gdb_assert (!section->is_virtual);
2251     }
2252   return section->s.section->owner;
2253 }
2254
2255 /* Return the bfd section of SECTION.
2256    Returns NULL if the section is not present.  */
2257
2258 static asection *
2259 get_section_bfd_section (const struct dwarf2_section_info *section)
2260 {
2261   if (section->is_virtual)
2262     {
2263       section = get_containing_section (section);
2264       gdb_assert (!section->is_virtual);
2265     }
2266   return section->s.section;
2267 }
2268
2269 /* Return the name of SECTION.  */
2270
2271 static const char *
2272 get_section_name (const struct dwarf2_section_info *section)
2273 {
2274   asection *sectp = get_section_bfd_section (section);
2275
2276   gdb_assert (sectp != NULL);
2277   return bfd_section_name (get_section_bfd_owner (section), sectp);
2278 }
2279
2280 /* Return the name of the file SECTION is in.  */
2281
2282 static const char *
2283 get_section_file_name (const struct dwarf2_section_info *section)
2284 {
2285   bfd *abfd = get_section_bfd_owner (section);
2286
2287   return bfd_get_filename (abfd);
2288 }
2289
2290 /* Return the id of SECTION.
2291    Returns 0 if SECTION doesn't exist.  */
2292
2293 static int
2294 get_section_id (const struct dwarf2_section_info *section)
2295 {
2296   asection *sectp = get_section_bfd_section (section);
2297
2298   if (sectp == NULL)
2299     return 0;
2300   return sectp->id;
2301 }
2302
2303 /* Return the flags of SECTION.
2304    SECTION (or containing section if this is a virtual section) must exist.  */
2305
2306 static int
2307 get_section_flags (const struct dwarf2_section_info *section)
2308 {
2309   asection *sectp = get_section_bfd_section (section);
2310
2311   gdb_assert (sectp != NULL);
2312   return bfd_get_section_flags (sectp->owner, sectp);
2313 }
2314
2315 /* When loading sections, we look either for uncompressed section or for
2316    compressed section names.  */
2317
2318 static int
2319 section_is_p (const char *section_name,
2320               const struct dwarf2_section_names *names)
2321 {
2322   if (names->normal != NULL
2323       && strcmp (section_name, names->normal) == 0)
2324     return 1;
2325   if (names->compressed != NULL
2326       && strcmp (section_name, names->compressed) == 0)
2327     return 1;
2328   return 0;
2329 }
2330
2331 /* See declaration.  */
2332
2333 void
2334 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2335                                      const dwarf2_debug_sections &names)
2336 {
2337   flagword aflag = bfd_get_section_flags (abfd, sectp);
2338
2339   if ((aflag & SEC_HAS_CONTENTS) == 0)
2340     {
2341     }
2342   else if (section_is_p (sectp->name, &names.info))
2343     {
2344       this->info.s.section = sectp;
2345       this->info.size = bfd_get_section_size (sectp);
2346     }
2347   else if (section_is_p (sectp->name, &names.abbrev))
2348     {
2349       this->abbrev.s.section = sectp;
2350       this->abbrev.size = bfd_get_section_size (sectp);
2351     }
2352   else if (section_is_p (sectp->name, &names.line))
2353     {
2354       this->line.s.section = sectp;
2355       this->line.size = bfd_get_section_size (sectp);
2356     }
2357   else if (section_is_p (sectp->name, &names.loc))
2358     {
2359       this->loc.s.section = sectp;
2360       this->loc.size = bfd_get_section_size (sectp);
2361     }
2362   else if (section_is_p (sectp->name, &names.loclists))
2363     {
2364       this->loclists.s.section = sectp;
2365       this->loclists.size = bfd_get_section_size (sectp);
2366     }
2367   else if (section_is_p (sectp->name, &names.macinfo))
2368     {
2369       this->macinfo.s.section = sectp;
2370       this->macinfo.size = bfd_get_section_size (sectp);
2371     }
2372   else if (section_is_p (sectp->name, &names.macro))
2373     {
2374       this->macro.s.section = sectp;
2375       this->macro.size = bfd_get_section_size (sectp);
2376     }
2377   else if (section_is_p (sectp->name, &names.str))
2378     {
2379       this->str.s.section = sectp;
2380       this->str.size = bfd_get_section_size (sectp);
2381     }
2382   else if (section_is_p (sectp->name, &names.line_str))
2383     {
2384       this->line_str.s.section = sectp;
2385       this->line_str.size = bfd_get_section_size (sectp);
2386     }
2387   else if (section_is_p (sectp->name, &names.addr))
2388     {
2389       this->addr.s.section = sectp;
2390       this->addr.size = bfd_get_section_size (sectp);
2391     }
2392   else if (section_is_p (sectp->name, &names.frame))
2393     {
2394       this->frame.s.section = sectp;
2395       this->frame.size = bfd_get_section_size (sectp);
2396     }
2397   else if (section_is_p (sectp->name, &names.eh_frame))
2398     {
2399       this->eh_frame.s.section = sectp;
2400       this->eh_frame.size = bfd_get_section_size (sectp);
2401     }
2402   else if (section_is_p (sectp->name, &names.ranges))
2403     {
2404       this->ranges.s.section = sectp;
2405       this->ranges.size = bfd_get_section_size (sectp);
2406     }
2407   else if (section_is_p (sectp->name, &names.rnglists))
2408     {
2409       this->rnglists.s.section = sectp;
2410       this->rnglists.size = bfd_get_section_size (sectp);
2411     }
2412   else if (section_is_p (sectp->name, &names.types))
2413     {
2414       struct dwarf2_section_info type_section;
2415
2416       memset (&type_section, 0, sizeof (type_section));
2417       type_section.s.section = sectp;
2418       type_section.size = bfd_get_section_size (sectp);
2419
2420       VEC_safe_push (dwarf2_section_info_def, this->types,
2421                      &type_section);
2422     }
2423   else if (section_is_p (sectp->name, &names.gdb_index))
2424     {
2425       this->gdb_index.s.section = sectp;
2426       this->gdb_index.size = bfd_get_section_size (sectp);
2427     }
2428   else if (section_is_p (sectp->name, &names.debug_names))
2429     {
2430       this->debug_names.s.section = sectp;
2431       this->debug_names.size = bfd_get_section_size (sectp);
2432     }
2433   else if (section_is_p (sectp->name, &names.debug_aranges))
2434     {
2435       this->debug_aranges.s.section = sectp;
2436       this->debug_aranges.size = bfd_get_section_size (sectp);
2437     }
2438
2439   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2440       && bfd_section_vma (abfd, sectp) == 0)
2441     this->has_section_at_zero = true;
2442 }
2443
2444 /* A helper function that decides whether a section is empty,
2445    or not present.  */
2446
2447 static int
2448 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2449 {
2450   if (section->is_virtual)
2451     return section->size == 0;
2452   return section->s.section == NULL || section->size == 0;
2453 }
2454
2455 /* See dwarf2read.h.  */
2456
2457 void
2458 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2459 {
2460   asection *sectp;
2461   bfd *abfd;
2462   gdb_byte *buf, *retbuf;
2463
2464   if (info->readin)
2465     return;
2466   info->buffer = NULL;
2467   info->readin = 1;
2468
2469   if (dwarf2_section_empty_p (info))
2470     return;
2471
2472   sectp = get_section_bfd_section (info);
2473
2474   /* If this is a virtual section we need to read in the real one first.  */
2475   if (info->is_virtual)
2476     {
2477       struct dwarf2_section_info *containing_section =
2478         get_containing_section (info);
2479
2480       gdb_assert (sectp != NULL);
2481       if ((sectp->flags & SEC_RELOC) != 0)
2482         {
2483           error (_("Dwarf Error: DWP format V2 with relocations is not"
2484                    " supported in section %s [in module %s]"),
2485                  get_section_name (info), get_section_file_name (info));
2486         }
2487       dwarf2_read_section (objfile, containing_section);
2488       /* Other code should have already caught virtual sections that don't
2489          fit.  */
2490       gdb_assert (info->virtual_offset + info->size
2491                   <= containing_section->size);
2492       /* If the real section is empty or there was a problem reading the
2493          section we shouldn't get here.  */
2494       gdb_assert (containing_section->buffer != NULL);
2495       info->buffer = containing_section->buffer + info->virtual_offset;
2496       return;
2497     }
2498
2499   /* If the section has relocations, we must read it ourselves.
2500      Otherwise we attach it to the BFD.  */
2501   if ((sectp->flags & SEC_RELOC) == 0)
2502     {
2503       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2504       return;
2505     }
2506
2507   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2508   info->buffer = buf;
2509
2510   /* When debugging .o files, we may need to apply relocations; see
2511      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2512      We never compress sections in .o files, so we only need to
2513      try this when the section is not compressed.  */
2514   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2515   if (retbuf != NULL)
2516     {
2517       info->buffer = retbuf;
2518       return;
2519     }
2520
2521   abfd = get_section_bfd_owner (info);
2522   gdb_assert (abfd != NULL);
2523
2524   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2525       || bfd_bread (buf, info->size, abfd) != info->size)
2526     {
2527       error (_("Dwarf Error: Can't read DWARF data"
2528                " in section %s [in module %s]"),
2529              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2530     }
2531 }
2532
2533 /* A helper function that returns the size of a section in a safe way.
2534    If you are positive that the section has been read before using the
2535    size, then it is safe to refer to the dwarf2_section_info object's
2536    "size" field directly.  In other cases, you must call this
2537    function, because for compressed sections the size field is not set
2538    correctly until the section has been read.  */
2539
2540 static bfd_size_type
2541 dwarf2_section_size (struct objfile *objfile,
2542                      struct dwarf2_section_info *info)
2543 {
2544   if (!info->readin)
2545     dwarf2_read_section (objfile, info);
2546   return info->size;
2547 }
2548
2549 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2550    SECTION_NAME.  */
2551
2552 void
2553 dwarf2_get_section_info (struct objfile *objfile,
2554                          enum dwarf2_section_enum sect,
2555                          asection **sectp, const gdb_byte **bufp,
2556                          bfd_size_type *sizep)
2557 {
2558   struct dwarf2_per_objfile *data
2559     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2560                                                   dwarf2_objfile_data_key);
2561   struct dwarf2_section_info *info;
2562
2563   /* We may see an objfile without any DWARF, in which case we just
2564      return nothing.  */
2565   if (data == NULL)
2566     {
2567       *sectp = NULL;
2568       *bufp = NULL;
2569       *sizep = 0;
2570       return;
2571     }
2572   switch (sect)
2573     {
2574     case DWARF2_DEBUG_FRAME:
2575       info = &data->frame;
2576       break;
2577     case DWARF2_EH_FRAME:
2578       info = &data->eh_frame;
2579       break;
2580     default:
2581       gdb_assert_not_reached ("unexpected section");
2582     }
2583
2584   dwarf2_read_section (objfile, info);
2585
2586   *sectp = get_section_bfd_section (info);
2587   *bufp = info->buffer;
2588   *sizep = info->size;
2589 }
2590
2591 /* A helper function to find the sections for a .dwz file.  */
2592
2593 static void
2594 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2595 {
2596   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2597
2598   /* Note that we only support the standard ELF names, because .dwz
2599      is ELF-only (at the time of writing).  */
2600   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2601     {
2602       dwz_file->abbrev.s.section = sectp;
2603       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2604     }
2605   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2606     {
2607       dwz_file->info.s.section = sectp;
2608       dwz_file->info.size = bfd_get_section_size (sectp);
2609     }
2610   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2611     {
2612       dwz_file->str.s.section = sectp;
2613       dwz_file->str.size = bfd_get_section_size (sectp);
2614     }
2615   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2616     {
2617       dwz_file->line.s.section = sectp;
2618       dwz_file->line.size = bfd_get_section_size (sectp);
2619     }
2620   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2621     {
2622       dwz_file->macro.s.section = sectp;
2623       dwz_file->macro.size = bfd_get_section_size (sectp);
2624     }
2625   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2626     {
2627       dwz_file->gdb_index.s.section = sectp;
2628       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2629     }
2630   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2631     {
2632       dwz_file->debug_names.s.section = sectp;
2633       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2634     }
2635 }
2636
2637 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2638    there is no .gnu_debugaltlink section in the file.  Error if there
2639    is such a section but the file cannot be found.  */
2640
2641 static struct dwz_file *
2642 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2643 {
2644   const char *filename;
2645   bfd_size_type buildid_len_arg;
2646   size_t buildid_len;
2647   bfd_byte *buildid;
2648
2649   if (dwarf2_per_objfile->dwz_file != NULL)
2650     return dwarf2_per_objfile->dwz_file.get ();
2651
2652   bfd_set_error (bfd_error_no_error);
2653   gdb::unique_xmalloc_ptr<char> data
2654     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2655                                   &buildid_len_arg, &buildid));
2656   if (data == NULL)
2657     {
2658       if (bfd_get_error () == bfd_error_no_error)
2659         return NULL;
2660       error (_("could not read '.gnu_debugaltlink' section: %s"),
2661              bfd_errmsg (bfd_get_error ()));
2662     }
2663
2664   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2665
2666   buildid_len = (size_t) buildid_len_arg;
2667
2668   filename = data.get ();
2669
2670   std::string abs_storage;
2671   if (!IS_ABSOLUTE_PATH (filename))
2672     {
2673       gdb::unique_xmalloc_ptr<char> abs
2674         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2675
2676       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2677       filename = abs_storage.c_str ();
2678     }
2679
2680   /* First try the file name given in the section.  If that doesn't
2681      work, try to use the build-id instead.  */
2682   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2683   if (dwz_bfd != NULL)
2684     {
2685       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2686         dwz_bfd.release ();
2687     }
2688
2689   if (dwz_bfd == NULL)
2690     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2691
2692   if (dwz_bfd == NULL)
2693     error (_("could not find '.gnu_debugaltlink' file for %s"),
2694            objfile_name (dwarf2_per_objfile->objfile));
2695
2696   std::unique_ptr<struct dwz_file> result
2697     (new struct dwz_file (std::move (dwz_bfd)));
2698
2699   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2700                          result.get ());
2701
2702   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2703                             result->dwz_bfd.get ());
2704   dwarf2_per_objfile->dwz_file = std::move (result);
2705   return dwarf2_per_objfile->dwz_file.get ();
2706 }
2707 \f
2708 /* DWARF quick_symbols_functions support.  */
2709
2710 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2711    unique line tables, so we maintain a separate table of all .debug_line
2712    derived entries to support the sharing.
2713    All the quick functions need is the list of file names.  We discard the
2714    line_header when we're done and don't need to record it here.  */
2715 struct quick_file_names
2716 {
2717   /* The data used to construct the hash key.  */
2718   struct stmt_list_hash hash;
2719
2720   /* The number of entries in file_names, real_names.  */
2721   unsigned int num_file_names;
2722
2723   /* The file names from the line table, after being run through
2724      file_full_name.  */
2725   const char **file_names;
2726
2727   /* The file names from the line table after being run through
2728      gdb_realpath.  These are computed lazily.  */
2729   const char **real_names;
2730 };
2731
2732 /* When using the index (and thus not using psymtabs), each CU has an
2733    object of this type.  This is used to hold information needed by
2734    the various "quick" methods.  */
2735 struct dwarf2_per_cu_quick_data
2736 {
2737   /* The file table.  This can be NULL if there was no file table
2738      or it's currently not read in.
2739      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2740   struct quick_file_names *file_names;
2741
2742   /* The corresponding symbol table.  This is NULL if symbols for this
2743      CU have not yet been read.  */
2744   struct compunit_symtab *compunit_symtab;
2745
2746   /* A temporary mark bit used when iterating over all CUs in
2747      expand_symtabs_matching.  */
2748   unsigned int mark : 1;
2749
2750   /* True if we've tried to read the file table and found there isn't one.
2751      There will be no point in trying to read it again next time.  */
2752   unsigned int no_file_data : 1;
2753 };
2754
2755 /* Utility hash function for a stmt_list_hash.  */
2756
2757 static hashval_t
2758 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2759 {
2760   hashval_t v = 0;
2761
2762   if (stmt_list_hash->dwo_unit != NULL)
2763     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2764   v += to_underlying (stmt_list_hash->line_sect_off);
2765   return v;
2766 }
2767
2768 /* Utility equality function for a stmt_list_hash.  */
2769
2770 static int
2771 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2772                     const struct stmt_list_hash *rhs)
2773 {
2774   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2775     return 0;
2776   if (lhs->dwo_unit != NULL
2777       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2778     return 0;
2779
2780   return lhs->line_sect_off == rhs->line_sect_off;
2781 }
2782
2783 /* Hash function for a quick_file_names.  */
2784
2785 static hashval_t
2786 hash_file_name_entry (const void *e)
2787 {
2788   const struct quick_file_names *file_data
2789     = (const struct quick_file_names *) e;
2790
2791   return hash_stmt_list_entry (&file_data->hash);
2792 }
2793
2794 /* Equality function for a quick_file_names.  */
2795
2796 static int
2797 eq_file_name_entry (const void *a, const void *b)
2798 {
2799   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2800   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2801
2802   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2803 }
2804
2805 /* Delete function for a quick_file_names.  */
2806
2807 static void
2808 delete_file_name_entry (void *e)
2809 {
2810   struct quick_file_names *file_data = (struct quick_file_names *) e;
2811   int i;
2812
2813   for (i = 0; i < file_data->num_file_names; ++i)
2814     {
2815       xfree ((void*) file_data->file_names[i]);
2816       if (file_data->real_names)
2817         xfree ((void*) file_data->real_names[i]);
2818     }
2819
2820   /* The space for the struct itself lives on objfile_obstack,
2821      so we don't free it here.  */
2822 }
2823
2824 /* Create a quick_file_names hash table.  */
2825
2826 static htab_t
2827 create_quick_file_names_table (unsigned int nr_initial_entries)
2828 {
2829   return htab_create_alloc (nr_initial_entries,
2830                             hash_file_name_entry, eq_file_name_entry,
2831                             delete_file_name_entry, xcalloc, xfree);
2832 }
2833
2834 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2835    have to be created afterwards.  You should call age_cached_comp_units after
2836    processing PER_CU->CU.  dw2_setup must have been already called.  */
2837
2838 static void
2839 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2840 {
2841   if (per_cu->is_debug_types)
2842     load_full_type_unit (per_cu);
2843   else
2844     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2845
2846   if (per_cu->cu == NULL)
2847     return;  /* Dummy CU.  */
2848
2849   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2850 }
2851
2852 /* Read in the symbols for PER_CU.  */
2853
2854 static void
2855 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2856 {
2857   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2858
2859   /* Skip type_unit_groups, reading the type units they contain
2860      is handled elsewhere.  */
2861   if (IS_TYPE_UNIT_GROUP (per_cu))
2862     return;
2863
2864   /* The destructor of dwarf2_queue_guard frees any entries left on
2865      the queue.  After this point we're guaranteed to leave this function
2866      with the dwarf queue empty.  */
2867   dwarf2_queue_guard q_guard;
2868
2869   if (dwarf2_per_objfile->using_index
2870       ? per_cu->v.quick->compunit_symtab == NULL
2871       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2872     {
2873       queue_comp_unit (per_cu, language_minimal);
2874       load_cu (per_cu, skip_partial);
2875
2876       /* If we just loaded a CU from a DWO, and we're working with an index
2877          that may badly handle TUs, load all the TUs in that DWO as well.
2878          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2879       if (!per_cu->is_debug_types
2880           && per_cu->cu != NULL
2881           && per_cu->cu->dwo_unit != NULL
2882           && dwarf2_per_objfile->index_table != NULL
2883           && dwarf2_per_objfile->index_table->version <= 7
2884           /* DWP files aren't supported yet.  */
2885           && get_dwp_file (dwarf2_per_objfile) == NULL)
2886         queue_and_load_all_dwo_tus (per_cu);
2887     }
2888
2889   process_queue (dwarf2_per_objfile);
2890
2891   /* Age the cache, releasing compilation units that have not
2892      been used recently.  */
2893   age_cached_comp_units (dwarf2_per_objfile);
2894 }
2895
2896 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2897    the objfile from which this CU came.  Returns the resulting symbol
2898    table.  */
2899
2900 static struct compunit_symtab *
2901 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2902 {
2903   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2904
2905   gdb_assert (dwarf2_per_objfile->using_index);
2906   if (!per_cu->v.quick->compunit_symtab)
2907     {
2908       free_cached_comp_units freer (dwarf2_per_objfile);
2909       scoped_restore decrementer = increment_reading_symtab ();
2910       dw2_do_instantiate_symtab (per_cu, skip_partial);
2911       process_cu_includes (dwarf2_per_objfile);
2912     }
2913
2914   return per_cu->v.quick->compunit_symtab;
2915 }
2916
2917 /* See declaration.  */
2918
2919 dwarf2_per_cu_data *
2920 dwarf2_per_objfile::get_cutu (int index)
2921 {
2922   if (index >= this->all_comp_units.size ())
2923     {
2924       index -= this->all_comp_units.size ();
2925       gdb_assert (index < this->all_type_units.size ());
2926       return &this->all_type_units[index]->per_cu;
2927     }
2928
2929   return this->all_comp_units[index];
2930 }
2931
2932 /* See declaration.  */
2933
2934 dwarf2_per_cu_data *
2935 dwarf2_per_objfile::get_cu (int index)
2936 {
2937   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2938
2939   return this->all_comp_units[index];
2940 }
2941
2942 /* See declaration.  */
2943
2944 signatured_type *
2945 dwarf2_per_objfile::get_tu (int index)
2946 {
2947   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2948
2949   return this->all_type_units[index];
2950 }
2951
2952 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2953    objfile_obstack, and constructed with the specified field
2954    values.  */
2955
2956 static dwarf2_per_cu_data *
2957 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2958                           struct dwarf2_section_info *section,
2959                           int is_dwz,
2960                           sect_offset sect_off, ULONGEST length)
2961 {
2962   struct objfile *objfile = dwarf2_per_objfile->objfile;
2963   dwarf2_per_cu_data *the_cu
2964     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2965                      struct dwarf2_per_cu_data);
2966   the_cu->sect_off = sect_off;
2967   the_cu->length = length;
2968   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2969   the_cu->section = section;
2970   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2971                                    struct dwarf2_per_cu_quick_data);
2972   the_cu->is_dwz = is_dwz;
2973   return the_cu;
2974 }
2975
2976 /* A helper for create_cus_from_index that handles a given list of
2977    CUs.  */
2978
2979 static void
2980 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2981                             const gdb_byte *cu_list, offset_type n_elements,
2982                             struct dwarf2_section_info *section,
2983                             int is_dwz)
2984 {
2985   for (offset_type i = 0; i < n_elements; i += 2)
2986     {
2987       gdb_static_assert (sizeof (ULONGEST) >= 8);
2988
2989       sect_offset sect_off
2990         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2991       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2992       cu_list += 2 * 8;
2993
2994       dwarf2_per_cu_data *per_cu
2995         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2996                                      sect_off, length);
2997       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
2998     }
2999 }
3000
3001 /* Read the CU list from the mapped index, and use it to create all
3002    the CU objects for this objfile.  */
3003
3004 static void
3005 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3006                        const gdb_byte *cu_list, offset_type cu_list_elements,
3007                        const gdb_byte *dwz_list, offset_type dwz_elements)
3008 {
3009   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
3010   dwarf2_per_objfile->all_comp_units.reserve
3011     ((cu_list_elements + dwz_elements) / 2);
3012
3013   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
3014                               &dwarf2_per_objfile->info, 0);
3015
3016   if (dwz_elements == 0)
3017     return;
3018
3019   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3020   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
3021                               &dwz->info, 1);
3022 }
3023
3024 /* Create the signatured type hash table from the index.  */
3025
3026 static void
3027 create_signatured_type_table_from_index
3028   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3029    struct dwarf2_section_info *section,
3030    const gdb_byte *bytes,
3031    offset_type elements)
3032 {
3033   struct objfile *objfile = dwarf2_per_objfile->objfile;
3034
3035   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3036   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
3037
3038   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3039
3040   for (offset_type i = 0; i < elements; i += 3)
3041     {
3042       struct signatured_type *sig_type;
3043       ULONGEST signature;
3044       void **slot;
3045       cu_offset type_offset_in_tu;
3046
3047       gdb_static_assert (sizeof (ULONGEST) >= 8);
3048       sect_offset sect_off
3049         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3050       type_offset_in_tu
3051         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3052                                                 BFD_ENDIAN_LITTLE);
3053       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3054       bytes += 3 * 8;
3055
3056       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3057                                  struct signatured_type);
3058       sig_type->signature = signature;
3059       sig_type->type_offset_in_tu = type_offset_in_tu;
3060       sig_type->per_cu.is_debug_types = 1;
3061       sig_type->per_cu.section = section;
3062       sig_type->per_cu.sect_off = sect_off;
3063       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3064       sig_type->per_cu.v.quick
3065         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3066                           struct dwarf2_per_cu_quick_data);
3067
3068       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3069       *slot = sig_type;
3070
3071       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3072     }
3073
3074   dwarf2_per_objfile->signatured_types = sig_types_hash;
3075 }
3076
3077 /* Create the signatured type hash table from .debug_names.  */
3078
3079 static void
3080 create_signatured_type_table_from_debug_names
3081   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3082    const mapped_debug_names &map,
3083    struct dwarf2_section_info *section,
3084    struct dwarf2_section_info *abbrev_section)
3085 {
3086   struct objfile *objfile = dwarf2_per_objfile->objfile;
3087
3088   dwarf2_read_section (objfile, section);
3089   dwarf2_read_section (objfile, abbrev_section);
3090
3091   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3092   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
3093
3094   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3095
3096   for (uint32_t i = 0; i < map.tu_count; ++i)
3097     {
3098       struct signatured_type *sig_type;
3099       void **slot;
3100
3101       sect_offset sect_off
3102         = (sect_offset) (extract_unsigned_integer
3103                          (map.tu_table_reordered + i * map.offset_size,
3104                           map.offset_size,
3105                           map.dwarf5_byte_order));
3106
3107       comp_unit_head cu_header;
3108       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3109                                      abbrev_section,
3110                                      section->buffer + to_underlying (sect_off),
3111                                      rcuh_kind::TYPE);
3112
3113       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3114                                  struct signatured_type);
3115       sig_type->signature = cu_header.signature;
3116       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3117       sig_type->per_cu.is_debug_types = 1;
3118       sig_type->per_cu.section = section;
3119       sig_type->per_cu.sect_off = sect_off;
3120       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3121       sig_type->per_cu.v.quick
3122         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3123                           struct dwarf2_per_cu_quick_data);
3124
3125       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3126       *slot = sig_type;
3127
3128       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3129     }
3130
3131   dwarf2_per_objfile->signatured_types = sig_types_hash;
3132 }
3133
3134 /* Read the address map data from the mapped index, and use it to
3135    populate the objfile's psymtabs_addrmap.  */
3136
3137 static void
3138 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3139                            struct mapped_index *index)
3140 {
3141   struct objfile *objfile = dwarf2_per_objfile->objfile;
3142   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3143   const gdb_byte *iter, *end;
3144   struct addrmap *mutable_map;
3145   CORE_ADDR baseaddr;
3146
3147   auto_obstack temp_obstack;
3148
3149   mutable_map = addrmap_create_mutable (&temp_obstack);
3150
3151   iter = index->address_table.data ();
3152   end = iter + index->address_table.size ();
3153
3154   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3155
3156   while (iter < end)
3157     {
3158       ULONGEST hi, lo, cu_index;
3159       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3160       iter += 8;
3161       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3162       iter += 8;
3163       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3164       iter += 4;
3165
3166       if (lo > hi)
3167         {
3168           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
3169                      hex_string (lo), hex_string (hi));
3170           continue;
3171         }
3172
3173       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
3174         {
3175           complaint (_(".gdb_index address table has invalid CU number %u"),
3176                      (unsigned) cu_index);
3177           continue;
3178         }
3179
3180       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr) - baseaddr;
3181       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr) - baseaddr;
3182       addrmap_set_empty (mutable_map, lo, hi - 1,
3183                          dwarf2_per_objfile->get_cu (cu_index));
3184     }
3185
3186   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3187                                                     &objfile->objfile_obstack);
3188 }
3189
3190 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3191    populate the objfile's psymtabs_addrmap.  */
3192
3193 static void
3194 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3195                              struct dwarf2_section_info *section)
3196 {
3197   struct objfile *objfile = dwarf2_per_objfile->objfile;
3198   bfd *abfd = objfile->obfd;
3199   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3200   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3201                                        SECT_OFF_TEXT (objfile));
3202
3203   auto_obstack temp_obstack;
3204   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3205
3206   std::unordered_map<sect_offset,
3207                      dwarf2_per_cu_data *,
3208                      gdb::hash_enum<sect_offset>>
3209     debug_info_offset_to_per_cu;
3210   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3211     {
3212       const auto insertpair
3213         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3214       if (!insertpair.second)
3215         {
3216           warning (_("Section .debug_aranges in %s has duplicate "
3217                      "debug_info_offset %s, ignoring .debug_aranges."),
3218                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3219           return;
3220         }
3221     }
3222
3223   dwarf2_read_section (objfile, section);
3224
3225   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3226
3227   const gdb_byte *addr = section->buffer;
3228
3229   while (addr < section->buffer + section->size)
3230     {
3231       const gdb_byte *const entry_addr = addr;
3232       unsigned int bytes_read;
3233
3234       const LONGEST entry_length = read_initial_length (abfd, addr,
3235                                                         &bytes_read);
3236       addr += bytes_read;
3237
3238       const gdb_byte *const entry_end = addr + entry_length;
3239       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3240       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3241       if (addr + entry_length > section->buffer + section->size)
3242         {
3243           warning (_("Section .debug_aranges in %s entry at offset %zu "
3244                      "length %s exceeds section length %s, "
3245                      "ignoring .debug_aranges."),
3246                    objfile_name (objfile), entry_addr - section->buffer,
3247                    plongest (bytes_read + entry_length),
3248                    pulongest (section->size));
3249           return;
3250         }
3251
3252       /* The version number.  */
3253       const uint16_t version = read_2_bytes (abfd, addr);
3254       addr += 2;
3255       if (version != 2)
3256         {
3257           warning (_("Section .debug_aranges in %s entry at offset %zu "
3258                      "has unsupported version %d, ignoring .debug_aranges."),
3259                    objfile_name (objfile), entry_addr - section->buffer,
3260                    version);
3261           return;
3262         }
3263
3264       const uint64_t debug_info_offset
3265         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3266       addr += offset_size;
3267       const auto per_cu_it
3268         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3269       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3270         {
3271           warning (_("Section .debug_aranges in %s entry at offset %zu "
3272                      "debug_info_offset %s does not exists, "
3273                      "ignoring .debug_aranges."),
3274                    objfile_name (objfile), entry_addr - section->buffer,
3275                    pulongest (debug_info_offset));
3276           return;
3277         }
3278       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3279
3280       const uint8_t address_size = *addr++;
3281       if (address_size < 1 || address_size > 8)
3282         {
3283           warning (_("Section .debug_aranges in %s entry at offset %zu "
3284                      "address_size %u is invalid, ignoring .debug_aranges."),
3285                    objfile_name (objfile), entry_addr - section->buffer,
3286                    address_size);
3287           return;
3288         }
3289
3290       const uint8_t segment_selector_size = *addr++;
3291       if (segment_selector_size != 0)
3292         {
3293           warning (_("Section .debug_aranges in %s entry at offset %zu "
3294                      "segment_selector_size %u is not supported, "
3295                      "ignoring .debug_aranges."),
3296                    objfile_name (objfile), entry_addr - section->buffer,
3297                    segment_selector_size);
3298           return;
3299         }
3300
3301       /* Must pad to an alignment boundary that is twice the address
3302          size.  It is undocumented by the DWARF standard but GCC does
3303          use it.  */
3304       for (size_t padding = ((-(addr - section->buffer))
3305                              & (2 * address_size - 1));
3306            padding > 0; padding--)
3307         if (*addr++ != 0)
3308           {
3309             warning (_("Section .debug_aranges in %s entry at offset %zu "
3310                        "padding is not zero, ignoring .debug_aranges."),
3311                      objfile_name (objfile), entry_addr - section->buffer);
3312             return;
3313           }
3314
3315       for (;;)
3316         {
3317           if (addr + 2 * address_size > entry_end)
3318             {
3319               warning (_("Section .debug_aranges in %s entry at offset %zu "
3320                          "address list is not properly terminated, "
3321                          "ignoring .debug_aranges."),
3322                        objfile_name (objfile), entry_addr - section->buffer);
3323               return;
3324             }
3325           ULONGEST start = extract_unsigned_integer (addr, address_size,
3326                                                      dwarf5_byte_order);
3327           addr += address_size;
3328           ULONGEST length = extract_unsigned_integer (addr, address_size,
3329                                                       dwarf5_byte_order);
3330           addr += address_size;
3331           if (start == 0 && length == 0)
3332             break;
3333           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3334             {
3335               /* Symbol was eliminated due to a COMDAT group.  */
3336               continue;
3337             }
3338           ULONGEST end = start + length;
3339           start = (gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr)
3340                    - baseaddr);
3341           end = (gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr)
3342                  - baseaddr);
3343           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3344         }
3345     }
3346
3347   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3348                                                     &objfile->objfile_obstack);
3349 }
3350
3351 /* Find a slot in the mapped index INDEX for the object named NAME.
3352    If NAME is found, set *VEC_OUT to point to the CU vector in the
3353    constant pool and return true.  If NAME cannot be found, return
3354    false.  */
3355
3356 static bool
3357 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3358                           offset_type **vec_out)
3359 {
3360   offset_type hash;
3361   offset_type slot, step;
3362   int (*cmp) (const char *, const char *);
3363
3364   gdb::unique_xmalloc_ptr<char> without_params;
3365   if (current_language->la_language == language_cplus
3366       || current_language->la_language == language_fortran
3367       || current_language->la_language == language_d)
3368     {
3369       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3370          not contain any.  */
3371
3372       if (strchr (name, '(') != NULL)
3373         {
3374           without_params = cp_remove_params (name);
3375
3376           if (without_params != NULL)
3377             name = without_params.get ();
3378         }
3379     }
3380
3381   /* Index version 4 did not support case insensitive searches.  But the
3382      indices for case insensitive languages are built in lowercase, therefore
3383      simulate our NAME being searched is also lowercased.  */
3384   hash = mapped_index_string_hash ((index->version == 4
3385                                     && case_sensitivity == case_sensitive_off
3386                                     ? 5 : index->version),
3387                                    name);
3388
3389   slot = hash & (index->symbol_table.size () - 1);
3390   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3391   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3392
3393   for (;;)
3394     {
3395       const char *str;
3396
3397       const auto &bucket = index->symbol_table[slot];
3398       if (bucket.name == 0 && bucket.vec == 0)
3399         return false;
3400
3401       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3402       if (!cmp (name, str))
3403         {
3404           *vec_out = (offset_type *) (index->constant_pool
3405                                       + MAYBE_SWAP (bucket.vec));
3406           return true;
3407         }
3408
3409       slot = (slot + step) & (index->symbol_table.size () - 1);
3410     }
3411 }
3412
3413 /* A helper function that reads the .gdb_index from BUFFER and fills
3414    in MAP.  FILENAME is the name of the file containing the data;
3415    it is used for error reporting.  DEPRECATED_OK is true if it is
3416    ok to use deprecated sections.
3417
3418    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3419    out parameters that are filled in with information about the CU and
3420    TU lists in the section.
3421
3422    Returns true if all went well, false otherwise.  */
3423
3424 static bool
3425 read_gdb_index_from_buffer (struct objfile *objfile,
3426                             const char *filename,
3427                             bool deprecated_ok,
3428                             gdb::array_view<const gdb_byte> buffer,
3429                             struct mapped_index *map,
3430                             const gdb_byte **cu_list,
3431                             offset_type *cu_list_elements,
3432                             const gdb_byte **types_list,
3433                             offset_type *types_list_elements)
3434 {
3435   const gdb_byte *addr = &buffer[0];
3436
3437   /* Version check.  */
3438   offset_type version = MAYBE_SWAP (*(offset_type *) addr);
3439   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3440      causes the index to behave very poorly for certain requests.  Version 3
3441      contained incomplete addrmap.  So, it seems better to just ignore such
3442      indices.  */
3443   if (version < 4)
3444     {
3445       static int warning_printed = 0;
3446       if (!warning_printed)
3447         {
3448           warning (_("Skipping obsolete .gdb_index section in %s."),
3449                    filename);
3450           warning_printed = 1;
3451         }
3452       return 0;
3453     }
3454   /* Index version 4 uses a different hash function than index version
3455      5 and later.
3456
3457      Versions earlier than 6 did not emit psymbols for inlined
3458      functions.  Using these files will cause GDB not to be able to
3459      set breakpoints on inlined functions by name, so we ignore these
3460      indices unless the user has done
3461      "set use-deprecated-index-sections on".  */
3462   if (version < 6 && !deprecated_ok)
3463     {
3464       static int warning_printed = 0;
3465       if (!warning_printed)
3466         {
3467           warning (_("\
3468 Skipping deprecated .gdb_index section in %s.\n\
3469 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3470 to use the section anyway."),
3471                    filename);
3472           warning_printed = 1;
3473         }
3474       return 0;
3475     }
3476   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3477      of the TU (for symbols coming from TUs),
3478      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3479      Plus gold-generated indices can have duplicate entries for global symbols,
3480      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3481      These are just performance bugs, and we can't distinguish gdb-generated
3482      indices from gold-generated ones, so issue no warning here.  */
3483
3484   /* Indexes with higher version than the one supported by GDB may be no
3485      longer backward compatible.  */
3486   if (version > 8)
3487     return 0;
3488
3489   map->version = version;
3490
3491   offset_type *metadata = (offset_type *) (addr + sizeof (offset_type));
3492
3493   int i = 0;
3494   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3495   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3496                        / 8);
3497   ++i;
3498
3499   *types_list = addr + MAYBE_SWAP (metadata[i]);
3500   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3501                            - MAYBE_SWAP (metadata[i]))
3502                           / 8);
3503   ++i;
3504
3505   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3506   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3507   map->address_table
3508     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3509   ++i;
3510
3511   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3512   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3513   map->symbol_table
3514     = gdb::array_view<mapped_index::symbol_table_slot>
3515        ((mapped_index::symbol_table_slot *) symbol_table,
3516         (mapped_index::symbol_table_slot *) symbol_table_end);
3517
3518   ++i;
3519   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3520
3521   return 1;
3522 }
3523
3524 /* Callback types for dwarf2_read_gdb_index.  */
3525
3526 typedef gdb::function_view
3527     <gdb::array_view<const gdb_byte>(objfile *, dwarf2_per_objfile *)>
3528     get_gdb_index_contents_ftype;
3529 typedef gdb::function_view
3530     <gdb::array_view<const gdb_byte>(objfile *, dwz_file *)>
3531     get_gdb_index_contents_dwz_ftype;
3532
3533 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3534    elements of all the CUs and return 1.  Otherwise, return 0.  */
3535
3536 static int
3537 dwarf2_read_gdb_index
3538   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3539    get_gdb_index_contents_ftype get_gdb_index_contents,
3540    get_gdb_index_contents_dwz_ftype get_gdb_index_contents_dwz)
3541 {
3542   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3543   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3544   struct dwz_file *dwz;
3545   struct objfile *objfile = dwarf2_per_objfile->objfile;
3546
3547   gdb::array_view<const gdb_byte> main_index_contents
3548     = get_gdb_index_contents (objfile, dwarf2_per_objfile);
3549
3550   if (main_index_contents.empty ())
3551     return 0;
3552
3553   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3554   if (!read_gdb_index_from_buffer (objfile, objfile_name (objfile),
3555                                    use_deprecated_index_sections,
3556                                    main_index_contents, map.get (), &cu_list,
3557                                    &cu_list_elements, &types_list,
3558                                    &types_list_elements))
3559     return 0;
3560
3561   /* Don't use the index if it's empty.  */
3562   if (map->symbol_table.empty ())
3563     return 0;
3564
3565   /* If there is a .dwz file, read it so we can get its CU list as
3566      well.  */
3567   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3568   if (dwz != NULL)
3569     {
3570       struct mapped_index dwz_map;
3571       const gdb_byte *dwz_types_ignore;
3572       offset_type dwz_types_elements_ignore;
3573
3574       gdb::array_view<const gdb_byte> dwz_index_content
3575         = get_gdb_index_contents_dwz (objfile, dwz);
3576
3577       if (dwz_index_content.empty ())
3578         return 0;
3579
3580       if (!read_gdb_index_from_buffer (objfile,
3581                                        bfd_get_filename (dwz->dwz_bfd), 1,
3582                                        dwz_index_content, &dwz_map,
3583                                        &dwz_list, &dwz_list_elements,
3584                                        &dwz_types_ignore,
3585                                        &dwz_types_elements_ignore))
3586         {
3587           warning (_("could not read '.gdb_index' section from %s; skipping"),
3588                    bfd_get_filename (dwz->dwz_bfd));
3589           return 0;
3590         }
3591     }
3592
3593   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3594                          dwz_list, dwz_list_elements);
3595
3596   if (types_list_elements)
3597     {
3598       struct dwarf2_section_info *section;
3599
3600       /* We can only handle a single .debug_types when we have an
3601          index.  */
3602       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3603         return 0;
3604
3605       section = VEC_index (dwarf2_section_info_def,
3606                            dwarf2_per_objfile->types, 0);
3607
3608       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3609                                                types_list, types_list_elements);
3610     }
3611
3612   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3613
3614   dwarf2_per_objfile->index_table = std::move (map);
3615   dwarf2_per_objfile->using_index = 1;
3616   dwarf2_per_objfile->quick_file_names_table =
3617     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3618
3619   return 1;
3620 }
3621
3622 /* die_reader_func for dw2_get_file_names.  */
3623
3624 static void
3625 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3626                            const gdb_byte *info_ptr,
3627                            struct die_info *comp_unit_die,
3628                            int has_children,
3629                            void *data)
3630 {
3631   struct dwarf2_cu *cu = reader->cu;
3632   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3633   struct dwarf2_per_objfile *dwarf2_per_objfile
3634     = cu->per_cu->dwarf2_per_objfile;
3635   struct objfile *objfile = dwarf2_per_objfile->objfile;
3636   struct dwarf2_per_cu_data *lh_cu;
3637   struct attribute *attr;
3638   int i;
3639   void **slot;
3640   struct quick_file_names *qfn;
3641
3642   gdb_assert (! this_cu->is_debug_types);
3643
3644   /* Our callers never want to match partial units -- instead they
3645      will match the enclosing full CU.  */
3646   if (comp_unit_die->tag == DW_TAG_partial_unit)
3647     {
3648       this_cu->v.quick->no_file_data = 1;
3649       return;
3650     }
3651
3652   lh_cu = this_cu;
3653   slot = NULL;
3654
3655   line_header_up lh;
3656   sect_offset line_offset {};
3657
3658   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3659   if (attr)
3660     {
3661       struct quick_file_names find_entry;
3662
3663       line_offset = (sect_offset) DW_UNSND (attr);
3664
3665       /* We may have already read in this line header (TU line header sharing).
3666          If we have we're done.  */
3667       find_entry.hash.dwo_unit = cu->dwo_unit;
3668       find_entry.hash.line_sect_off = line_offset;
3669       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3670                              &find_entry, INSERT);
3671       if (*slot != NULL)
3672         {
3673           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3674           return;
3675         }
3676
3677       lh = dwarf_decode_line_header (line_offset, cu);
3678     }
3679   if (lh == NULL)
3680     {
3681       lh_cu->v.quick->no_file_data = 1;
3682       return;
3683     }
3684
3685   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3686   qfn->hash.dwo_unit = cu->dwo_unit;
3687   qfn->hash.line_sect_off = line_offset;
3688   gdb_assert (slot != NULL);
3689   *slot = qfn;
3690
3691   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3692
3693   qfn->num_file_names = lh->file_names.size ();
3694   qfn->file_names =
3695     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3696   for (i = 0; i < lh->file_names.size (); ++i)
3697     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3698   qfn->real_names = NULL;
3699
3700   lh_cu->v.quick->file_names = qfn;
3701 }
3702
3703 /* A helper for the "quick" functions which attempts to read the line
3704    table for THIS_CU.  */
3705
3706 static struct quick_file_names *
3707 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3708 {
3709   /* This should never be called for TUs.  */
3710   gdb_assert (! this_cu->is_debug_types);
3711   /* Nor type unit groups.  */
3712   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3713
3714   if (this_cu->v.quick->file_names != NULL)
3715     return this_cu->v.quick->file_names;
3716   /* If we know there is no line data, no point in looking again.  */
3717   if (this_cu->v.quick->no_file_data)
3718     return NULL;
3719
3720   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3721
3722   if (this_cu->v.quick->no_file_data)
3723     return NULL;
3724   return this_cu->v.quick->file_names;
3725 }
3726
3727 /* A helper for the "quick" functions which computes and caches the
3728    real path for a given file name from the line table.  */
3729
3730 static const char *
3731 dw2_get_real_path (struct objfile *objfile,
3732                    struct quick_file_names *qfn, int index)
3733 {
3734   if (qfn->real_names == NULL)
3735     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3736                                       qfn->num_file_names, const char *);
3737
3738   if (qfn->real_names[index] == NULL)
3739     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3740
3741   return qfn->real_names[index];
3742 }
3743
3744 static struct symtab *
3745 dw2_find_last_source_symtab (struct objfile *objfile)
3746 {
3747   struct dwarf2_per_objfile *dwarf2_per_objfile
3748     = get_dwarf2_per_objfile (objfile);
3749   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3750   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3751
3752   if (cust == NULL)
3753     return NULL;
3754
3755   return compunit_primary_filetab (cust);
3756 }
3757
3758 /* Traversal function for dw2_forget_cached_source_info.  */
3759
3760 static int
3761 dw2_free_cached_file_names (void **slot, void *info)
3762 {
3763   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3764
3765   if (file_data->real_names)
3766     {
3767       int i;
3768
3769       for (i = 0; i < file_data->num_file_names; ++i)
3770         {
3771           xfree ((void*) file_data->real_names[i]);
3772           file_data->real_names[i] = NULL;
3773         }
3774     }
3775
3776   return 1;
3777 }
3778
3779 static void
3780 dw2_forget_cached_source_info (struct objfile *objfile)
3781 {
3782   struct dwarf2_per_objfile *dwarf2_per_objfile
3783     = get_dwarf2_per_objfile (objfile);
3784
3785   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3786                           dw2_free_cached_file_names, NULL);
3787 }
3788
3789 /* Helper function for dw2_map_symtabs_matching_filename that expands
3790    the symtabs and calls the iterator.  */
3791
3792 static int
3793 dw2_map_expand_apply (struct objfile *objfile,
3794                       struct dwarf2_per_cu_data *per_cu,
3795                       const char *name, const char *real_path,
3796                       gdb::function_view<bool (symtab *)> callback)
3797 {
3798   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3799
3800   /* Don't visit already-expanded CUs.  */
3801   if (per_cu->v.quick->compunit_symtab)
3802     return 0;
3803
3804   /* This may expand more than one symtab, and we want to iterate over
3805      all of them.  */
3806   dw2_instantiate_symtab (per_cu, false);
3807
3808   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3809                                     last_made, callback);
3810 }
3811
3812 /* Implementation of the map_symtabs_matching_filename method.  */
3813
3814 static bool
3815 dw2_map_symtabs_matching_filename
3816   (struct objfile *objfile, const char *name, const char *real_path,
3817    gdb::function_view<bool (symtab *)> callback)
3818 {
3819   const char *name_basename = lbasename (name);
3820   struct dwarf2_per_objfile *dwarf2_per_objfile
3821     = get_dwarf2_per_objfile (objfile);
3822
3823   /* The rule is CUs specify all the files, including those used by
3824      any TU, so there's no need to scan TUs here.  */
3825
3826   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3827     {
3828       /* We only need to look at symtabs not already expanded.  */
3829       if (per_cu->v.quick->compunit_symtab)
3830         continue;
3831
3832       quick_file_names *file_data = dw2_get_file_names (per_cu);
3833       if (file_data == NULL)
3834         continue;
3835
3836       for (int j = 0; j < file_data->num_file_names; ++j)
3837         {
3838           const char *this_name = file_data->file_names[j];
3839           const char *this_real_name;
3840
3841           if (compare_filenames_for_search (this_name, name))
3842             {
3843               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3844                                         callback))
3845                 return true;
3846               continue;
3847             }
3848
3849           /* Before we invoke realpath, which can get expensive when many
3850              files are involved, do a quick comparison of the basenames.  */
3851           if (! basenames_may_differ
3852               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3853             continue;
3854
3855           this_real_name = dw2_get_real_path (objfile, file_data, j);
3856           if (compare_filenames_for_search (this_real_name, name))
3857             {
3858               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3859                                         callback))
3860                 return true;
3861               continue;
3862             }
3863
3864           if (real_path != NULL)
3865             {
3866               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3867               gdb_assert (IS_ABSOLUTE_PATH (name));
3868               if (this_real_name != NULL
3869                   && FILENAME_CMP (real_path, this_real_name) == 0)
3870                 {
3871                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3872                                             callback))
3873                     return true;
3874                   continue;
3875                 }
3876             }
3877         }
3878     }
3879
3880   return false;
3881 }
3882
3883 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3884
3885 struct dw2_symtab_iterator
3886 {
3887   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3888   struct dwarf2_per_objfile *dwarf2_per_objfile;
3889   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3890   int want_specific_block;
3891   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3892      Unused if !WANT_SPECIFIC_BLOCK.  */
3893   int block_index;
3894   /* The kind of symbol we're looking for.  */
3895   domain_enum domain;
3896   /* The list of CUs from the index entry of the symbol,
3897      or NULL if not found.  */
3898   offset_type *vec;
3899   /* The next element in VEC to look at.  */
3900   int next;
3901   /* The number of elements in VEC, or zero if there is no match.  */
3902   int length;
3903   /* Have we seen a global version of the symbol?
3904      If so we can ignore all further global instances.
3905      This is to work around gold/15646, inefficient gold-generated
3906      indices.  */
3907   int global_seen;
3908 };
3909
3910 /* Initialize the index symtab iterator ITER.
3911    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3912    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3913
3914 static void
3915 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3916                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3917                       int want_specific_block,
3918                       int block_index,
3919                       domain_enum domain,
3920                       const char *name)
3921 {
3922   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3923   iter->want_specific_block = want_specific_block;
3924   iter->block_index = block_index;
3925   iter->domain = domain;
3926   iter->next = 0;
3927   iter->global_seen = 0;
3928
3929   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3930
3931   /* index is NULL if OBJF_READNOW.  */
3932   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3933     iter->length = MAYBE_SWAP (*iter->vec);
3934   else
3935     {
3936       iter->vec = NULL;
3937       iter->length = 0;
3938     }
3939 }
3940
3941 /* Return the next matching CU or NULL if there are no more.  */
3942
3943 static struct dwarf2_per_cu_data *
3944 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3945 {
3946   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3947
3948   for ( ; iter->next < iter->length; ++iter->next)
3949     {
3950       offset_type cu_index_and_attrs =
3951         MAYBE_SWAP (iter->vec[iter->next + 1]);
3952       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3953       int want_static = iter->block_index != GLOBAL_BLOCK;
3954       /* This value is only valid for index versions >= 7.  */
3955       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3956       gdb_index_symbol_kind symbol_kind =
3957         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3958       /* Only check the symbol attributes if they're present.
3959          Indices prior to version 7 don't record them,
3960          and indices >= 7 may elide them for certain symbols
3961          (gold does this).  */
3962       int attrs_valid =
3963         (dwarf2_per_objfile->index_table->version >= 7
3964          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3965
3966       /* Don't crash on bad data.  */
3967       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3968                        + dwarf2_per_objfile->all_type_units.size ()))
3969         {
3970           complaint (_(".gdb_index entry has bad CU index"
3971                        " [in module %s]"),
3972                      objfile_name (dwarf2_per_objfile->objfile));
3973           continue;
3974         }
3975
3976       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3977
3978       /* Skip if already read in.  */
3979       if (per_cu->v.quick->compunit_symtab)
3980         continue;
3981
3982       /* Check static vs global.  */
3983       if (attrs_valid)
3984         {
3985           if (iter->want_specific_block
3986               && want_static != is_static)
3987             continue;
3988           /* Work around gold/15646.  */
3989           if (!is_static && iter->global_seen)
3990             continue;
3991           if (!is_static)
3992             iter->global_seen = 1;
3993         }
3994
3995       /* Only check the symbol's kind if it has one.  */
3996       if (attrs_valid)
3997         {
3998           switch (iter->domain)
3999             {
4000             case VAR_DOMAIN:
4001               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
4002                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
4003                   /* Some types are also in VAR_DOMAIN.  */
4004                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4005                 continue;
4006               break;
4007             case STRUCT_DOMAIN:
4008               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4009                 continue;
4010               break;
4011             case LABEL_DOMAIN:
4012               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
4013                 continue;
4014               break;
4015             default:
4016               break;
4017             }
4018         }
4019
4020       ++iter->next;
4021       return per_cu;
4022     }
4023
4024   return NULL;
4025 }
4026
4027 static struct compunit_symtab *
4028 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4029                    const char *name, domain_enum domain)
4030 {
4031   struct compunit_symtab *stab_best = NULL;
4032   struct dwarf2_per_objfile *dwarf2_per_objfile
4033     = get_dwarf2_per_objfile (objfile);
4034
4035   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4036
4037   struct dw2_symtab_iterator iter;
4038   struct dwarf2_per_cu_data *per_cu;
4039
4040   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4041
4042   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4043     {
4044       struct symbol *sym, *with_opaque = NULL;
4045       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
4046       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4047       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4048
4049       sym = block_find_symbol (block, name, domain,
4050                                block_find_non_opaque_type_preferred,
4051                                &with_opaque);
4052
4053       /* Some caution must be observed with overloaded functions
4054          and methods, since the index will not contain any overload
4055          information (but NAME might contain it).  */
4056
4057       if (sym != NULL
4058           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4059         return stab;
4060       if (with_opaque != NULL
4061           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4062         stab_best = stab;
4063
4064       /* Keep looking through other CUs.  */
4065     }
4066
4067   return stab_best;
4068 }
4069
4070 static void
4071 dw2_print_stats (struct objfile *objfile)
4072 {
4073   struct dwarf2_per_objfile *dwarf2_per_objfile
4074     = get_dwarf2_per_objfile (objfile);
4075   int total = (dwarf2_per_objfile->all_comp_units.size ()
4076                + dwarf2_per_objfile->all_type_units.size ());
4077   int count = 0;
4078
4079   for (int i = 0; i < total; ++i)
4080     {
4081       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4082
4083       if (!per_cu->v.quick->compunit_symtab)
4084         ++count;
4085     }
4086   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4087   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4088 }
4089
4090 /* This dumps minimal information about the index.
4091    It is called via "mt print objfiles".
4092    One use is to verify .gdb_index has been loaded by the
4093    gdb.dwarf2/gdb-index.exp testcase.  */
4094
4095 static void
4096 dw2_dump (struct objfile *objfile)
4097 {
4098   struct dwarf2_per_objfile *dwarf2_per_objfile
4099     = get_dwarf2_per_objfile (objfile);
4100
4101   gdb_assert (dwarf2_per_objfile->using_index);
4102   printf_filtered (".gdb_index:");
4103   if (dwarf2_per_objfile->index_table != NULL)
4104     {
4105       printf_filtered (" version %d\n",
4106                        dwarf2_per_objfile->index_table->version);
4107     }
4108   else
4109     printf_filtered (" faked for \"readnow\"\n");
4110   printf_filtered ("\n");
4111 }
4112
4113 static void
4114 dw2_expand_symtabs_for_function (struct objfile *objfile,
4115                                  const char *func_name)
4116 {
4117   struct dwarf2_per_objfile *dwarf2_per_objfile
4118     = get_dwarf2_per_objfile (objfile);
4119
4120   struct dw2_symtab_iterator iter;
4121   struct dwarf2_per_cu_data *per_cu;
4122
4123   /* Note: It doesn't matter what we pass for block_index here.  */
4124   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4125                         func_name);
4126
4127   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4128     dw2_instantiate_symtab (per_cu, false);
4129
4130 }
4131
4132 static void
4133 dw2_expand_all_symtabs (struct objfile *objfile)
4134 {
4135   struct dwarf2_per_objfile *dwarf2_per_objfile
4136     = get_dwarf2_per_objfile (objfile);
4137   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4138                      + dwarf2_per_objfile->all_type_units.size ());
4139
4140   for (int i = 0; i < total_units; ++i)
4141     {
4142       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4143
4144       /* We don't want to directly expand a partial CU, because if we
4145          read it with the wrong language, then assertion failures can
4146          be triggered later on.  See PR symtab/23010.  So, tell
4147          dw2_instantiate_symtab to skip partial CUs -- any important
4148          partial CU will be read via DW_TAG_imported_unit anyway.  */
4149       dw2_instantiate_symtab (per_cu, true);
4150     }
4151 }
4152
4153 static void
4154 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4155                                   const char *fullname)
4156 {
4157   struct dwarf2_per_objfile *dwarf2_per_objfile
4158     = get_dwarf2_per_objfile (objfile);
4159
4160   /* We don't need to consider type units here.
4161      This is only called for examining code, e.g. expand_line_sal.
4162      There can be an order of magnitude (or more) more type units
4163      than comp units, and we avoid them if we can.  */
4164
4165   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4166     {
4167       /* We only need to look at symtabs not already expanded.  */
4168       if (per_cu->v.quick->compunit_symtab)
4169         continue;
4170
4171       quick_file_names *file_data = dw2_get_file_names (per_cu);
4172       if (file_data == NULL)
4173         continue;
4174
4175       for (int j = 0; j < file_data->num_file_names; ++j)
4176         {
4177           const char *this_fullname = file_data->file_names[j];
4178
4179           if (filename_cmp (this_fullname, fullname) == 0)
4180             {
4181               dw2_instantiate_symtab (per_cu, false);
4182               break;
4183             }
4184         }
4185     }
4186 }
4187
4188 static void
4189 dw2_map_matching_symbols (struct objfile *objfile,
4190                           const char * name, domain_enum domain,
4191                           int global,
4192                           int (*callback) (struct block *,
4193                                            struct symbol *, void *),
4194                           void *data, symbol_name_match_type match,
4195                           symbol_compare_ftype *ordered_compare)
4196 {
4197   /* Currently unimplemented; used for Ada.  The function can be called if the
4198      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4199      does not look for non-Ada symbols this function should just return.  */
4200 }
4201
4202 /* Symbol name matcher for .gdb_index names.
4203
4204    Symbol names in .gdb_index have a few particularities:
4205
4206    - There's no indication of which is the language of each symbol.
4207
4208      Since each language has its own symbol name matching algorithm,
4209      and we don't know which language is the right one, we must match
4210      each symbol against all languages.  This would be a potential
4211      performance problem if it were not mitigated by the
4212      mapped_index::name_components lookup table, which significantly
4213      reduces the number of times we need to call into this matcher,
4214      making it a non-issue.
4215
4216    - Symbol names in the index have no overload (parameter)
4217      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4218      appear as "foo" in the index, for example.
4219
4220      This means that the lookup names passed to the symbol name
4221      matcher functions must have no parameter information either
4222      because (e.g.) symbol search name "foo" does not match
4223      lookup-name "foo(int)" [while swapping search name for lookup
4224      name would match].
4225 */
4226 class gdb_index_symbol_name_matcher
4227 {
4228 public:
4229   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4230   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4231
4232   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4233      Returns true if any matcher matches.  */
4234   bool matches (const char *symbol_name);
4235
4236 private:
4237   /* A reference to the lookup name we're matching against.  */
4238   const lookup_name_info &m_lookup_name;
4239
4240   /* A vector holding all the different symbol name matchers, for all
4241      languages.  */
4242   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4243 };
4244
4245 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4246   (const lookup_name_info &lookup_name)
4247     : m_lookup_name (lookup_name)
4248 {
4249   /* Prepare the vector of comparison functions upfront, to avoid
4250      doing the same work for each symbol.  Care is taken to avoid
4251      matching with the same matcher more than once if/when multiple
4252      languages use the same matcher function.  */
4253   auto &matchers = m_symbol_name_matcher_funcs;
4254   matchers.reserve (nr_languages);
4255
4256   matchers.push_back (default_symbol_name_matcher);
4257
4258   for (int i = 0; i < nr_languages; i++)
4259     {
4260       const language_defn *lang = language_def ((enum language) i);
4261       symbol_name_matcher_ftype *name_matcher
4262         = get_symbol_name_matcher (lang, m_lookup_name);
4263
4264       /* Don't insert the same comparison routine more than once.
4265          Note that we do this linear walk instead of a seemingly
4266          cheaper sorted insert, or use a std::set or something like
4267          that, because relative order of function addresses is not
4268          stable.  This is not a problem in practice because the number
4269          of supported languages is low, and the cost here is tiny
4270          compared to the number of searches we'll do afterwards using
4271          this object.  */
4272       if (name_matcher != default_symbol_name_matcher
4273           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4274               == matchers.end ()))
4275         matchers.push_back (name_matcher);
4276     }
4277 }
4278
4279 bool
4280 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4281 {
4282   for (auto matches_name : m_symbol_name_matcher_funcs)
4283     if (matches_name (symbol_name, m_lookup_name, NULL))
4284       return true;
4285
4286   return false;
4287 }
4288
4289 /* Starting from a search name, return the string that finds the upper
4290    bound of all strings that start with SEARCH_NAME in a sorted name
4291    list.  Returns the empty string to indicate that the upper bound is
4292    the end of the list.  */
4293
4294 static std::string
4295 make_sort_after_prefix_name (const char *search_name)
4296 {
4297   /* When looking to complete "func", we find the upper bound of all
4298      symbols that start with "func" by looking for where we'd insert
4299      the closest string that would follow "func" in lexicographical
4300      order.  Usually, that's "func"-with-last-character-incremented,
4301      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4302      will be UTF-8 multi-byte sequences, but we can't be certain.
4303      Especially mind the 0xff character, which is a valid character in
4304      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4305      rule out compilers allowing it in identifiers.  Note that
4306      conveniently, strcmp/strcasecmp are specified to compare
4307      characters interpreted as unsigned char.  So what we do is treat
4308      the whole string as a base 256 number composed of a sequence of
4309      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4310      to 0, and carries 1 to the following more-significant position.
4311      If the very first character in SEARCH_NAME ends up incremented
4312      and carries/overflows, then the upper bound is the end of the
4313      list.  The string after the empty string is also the empty
4314      string.
4315
4316      Some examples of this operation:
4317
4318        SEARCH_NAME  => "+1" RESULT
4319
4320        "abc"              => "abd"
4321        "ab\xff"           => "ac"
4322        "\xff" "a" "\xff"  => "\xff" "b"
4323        "\xff"             => ""
4324        "\xff\xff"         => ""
4325        ""                 => ""
4326
4327      Then, with these symbols for example:
4328
4329       func
4330       func1
4331       fund
4332
4333      completing "func" looks for symbols between "func" and
4334      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4335      which finds "func" and "func1", but not "fund".
4336
4337      And with:
4338
4339       funcÿ     (Latin1 'ÿ' [0xff])
4340       funcÿ1
4341       fund
4342
4343      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4344      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4345
4346      And with:
4347
4348       ÿÿ        (Latin1 'ÿ' [0xff])
4349       ÿÿ1
4350
4351      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4352      the end of the list.
4353   */
4354   std::string after = search_name;
4355   while (!after.empty () && (unsigned char) after.back () == 0xff)
4356     after.pop_back ();
4357   if (!after.empty ())
4358     after.back () = (unsigned char) after.back () + 1;
4359   return after;
4360 }
4361
4362 /* See declaration.  */
4363
4364 std::pair<std::vector<name_component>::const_iterator,
4365           std::vector<name_component>::const_iterator>
4366 mapped_index_base::find_name_components_bounds
4367   (const lookup_name_info &lookup_name_without_params) const
4368 {
4369   auto *name_cmp
4370     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4371
4372   const char *cplus
4373     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4374
4375   /* Comparison function object for lower_bound that matches against a
4376      given symbol name.  */
4377   auto lookup_compare_lower = [&] (const name_component &elem,
4378                                    const char *name)
4379     {
4380       const char *elem_qualified = this->symbol_name_at (elem.idx);
4381       const char *elem_name = elem_qualified + elem.name_offset;
4382       return name_cmp (elem_name, name) < 0;
4383     };
4384
4385   /* Comparison function object for upper_bound that matches against a
4386      given symbol name.  */
4387   auto lookup_compare_upper = [&] (const char *name,
4388                                    const name_component &elem)
4389     {
4390       const char *elem_qualified = this->symbol_name_at (elem.idx);
4391       const char *elem_name = elem_qualified + elem.name_offset;
4392       return name_cmp (name, elem_name) < 0;
4393     };
4394
4395   auto begin = this->name_components.begin ();
4396   auto end = this->name_components.end ();
4397
4398   /* Find the lower bound.  */
4399   auto lower = [&] ()
4400     {
4401       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4402         return begin;
4403       else
4404         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4405     } ();
4406
4407   /* Find the upper bound.  */
4408   auto upper = [&] ()
4409     {
4410       if (lookup_name_without_params.completion_mode ())
4411         {
4412           /* In completion mode, we want UPPER to point past all
4413              symbols names that have the same prefix.  I.e., with
4414              these symbols, and completing "func":
4415
4416               function        << lower bound
4417               function1
4418               other_function  << upper bound
4419
4420              We find the upper bound by looking for the insertion
4421              point of "func"-with-last-character-incremented,
4422              i.e. "fund".  */
4423           std::string after = make_sort_after_prefix_name (cplus);
4424           if (after.empty ())
4425             return end;
4426           return std::lower_bound (lower, end, after.c_str (),
4427                                    lookup_compare_lower);
4428         }
4429       else
4430         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4431     } ();
4432
4433   return {lower, upper};
4434 }
4435
4436 /* See declaration.  */
4437
4438 void
4439 mapped_index_base::build_name_components ()
4440 {
4441   if (!this->name_components.empty ())
4442     return;
4443
4444   this->name_components_casing = case_sensitivity;
4445   auto *name_cmp
4446     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4447
4448   /* The code below only knows how to break apart components of C++
4449      symbol names (and other languages that use '::' as
4450      namespace/module separator).  If we add support for wild matching
4451      to some language that uses some other operator (E.g., Ada, Go and
4452      D use '.'), then we'll need to try splitting the symbol name
4453      according to that language too.  Note that Ada does support wild
4454      matching, but doesn't currently support .gdb_index.  */
4455   auto count = this->symbol_name_count ();
4456   for (offset_type idx = 0; idx < count; idx++)
4457     {
4458       if (this->symbol_name_slot_invalid (idx))
4459         continue;
4460
4461       const char *name = this->symbol_name_at (idx);
4462
4463       /* Add each name component to the name component table.  */
4464       unsigned int previous_len = 0;
4465       for (unsigned int current_len = cp_find_first_component (name);
4466            name[current_len] != '\0';
4467            current_len += cp_find_first_component (name + current_len))
4468         {
4469           gdb_assert (name[current_len] == ':');
4470           this->name_components.push_back ({previous_len, idx});
4471           /* Skip the '::'.  */
4472           current_len += 2;
4473           previous_len = current_len;
4474         }
4475       this->name_components.push_back ({previous_len, idx});
4476     }
4477
4478   /* Sort name_components elements by name.  */
4479   auto name_comp_compare = [&] (const name_component &left,
4480                                 const name_component &right)
4481     {
4482       const char *left_qualified = this->symbol_name_at (left.idx);
4483       const char *right_qualified = this->symbol_name_at (right.idx);
4484
4485       const char *left_name = left_qualified + left.name_offset;
4486       const char *right_name = right_qualified + right.name_offset;
4487
4488       return name_cmp (left_name, right_name) < 0;
4489     };
4490
4491   std::sort (this->name_components.begin (),
4492              this->name_components.end (),
4493              name_comp_compare);
4494 }
4495
4496 /* Helper for dw2_expand_symtabs_matching that works with a
4497    mapped_index_base instead of the containing objfile.  This is split
4498    to a separate function in order to be able to unit test the
4499    name_components matching using a mock mapped_index_base.  For each
4500    symbol name that matches, calls MATCH_CALLBACK, passing it the
4501    symbol's index in the mapped_index_base symbol table.  */
4502
4503 static void
4504 dw2_expand_symtabs_matching_symbol
4505   (mapped_index_base &index,
4506    const lookup_name_info &lookup_name_in,
4507    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4508    enum search_domain kind,
4509    gdb::function_view<void (offset_type)> match_callback)
4510 {
4511   lookup_name_info lookup_name_without_params
4512     = lookup_name_in.make_ignore_params ();
4513   gdb_index_symbol_name_matcher lookup_name_matcher
4514     (lookup_name_without_params);
4515
4516   /* Build the symbol name component sorted vector, if we haven't
4517      yet.  */
4518   index.build_name_components ();
4519
4520   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4521
4522   /* Now for each symbol name in range, check to see if we have a name
4523      match, and if so, call the MATCH_CALLBACK callback.  */
4524
4525   /* The same symbol may appear more than once in the range though.
4526      E.g., if we're looking for symbols that complete "w", and we have
4527      a symbol named "w1::w2", we'll find the two name components for
4528      that same symbol in the range.  To be sure we only call the
4529      callback once per symbol, we first collect the symbol name
4530      indexes that matched in a temporary vector and ignore
4531      duplicates.  */
4532   std::vector<offset_type> matches;
4533   matches.reserve (std::distance (bounds.first, bounds.second));
4534
4535   for (; bounds.first != bounds.second; ++bounds.first)
4536     {
4537       const char *qualified = index.symbol_name_at (bounds.first->idx);
4538
4539       if (!lookup_name_matcher.matches (qualified)
4540           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4541         continue;
4542
4543       matches.push_back (bounds.first->idx);
4544     }
4545
4546   std::sort (matches.begin (), matches.end ());
4547
4548   /* Finally call the callback, once per match.  */
4549   ULONGEST prev = -1;
4550   for (offset_type idx : matches)
4551     {
4552       if (prev != idx)
4553         {
4554           match_callback (idx);
4555           prev = idx;
4556         }
4557     }
4558
4559   /* Above we use a type wider than idx's for 'prev', since 0 and
4560      (offset_type)-1 are both possible values.  */
4561   static_assert (sizeof (prev) > sizeof (offset_type), "");
4562 }
4563
4564 #if GDB_SELF_TEST
4565
4566 namespace selftests { namespace dw2_expand_symtabs_matching {
4567
4568 /* A mock .gdb_index/.debug_names-like name index table, enough to
4569    exercise dw2_expand_symtabs_matching_symbol, which works with the
4570    mapped_index_base interface.  Builds an index from the symbol list
4571    passed as parameter to the constructor.  */
4572 class mock_mapped_index : public mapped_index_base
4573 {
4574 public:
4575   mock_mapped_index (gdb::array_view<const char *> symbols)
4576     : m_symbol_table (symbols)
4577   {}
4578
4579   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4580
4581   /* Return the number of names in the symbol table.  */
4582   size_t symbol_name_count () const override
4583   {
4584     return m_symbol_table.size ();
4585   }
4586
4587   /* Get the name of the symbol at IDX in the symbol table.  */
4588   const char *symbol_name_at (offset_type idx) const override
4589   {
4590     return m_symbol_table[idx];
4591   }
4592
4593 private:
4594   gdb::array_view<const char *> m_symbol_table;
4595 };
4596
4597 /* Convenience function that converts a NULL pointer to a "<null>"
4598    string, to pass to print routines.  */
4599
4600 static const char *
4601 string_or_null (const char *str)
4602 {
4603   return str != NULL ? str : "<null>";
4604 }
4605
4606 /* Check if a lookup_name_info built from
4607    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4608    index.  EXPECTED_LIST is the list of expected matches, in expected
4609    matching order.  If no match expected, then an empty list is
4610    specified.  Returns true on success.  On failure prints a warning
4611    indicating the file:line that failed, and returns false.  */
4612
4613 static bool
4614 check_match (const char *file, int line,
4615              mock_mapped_index &mock_index,
4616              const char *name, symbol_name_match_type match_type,
4617              bool completion_mode,
4618              std::initializer_list<const char *> expected_list)
4619 {
4620   lookup_name_info lookup_name (name, match_type, completion_mode);
4621
4622   bool matched = true;
4623
4624   auto mismatch = [&] (const char *expected_str,
4625                        const char *got)
4626   {
4627     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4628                "expected=\"%s\", got=\"%s\"\n"),
4629              file, line,
4630              (match_type == symbol_name_match_type::FULL
4631               ? "FULL" : "WILD"),
4632              name, string_or_null (expected_str), string_or_null (got));
4633     matched = false;
4634   };
4635
4636   auto expected_it = expected_list.begin ();
4637   auto expected_end = expected_list.end ();
4638
4639   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4640                                       NULL, ALL_DOMAIN,
4641                                       [&] (offset_type idx)
4642   {
4643     const char *matched_name = mock_index.symbol_name_at (idx);
4644     const char *expected_str
4645       = expected_it == expected_end ? NULL : *expected_it++;
4646
4647     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4648       mismatch (expected_str, matched_name);
4649   });
4650
4651   const char *expected_str
4652   = expected_it == expected_end ? NULL : *expected_it++;
4653   if (expected_str != NULL)
4654     mismatch (expected_str, NULL);
4655
4656   return matched;
4657 }
4658
4659 /* The symbols added to the mock mapped_index for testing (in
4660    canonical form).  */
4661 static const char *test_symbols[] = {
4662   "function",
4663   "std::bar",
4664   "std::zfunction",
4665   "std::zfunction2",
4666   "w1::w2",
4667   "ns::foo<char*>",
4668   "ns::foo<int>",
4669   "ns::foo<long>",
4670   "ns2::tmpl<int>::foo2",
4671   "(anonymous namespace)::A::B::C",
4672
4673   /* These are used to check that the increment-last-char in the
4674      matching algorithm for completion doesn't match "t1_fund" when
4675      completing "t1_func".  */
4676   "t1_func",
4677   "t1_func1",
4678   "t1_fund",
4679   "t1_fund1",
4680
4681   /* A UTF-8 name with multi-byte sequences to make sure that
4682      cp-name-parser understands this as a single identifier ("função"
4683      is "function" in PT).  */
4684   u8"u8função",
4685
4686   /* \377 (0xff) is Latin1 'ÿ'.  */
4687   "yfunc\377",
4688
4689   /* \377 (0xff) is Latin1 'ÿ'.  */
4690   "\377",
4691   "\377\377123",
4692
4693   /* A name with all sorts of complications.  Starts with "z" to make
4694      it easier for the completion tests below.  */
4695 #define Z_SYM_NAME \
4696   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4697     "::tuple<(anonymous namespace)::ui*, " \
4698     "std::default_delete<(anonymous namespace)::ui>, void>"
4699
4700   Z_SYM_NAME
4701 };
4702
4703 /* Returns true if the mapped_index_base::find_name_component_bounds
4704    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4705    in completion mode.  */
4706
4707 static bool
4708 check_find_bounds_finds (mapped_index_base &index,
4709                          const char *search_name,
4710                          gdb::array_view<const char *> expected_syms)
4711 {
4712   lookup_name_info lookup_name (search_name,
4713                                 symbol_name_match_type::FULL, true);
4714
4715   auto bounds = index.find_name_components_bounds (lookup_name);
4716
4717   size_t distance = std::distance (bounds.first, bounds.second);
4718   if (distance != expected_syms.size ())
4719     return false;
4720
4721   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4722     {
4723       auto nc_elem = bounds.first + exp_elem;
4724       const char *qualified = index.symbol_name_at (nc_elem->idx);
4725       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4726         return false;
4727     }
4728
4729   return true;
4730 }
4731
4732 /* Test the lower-level mapped_index::find_name_component_bounds
4733    method.  */
4734
4735 static void
4736 test_mapped_index_find_name_component_bounds ()
4737 {
4738   mock_mapped_index mock_index (test_symbols);
4739
4740   mock_index.build_name_components ();
4741
4742   /* Test the lower-level mapped_index::find_name_component_bounds
4743      method in completion mode.  */
4744   {
4745     static const char *expected_syms[] = {
4746       "t1_func",
4747       "t1_func1",
4748     };
4749
4750     SELF_CHECK (check_find_bounds_finds (mock_index,
4751                                          "t1_func", expected_syms));
4752   }
4753
4754   /* Check that the increment-last-char in the name matching algorithm
4755      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4756   {
4757     static const char *expected_syms1[] = {
4758       "\377",
4759       "\377\377123",
4760     };
4761     SELF_CHECK (check_find_bounds_finds (mock_index,
4762                                          "\377", expected_syms1));
4763
4764     static const char *expected_syms2[] = {
4765       "\377\377123",
4766     };
4767     SELF_CHECK (check_find_bounds_finds (mock_index,
4768                                          "\377\377", expected_syms2));
4769   }
4770 }
4771
4772 /* Test dw2_expand_symtabs_matching_symbol.  */
4773
4774 static void
4775 test_dw2_expand_symtabs_matching_symbol ()
4776 {
4777   mock_mapped_index mock_index (test_symbols);
4778
4779   /* We let all tests run until the end even if some fails, for debug
4780      convenience.  */
4781   bool any_mismatch = false;
4782
4783   /* Create the expected symbols list (an initializer_list).  Needed
4784      because lists have commas, and we need to pass them to CHECK,
4785      which is a macro.  */
4786 #define EXPECT(...) { __VA_ARGS__ }
4787
4788   /* Wrapper for check_match that passes down the current
4789      __FILE__/__LINE__.  */
4790 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4791   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4792                                 mock_index,                             \
4793                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4794                                 EXPECTED_LIST)
4795
4796   /* Identity checks.  */
4797   for (const char *sym : test_symbols)
4798     {
4799       /* Should be able to match all existing symbols.  */
4800       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4801                    EXPECT (sym));
4802
4803       /* Should be able to match all existing symbols with
4804          parameters.  */
4805       std::string with_params = std::string (sym) + "(int)";
4806       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4807                    EXPECT (sym));
4808
4809       /* Should be able to match all existing symbols with
4810          parameters and qualifiers.  */
4811       with_params = std::string (sym) + " ( int ) const";
4812       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4813                    EXPECT (sym));
4814
4815       /* This should really find sym, but cp-name-parser.y doesn't
4816          know about lvalue/rvalue qualifiers yet.  */
4817       with_params = std::string (sym) + " ( int ) &&";
4818       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4819                    {});
4820     }
4821
4822   /* Check that the name matching algorithm for completion doesn't get
4823      confused with Latin1 'ÿ' / 0xff.  */
4824   {
4825     static const char str[] = "\377";
4826     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4827                  EXPECT ("\377", "\377\377123"));
4828   }
4829
4830   /* Check that the increment-last-char in the matching algorithm for
4831      completion doesn't match "t1_fund" when completing "t1_func".  */
4832   {
4833     static const char str[] = "t1_func";
4834     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4835                  EXPECT ("t1_func", "t1_func1"));
4836   }
4837
4838   /* Check that completion mode works at each prefix of the expected
4839      symbol name.  */
4840   {
4841     static const char str[] = "function(int)";
4842     size_t len = strlen (str);
4843     std::string lookup;
4844
4845     for (size_t i = 1; i < len; i++)
4846       {
4847         lookup.assign (str, i);
4848         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4849                      EXPECT ("function"));
4850       }
4851   }
4852
4853   /* While "w" is a prefix of both components, the match function
4854      should still only be called once.  */
4855   {
4856     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4857                  EXPECT ("w1::w2"));
4858     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4859                  EXPECT ("w1::w2"));
4860   }
4861
4862   /* Same, with a "complicated" symbol.  */
4863   {
4864     static const char str[] = Z_SYM_NAME;
4865     size_t len = strlen (str);
4866     std::string lookup;
4867
4868     for (size_t i = 1; i < len; i++)
4869       {
4870         lookup.assign (str, i);
4871         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4872                      EXPECT (Z_SYM_NAME));
4873       }
4874   }
4875
4876   /* In FULL mode, an incomplete symbol doesn't match.  */
4877   {
4878     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4879                  {});
4880   }
4881
4882   /* A complete symbol with parameters matches any overload, since the
4883      index has no overload info.  */
4884   {
4885     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4886                  EXPECT ("std::zfunction", "std::zfunction2"));
4887     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4888                  EXPECT ("std::zfunction", "std::zfunction2"));
4889     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4890                  EXPECT ("std::zfunction", "std::zfunction2"));
4891   }
4892
4893   /* Check that whitespace is ignored appropriately.  A symbol with a
4894      template argument list. */
4895   {
4896     static const char expected[] = "ns::foo<int>";
4897     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4898                  EXPECT (expected));
4899     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4900                  EXPECT (expected));
4901   }
4902
4903   /* Check that whitespace is ignored appropriately.  A symbol with a
4904      template argument list that includes a pointer.  */
4905   {
4906     static const char expected[] = "ns::foo<char*>";
4907     /* Try both completion and non-completion modes.  */
4908     static const bool completion_mode[2] = {false, true};
4909     for (size_t i = 0; i < 2; i++)
4910       {
4911         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4912                      completion_mode[i], EXPECT (expected));
4913         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4914                      completion_mode[i], EXPECT (expected));
4915
4916         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4917                      completion_mode[i], EXPECT (expected));
4918         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4919                      completion_mode[i], EXPECT (expected));
4920       }
4921   }
4922
4923   {
4924     /* Check method qualifiers are ignored.  */
4925     static const char expected[] = "ns::foo<char*>";
4926     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4927                  symbol_name_match_type::FULL, true, EXPECT (expected));
4928     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4929                  symbol_name_match_type::FULL, true, EXPECT (expected));
4930     CHECK_MATCH ("foo < char * >  ( int ) const",
4931                  symbol_name_match_type::WILD, true, EXPECT (expected));
4932     CHECK_MATCH ("foo < char * >  ( int ) &&",
4933                  symbol_name_match_type::WILD, true, EXPECT (expected));
4934   }
4935
4936   /* Test lookup names that don't match anything.  */
4937   {
4938     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4939                  {});
4940
4941     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4942                  {});
4943   }
4944
4945   /* Some wild matching tests, exercising "(anonymous namespace)",
4946      which should not be confused with a parameter list.  */
4947   {
4948     static const char *syms[] = {
4949       "A::B::C",
4950       "B::C",
4951       "C",
4952       "A :: B :: C ( int )",
4953       "B :: C ( int )",
4954       "C ( int )",
4955     };
4956
4957     for (const char *s : syms)
4958       {
4959         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4960                      EXPECT ("(anonymous namespace)::A::B::C"));
4961       }
4962   }
4963
4964   {
4965     static const char expected[] = "ns2::tmpl<int>::foo2";
4966     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4967                  EXPECT (expected));
4968     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4969                  EXPECT (expected));
4970   }
4971
4972   SELF_CHECK (!any_mismatch);
4973
4974 #undef EXPECT
4975 #undef CHECK_MATCH
4976 }
4977
4978 static void
4979 run_test ()
4980 {
4981   test_mapped_index_find_name_component_bounds ();
4982   test_dw2_expand_symtabs_matching_symbol ();
4983 }
4984
4985 }} // namespace selftests::dw2_expand_symtabs_matching
4986
4987 #endif /* GDB_SELF_TEST */
4988
4989 /* If FILE_MATCHER is NULL or if PER_CU has
4990    dwarf2_per_cu_quick_data::MARK set (see
4991    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4992    EXPANSION_NOTIFY on it.  */
4993
4994 static void
4995 dw2_expand_symtabs_matching_one
4996   (struct dwarf2_per_cu_data *per_cu,
4997    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4998    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4999 {
5000   if (file_matcher == NULL || per_cu->v.quick->mark)
5001     {
5002       bool symtab_was_null
5003         = (per_cu->v.quick->compunit_symtab == NULL);
5004
5005       dw2_instantiate_symtab (per_cu, false);
5006
5007       if (expansion_notify != NULL
5008           && symtab_was_null
5009           && per_cu->v.quick->compunit_symtab != NULL)
5010         expansion_notify (per_cu->v.quick->compunit_symtab);
5011     }
5012 }
5013
5014 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5015    matched, to expand corresponding CUs that were marked.  IDX is the
5016    index of the symbol name that matched.  */
5017
5018 static void
5019 dw2_expand_marked_cus
5020   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5021    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5022    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5023    search_domain kind)
5024 {
5025   offset_type *vec, vec_len, vec_idx;
5026   bool global_seen = false;
5027   mapped_index &index = *dwarf2_per_objfile->index_table;
5028
5029   vec = (offset_type *) (index.constant_pool
5030                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5031   vec_len = MAYBE_SWAP (vec[0]);
5032   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5033     {
5034       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5035       /* This value is only valid for index versions >= 7.  */
5036       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5037       gdb_index_symbol_kind symbol_kind =
5038         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5039       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5040       /* Only check the symbol attributes if they're present.
5041          Indices prior to version 7 don't record them,
5042          and indices >= 7 may elide them for certain symbols
5043          (gold does this).  */
5044       int attrs_valid =
5045         (index.version >= 7
5046          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5047
5048       /* Work around gold/15646.  */
5049       if (attrs_valid)
5050         {
5051           if (!is_static && global_seen)
5052             continue;
5053           if (!is_static)
5054             global_seen = true;
5055         }
5056
5057       /* Only check the symbol's kind if it has one.  */
5058       if (attrs_valid)
5059         {
5060           switch (kind)
5061             {
5062             case VARIABLES_DOMAIN:
5063               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5064                 continue;
5065               break;
5066             case FUNCTIONS_DOMAIN:
5067               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5068                 continue;
5069               break;
5070             case TYPES_DOMAIN:
5071               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5072                 continue;
5073               break;
5074             default:
5075               break;
5076             }
5077         }
5078
5079       /* Don't crash on bad data.  */
5080       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5081                        + dwarf2_per_objfile->all_type_units.size ()))
5082         {
5083           complaint (_(".gdb_index entry has bad CU index"
5084                        " [in module %s]"),
5085                        objfile_name (dwarf2_per_objfile->objfile));
5086           continue;
5087         }
5088
5089       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5090       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5091                                        expansion_notify);
5092     }
5093 }
5094
5095 /* If FILE_MATCHER is non-NULL, set all the
5096    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5097    that match FILE_MATCHER.  */
5098
5099 static void
5100 dw_expand_symtabs_matching_file_matcher
5101   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5102    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5103 {
5104   if (file_matcher == NULL)
5105     return;
5106
5107   objfile *const objfile = dwarf2_per_objfile->objfile;
5108
5109   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5110                                             htab_eq_pointer,
5111                                             NULL, xcalloc, xfree));
5112   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5113                                                 htab_eq_pointer,
5114                                                 NULL, xcalloc, xfree));
5115
5116   /* The rule is CUs specify all the files, including those used by
5117      any TU, so there's no need to scan TUs here.  */
5118
5119   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5120     {
5121       QUIT;
5122
5123       per_cu->v.quick->mark = 0;
5124
5125       /* We only need to look at symtabs not already expanded.  */
5126       if (per_cu->v.quick->compunit_symtab)
5127         continue;
5128
5129       quick_file_names *file_data = dw2_get_file_names (per_cu);
5130       if (file_data == NULL)
5131         continue;
5132
5133       if (htab_find (visited_not_found.get (), file_data) != NULL)
5134         continue;
5135       else if (htab_find (visited_found.get (), file_data) != NULL)
5136         {
5137           per_cu->v.quick->mark = 1;
5138           continue;
5139         }
5140
5141       for (int j = 0; j < file_data->num_file_names; ++j)
5142         {
5143           const char *this_real_name;
5144
5145           if (file_matcher (file_data->file_names[j], false))
5146             {
5147               per_cu->v.quick->mark = 1;
5148               break;
5149             }
5150
5151           /* Before we invoke realpath, which can get expensive when many
5152              files are involved, do a quick comparison of the basenames.  */
5153           if (!basenames_may_differ
5154               && !file_matcher (lbasename (file_data->file_names[j]),
5155                                 true))
5156             continue;
5157
5158           this_real_name = dw2_get_real_path (objfile, file_data, j);
5159           if (file_matcher (this_real_name, false))
5160             {
5161               per_cu->v.quick->mark = 1;
5162               break;
5163             }
5164         }
5165
5166       void **slot = htab_find_slot (per_cu->v.quick->mark
5167                                     ? visited_found.get ()
5168                                     : visited_not_found.get (),
5169                                     file_data, INSERT);
5170       *slot = file_data;
5171     }
5172 }
5173
5174 static void
5175 dw2_expand_symtabs_matching
5176   (struct objfile *objfile,
5177    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5178    const lookup_name_info &lookup_name,
5179    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5180    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5181    enum search_domain kind)
5182 {
5183   struct dwarf2_per_objfile *dwarf2_per_objfile
5184     = get_dwarf2_per_objfile (objfile);
5185
5186   /* index_table is NULL if OBJF_READNOW.  */
5187   if (!dwarf2_per_objfile->index_table)
5188     return;
5189
5190   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5191
5192   mapped_index &index = *dwarf2_per_objfile->index_table;
5193
5194   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5195                                       symbol_matcher,
5196                                       kind, [&] (offset_type idx)
5197     {
5198       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5199                              expansion_notify, kind);
5200     });
5201 }
5202
5203 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5204    symtab.  */
5205
5206 static struct compunit_symtab *
5207 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5208                                           CORE_ADDR pc)
5209 {
5210   int i;
5211
5212   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5213       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5214     return cust;
5215
5216   if (cust->includes == NULL)
5217     return NULL;
5218
5219   for (i = 0; cust->includes[i]; ++i)
5220     {
5221       struct compunit_symtab *s = cust->includes[i];
5222
5223       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5224       if (s != NULL)
5225         return s;
5226     }
5227
5228   return NULL;
5229 }
5230
5231 static struct compunit_symtab *
5232 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5233                                   struct bound_minimal_symbol msymbol,
5234                                   CORE_ADDR pc,
5235                                   struct obj_section *section,
5236                                   int warn_if_readin)
5237 {
5238   struct dwarf2_per_cu_data *data;
5239   struct compunit_symtab *result;
5240
5241   if (!objfile->psymtabs_addrmap)
5242     return NULL;
5243
5244   CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
5245                                  SECT_OFF_TEXT (objfile));
5246   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5247                                                      pc - baseaddr);
5248   if (!data)
5249     return NULL;
5250
5251   if (warn_if_readin && data->v.quick->compunit_symtab)
5252     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5253              paddress (get_objfile_arch (objfile), pc));
5254
5255   result
5256     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
5257                                                                         false),
5258                                                 pc);
5259   gdb_assert (result != NULL);
5260   return result;
5261 }
5262
5263 static void
5264 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5265                           void *data, int need_fullname)
5266 {
5267   struct dwarf2_per_objfile *dwarf2_per_objfile
5268     = get_dwarf2_per_objfile (objfile);
5269
5270   if (!dwarf2_per_objfile->filenames_cache)
5271     {
5272       dwarf2_per_objfile->filenames_cache.emplace ();
5273
5274       htab_up visited (htab_create_alloc (10,
5275                                           htab_hash_pointer, htab_eq_pointer,
5276                                           NULL, xcalloc, xfree));
5277
5278       /* The rule is CUs specify all the files, including those used
5279          by any TU, so there's no need to scan TUs here.  We can
5280          ignore file names coming from already-expanded CUs.  */
5281
5282       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5283         {
5284           if (per_cu->v.quick->compunit_symtab)
5285             {
5286               void **slot = htab_find_slot (visited.get (),
5287                                             per_cu->v.quick->file_names,
5288                                             INSERT);
5289
5290               *slot = per_cu->v.quick->file_names;
5291             }
5292         }
5293
5294       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5295         {
5296           /* We only need to look at symtabs not already expanded.  */
5297           if (per_cu->v.quick->compunit_symtab)
5298             continue;
5299
5300           quick_file_names *file_data = dw2_get_file_names (per_cu);
5301           if (file_data == NULL)
5302             continue;
5303
5304           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5305           if (*slot)
5306             {
5307               /* Already visited.  */
5308               continue;
5309             }
5310           *slot = file_data;
5311
5312           for (int j = 0; j < file_data->num_file_names; ++j)
5313             {
5314               const char *filename = file_data->file_names[j];
5315               dwarf2_per_objfile->filenames_cache->seen (filename);
5316             }
5317         }
5318     }
5319
5320   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5321     {
5322       gdb::unique_xmalloc_ptr<char> this_real_name;
5323
5324       if (need_fullname)
5325         this_real_name = gdb_realpath (filename);
5326       (*fun) (filename, this_real_name.get (), data);
5327     });
5328 }
5329
5330 static int
5331 dw2_has_symbols (struct objfile *objfile)
5332 {
5333   return 1;
5334 }
5335
5336 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5337 {
5338   dw2_has_symbols,
5339   dw2_find_last_source_symtab,
5340   dw2_forget_cached_source_info,
5341   dw2_map_symtabs_matching_filename,
5342   dw2_lookup_symbol,
5343   dw2_print_stats,
5344   dw2_dump,
5345   dw2_expand_symtabs_for_function,
5346   dw2_expand_all_symtabs,
5347   dw2_expand_symtabs_with_fullname,
5348   dw2_map_matching_symbols,
5349   dw2_expand_symtabs_matching,
5350   dw2_find_pc_sect_compunit_symtab,
5351   NULL,
5352   dw2_map_symbol_filenames
5353 };
5354
5355 /* DWARF-5 debug_names reader.  */
5356
5357 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5358 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5359
5360 /* A helper function that reads the .debug_names section in SECTION
5361    and fills in MAP.  FILENAME is the name of the file containing the
5362    section; it is used for error reporting.
5363
5364    Returns true if all went well, false otherwise.  */
5365
5366 static bool
5367 read_debug_names_from_section (struct objfile *objfile,
5368                                const char *filename,
5369                                struct dwarf2_section_info *section,
5370                                mapped_debug_names &map)
5371 {
5372   if (dwarf2_section_empty_p (section))
5373     return false;
5374
5375   /* Older elfutils strip versions could keep the section in the main
5376      executable while splitting it for the separate debug info file.  */
5377   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5378     return false;
5379
5380   dwarf2_read_section (objfile, section);
5381
5382   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5383
5384   const gdb_byte *addr = section->buffer;
5385
5386   bfd *const abfd = get_section_bfd_owner (section);
5387
5388   unsigned int bytes_read;
5389   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5390   addr += bytes_read;
5391
5392   map.dwarf5_is_dwarf64 = bytes_read != 4;
5393   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5394   if (bytes_read + length != section->size)
5395     {
5396       /* There may be multiple per-CU indices.  */
5397       warning (_("Section .debug_names in %s length %s does not match "
5398                  "section length %s, ignoring .debug_names."),
5399                filename, plongest (bytes_read + length),
5400                pulongest (section->size));
5401       return false;
5402     }
5403
5404   /* The version number.  */
5405   uint16_t version = read_2_bytes (abfd, addr);
5406   addr += 2;
5407   if (version != 5)
5408     {
5409       warning (_("Section .debug_names in %s has unsupported version %d, "
5410                  "ignoring .debug_names."),
5411                filename, version);
5412       return false;
5413     }
5414
5415   /* Padding.  */
5416   uint16_t padding = read_2_bytes (abfd, addr);
5417   addr += 2;
5418   if (padding != 0)
5419     {
5420       warning (_("Section .debug_names in %s has unsupported padding %d, "
5421                  "ignoring .debug_names."),
5422                filename, padding);
5423       return false;
5424     }
5425
5426   /* comp_unit_count - The number of CUs in the CU list.  */
5427   map.cu_count = read_4_bytes (abfd, addr);
5428   addr += 4;
5429
5430   /* local_type_unit_count - The number of TUs in the local TU
5431      list.  */
5432   map.tu_count = read_4_bytes (abfd, addr);
5433   addr += 4;
5434
5435   /* foreign_type_unit_count - The number of TUs in the foreign TU
5436      list.  */
5437   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5438   addr += 4;
5439   if (foreign_tu_count != 0)
5440     {
5441       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5442                  "ignoring .debug_names."),
5443                filename, static_cast<unsigned long> (foreign_tu_count));
5444       return false;
5445     }
5446
5447   /* bucket_count - The number of hash buckets in the hash lookup
5448      table.  */
5449   map.bucket_count = read_4_bytes (abfd, addr);
5450   addr += 4;
5451
5452   /* name_count - The number of unique names in the index.  */
5453   map.name_count = read_4_bytes (abfd, addr);
5454   addr += 4;
5455
5456   /* abbrev_table_size - The size in bytes of the abbreviations
5457      table.  */
5458   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5459   addr += 4;
5460
5461   /* augmentation_string_size - The size in bytes of the augmentation
5462      string.  This value is rounded up to a multiple of 4.  */
5463   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5464   addr += 4;
5465   map.augmentation_is_gdb = ((augmentation_string_size
5466                               == sizeof (dwarf5_augmentation))
5467                              && memcmp (addr, dwarf5_augmentation,
5468                                         sizeof (dwarf5_augmentation)) == 0);
5469   augmentation_string_size += (-augmentation_string_size) & 3;
5470   addr += augmentation_string_size;
5471
5472   /* List of CUs */
5473   map.cu_table_reordered = addr;
5474   addr += map.cu_count * map.offset_size;
5475
5476   /* List of Local TUs */
5477   map.tu_table_reordered = addr;
5478   addr += map.tu_count * map.offset_size;
5479
5480   /* Hash Lookup Table */
5481   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5482   addr += map.bucket_count * 4;
5483   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5484   addr += map.name_count * 4;
5485
5486   /* Name Table */
5487   map.name_table_string_offs_reordered = addr;
5488   addr += map.name_count * map.offset_size;
5489   map.name_table_entry_offs_reordered = addr;
5490   addr += map.name_count * map.offset_size;
5491
5492   const gdb_byte *abbrev_table_start = addr;
5493   for (;;)
5494     {
5495       unsigned int bytes_read;
5496       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5497       addr += bytes_read;
5498       if (index_num == 0)
5499         break;
5500
5501       const auto insertpair
5502         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5503       if (!insertpair.second)
5504         {
5505           warning (_("Section .debug_names in %s has duplicate index %s, "
5506                      "ignoring .debug_names."),
5507                    filename, pulongest (index_num));
5508           return false;
5509         }
5510       mapped_debug_names::index_val &indexval = insertpair.first->second;
5511       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5512       addr += bytes_read;
5513
5514       for (;;)
5515         {
5516           mapped_debug_names::index_val::attr attr;
5517           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5518           addr += bytes_read;
5519           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5520           addr += bytes_read;
5521           if (attr.form == DW_FORM_implicit_const)
5522             {
5523               attr.implicit_const = read_signed_leb128 (abfd, addr,
5524                                                         &bytes_read);
5525               addr += bytes_read;
5526             }
5527           if (attr.dw_idx == 0 && attr.form == 0)
5528             break;
5529           indexval.attr_vec.push_back (std::move (attr));
5530         }
5531     }
5532   if (addr != abbrev_table_start + abbrev_table_size)
5533     {
5534       warning (_("Section .debug_names in %s has abbreviation_table "
5535                  "of size %zu vs. written as %u, ignoring .debug_names."),
5536                filename, addr - abbrev_table_start, abbrev_table_size);
5537       return false;
5538     }
5539   map.entry_pool = addr;
5540
5541   return true;
5542 }
5543
5544 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5545    list.  */
5546
5547 static void
5548 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5549                                   const mapped_debug_names &map,
5550                                   dwarf2_section_info &section,
5551                                   bool is_dwz)
5552 {
5553   sect_offset sect_off_prev;
5554   for (uint32_t i = 0; i <= map.cu_count; ++i)
5555     {
5556       sect_offset sect_off_next;
5557       if (i < map.cu_count)
5558         {
5559           sect_off_next
5560             = (sect_offset) (extract_unsigned_integer
5561                              (map.cu_table_reordered + i * map.offset_size,
5562                               map.offset_size,
5563                               map.dwarf5_byte_order));
5564         }
5565       else
5566         sect_off_next = (sect_offset) section.size;
5567       if (i >= 1)
5568         {
5569           const ULONGEST length = sect_off_next - sect_off_prev;
5570           dwarf2_per_cu_data *per_cu
5571             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5572                                          sect_off_prev, length);
5573           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5574         }
5575       sect_off_prev = sect_off_next;
5576     }
5577 }
5578
5579 /* Read the CU list from the mapped index, and use it to create all
5580    the CU objects for this dwarf2_per_objfile.  */
5581
5582 static void
5583 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5584                              const mapped_debug_names &map,
5585                              const mapped_debug_names &dwz_map)
5586 {
5587   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5588   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5589
5590   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5591                                     dwarf2_per_objfile->info,
5592                                     false /* is_dwz */);
5593
5594   if (dwz_map.cu_count == 0)
5595     return;
5596
5597   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5598   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5599                                     true /* is_dwz */);
5600 }
5601
5602 /* Read .debug_names.  If everything went ok, initialize the "quick"
5603    elements of all the CUs and return true.  Otherwise, return false.  */
5604
5605 static bool
5606 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5607 {
5608   std::unique_ptr<mapped_debug_names> map
5609     (new mapped_debug_names (dwarf2_per_objfile));
5610   mapped_debug_names dwz_map (dwarf2_per_objfile);
5611   struct objfile *objfile = dwarf2_per_objfile->objfile;
5612
5613   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5614                                       &dwarf2_per_objfile->debug_names,
5615                                       *map))
5616     return false;
5617
5618   /* Don't use the index if it's empty.  */
5619   if (map->name_count == 0)
5620     return false;
5621
5622   /* If there is a .dwz file, read it so we can get its CU list as
5623      well.  */
5624   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5625   if (dwz != NULL)
5626     {
5627       if (!read_debug_names_from_section (objfile,
5628                                           bfd_get_filename (dwz->dwz_bfd),
5629                                           &dwz->debug_names, dwz_map))
5630         {
5631           warning (_("could not read '.debug_names' section from %s; skipping"),
5632                    bfd_get_filename (dwz->dwz_bfd));
5633           return false;
5634         }
5635     }
5636
5637   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5638
5639   if (map->tu_count != 0)
5640     {
5641       /* We can only handle a single .debug_types when we have an
5642          index.  */
5643       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5644         return false;
5645
5646       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5647                                                 dwarf2_per_objfile->types, 0);
5648
5649       create_signatured_type_table_from_debug_names
5650         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5651     }
5652
5653   create_addrmap_from_aranges (dwarf2_per_objfile,
5654                                &dwarf2_per_objfile->debug_aranges);
5655
5656   dwarf2_per_objfile->debug_names_table = std::move (map);
5657   dwarf2_per_objfile->using_index = 1;
5658   dwarf2_per_objfile->quick_file_names_table =
5659     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5660
5661   return true;
5662 }
5663
5664 /* Type used to manage iterating over all CUs looking for a symbol for
5665    .debug_names.  */
5666
5667 class dw2_debug_names_iterator
5668 {
5669 public:
5670   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5671      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5672   dw2_debug_names_iterator (const mapped_debug_names &map,
5673                             bool want_specific_block,
5674                             block_enum block_index, domain_enum domain,
5675                             const char *name)
5676     : m_map (map), m_want_specific_block (want_specific_block),
5677       m_block_index (block_index), m_domain (domain),
5678       m_addr (find_vec_in_debug_names (map, name))
5679   {}
5680
5681   dw2_debug_names_iterator (const mapped_debug_names &map,
5682                             search_domain search, uint32_t namei)
5683     : m_map (map),
5684       m_search (search),
5685       m_addr (find_vec_in_debug_names (map, namei))
5686   {}
5687
5688   /* Return the next matching CU or NULL if there are no more.  */
5689   dwarf2_per_cu_data *next ();
5690
5691 private:
5692   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5693                                                   const char *name);
5694   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5695                                                   uint32_t namei);
5696
5697   /* The internalized form of .debug_names.  */
5698   const mapped_debug_names &m_map;
5699
5700   /* If true, only look for symbols that match BLOCK_INDEX.  */
5701   const bool m_want_specific_block = false;
5702
5703   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5704      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5705      value.  */
5706   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5707
5708   /* The kind of symbol we're looking for.  */
5709   const domain_enum m_domain = UNDEF_DOMAIN;
5710   const search_domain m_search = ALL_DOMAIN;
5711
5712   /* The list of CUs from the index entry of the symbol, or NULL if
5713      not found.  */
5714   const gdb_byte *m_addr;
5715 };
5716
5717 const char *
5718 mapped_debug_names::namei_to_name (uint32_t namei) const
5719 {
5720   const ULONGEST namei_string_offs
5721     = extract_unsigned_integer ((name_table_string_offs_reordered
5722                                  + namei * offset_size),
5723                                 offset_size,
5724                                 dwarf5_byte_order);
5725   return read_indirect_string_at_offset
5726     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5727 }
5728
5729 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5730    found, return pointer to its pool data.  If NAME cannot be found,
5731    return NULL.  */
5732
5733 const gdb_byte *
5734 dw2_debug_names_iterator::find_vec_in_debug_names
5735   (const mapped_debug_names &map, const char *name)
5736 {
5737   int (*cmp) (const char *, const char *);
5738
5739   if (current_language->la_language == language_cplus
5740       || current_language->la_language == language_fortran
5741       || current_language->la_language == language_d)
5742     {
5743       /* NAME is already canonical.  Drop any qualifiers as
5744          .debug_names does not contain any.  */
5745
5746       if (strchr (name, '(') != NULL)
5747         {
5748           gdb::unique_xmalloc_ptr<char> without_params
5749             = cp_remove_params (name);
5750
5751           if (without_params != NULL)
5752             {
5753               name = without_params.get();
5754             }
5755         }
5756     }
5757
5758   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5759
5760   const uint32_t full_hash = dwarf5_djb_hash (name);
5761   uint32_t namei
5762     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5763                                 (map.bucket_table_reordered
5764                                  + (full_hash % map.bucket_count)), 4,
5765                                 map.dwarf5_byte_order);
5766   if (namei == 0)
5767     return NULL;
5768   --namei;
5769   if (namei >= map.name_count)
5770     {
5771       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5772                    "[in module %s]"),
5773                  namei, map.name_count,
5774                  objfile_name (map.dwarf2_per_objfile->objfile));
5775       return NULL;
5776     }
5777
5778   for (;;)
5779     {
5780       const uint32_t namei_full_hash
5781         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5782                                     (map.hash_table_reordered + namei), 4,
5783                                     map.dwarf5_byte_order);
5784       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5785         return NULL;
5786
5787       if (full_hash == namei_full_hash)
5788         {
5789           const char *const namei_string = map.namei_to_name (namei);
5790
5791 #if 0 /* An expensive sanity check.  */
5792           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5793             {
5794               complaint (_("Wrong .debug_names hash for string at index %u "
5795                            "[in module %s]"),
5796                          namei, objfile_name (dwarf2_per_objfile->objfile));
5797               return NULL;
5798             }
5799 #endif
5800
5801           if (cmp (namei_string, name) == 0)
5802             {
5803               const ULONGEST namei_entry_offs
5804                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5805                                              + namei * map.offset_size),
5806                                             map.offset_size, map.dwarf5_byte_order);
5807               return map.entry_pool + namei_entry_offs;
5808             }
5809         }
5810
5811       ++namei;
5812       if (namei >= map.name_count)
5813         return NULL;
5814     }
5815 }
5816
5817 const gdb_byte *
5818 dw2_debug_names_iterator::find_vec_in_debug_names
5819   (const mapped_debug_names &map, uint32_t namei)
5820 {
5821   if (namei >= map.name_count)
5822     {
5823       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5824                    "[in module %s]"),
5825                  namei, map.name_count,
5826                  objfile_name (map.dwarf2_per_objfile->objfile));
5827       return NULL;
5828     }
5829
5830   const ULONGEST namei_entry_offs
5831     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5832                                  + namei * map.offset_size),
5833                                 map.offset_size, map.dwarf5_byte_order);
5834   return map.entry_pool + namei_entry_offs;
5835 }
5836
5837 /* See dw2_debug_names_iterator.  */
5838
5839 dwarf2_per_cu_data *
5840 dw2_debug_names_iterator::next ()
5841 {
5842   if (m_addr == NULL)
5843     return NULL;
5844
5845   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5846   struct objfile *objfile = dwarf2_per_objfile->objfile;
5847   bfd *const abfd = objfile->obfd;
5848
5849  again:
5850
5851   unsigned int bytes_read;
5852   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5853   m_addr += bytes_read;
5854   if (abbrev == 0)
5855     return NULL;
5856
5857   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5858   if (indexval_it == m_map.abbrev_map.cend ())
5859     {
5860       complaint (_("Wrong .debug_names undefined abbrev code %s "
5861                    "[in module %s]"),
5862                  pulongest (abbrev), objfile_name (objfile));
5863       return NULL;
5864     }
5865   const mapped_debug_names::index_val &indexval = indexval_it->second;
5866   bool have_is_static = false;
5867   bool is_static;
5868   dwarf2_per_cu_data *per_cu = NULL;
5869   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5870     {
5871       ULONGEST ull;
5872       switch (attr.form)
5873         {
5874         case DW_FORM_implicit_const:
5875           ull = attr.implicit_const;
5876           break;
5877         case DW_FORM_flag_present:
5878           ull = 1;
5879           break;
5880         case DW_FORM_udata:
5881           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5882           m_addr += bytes_read;
5883           break;
5884         default:
5885           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5886                      dwarf_form_name (attr.form),
5887                      objfile_name (objfile));
5888           return NULL;
5889         }
5890       switch (attr.dw_idx)
5891         {
5892         case DW_IDX_compile_unit:
5893           /* Don't crash on bad data.  */
5894           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5895             {
5896               complaint (_(".debug_names entry has bad CU index %s"
5897                            " [in module %s]"),
5898                          pulongest (ull),
5899                          objfile_name (dwarf2_per_objfile->objfile));
5900               continue;
5901             }
5902           per_cu = dwarf2_per_objfile->get_cutu (ull);
5903           break;
5904         case DW_IDX_type_unit:
5905           /* Don't crash on bad data.  */
5906           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5907             {
5908               complaint (_(".debug_names entry has bad TU index %s"
5909                            " [in module %s]"),
5910                          pulongest (ull),
5911                          objfile_name (dwarf2_per_objfile->objfile));
5912               continue;
5913             }
5914           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5915           break;
5916         case DW_IDX_GNU_internal:
5917           if (!m_map.augmentation_is_gdb)
5918             break;
5919           have_is_static = true;
5920           is_static = true;
5921           break;
5922         case DW_IDX_GNU_external:
5923           if (!m_map.augmentation_is_gdb)
5924             break;
5925           have_is_static = true;
5926           is_static = false;
5927           break;
5928         }
5929     }
5930
5931   /* Skip if already read in.  */
5932   if (per_cu->v.quick->compunit_symtab)
5933     goto again;
5934
5935   /* Check static vs global.  */
5936   if (have_is_static)
5937     {
5938       const bool want_static = m_block_index != GLOBAL_BLOCK;
5939       if (m_want_specific_block && want_static != is_static)
5940         goto again;
5941     }
5942
5943   /* Match dw2_symtab_iter_next, symbol_kind
5944      and debug_names::psymbol_tag.  */
5945   switch (m_domain)
5946     {
5947     case VAR_DOMAIN:
5948       switch (indexval.dwarf_tag)
5949         {
5950         case DW_TAG_variable:
5951         case DW_TAG_subprogram:
5952         /* Some types are also in VAR_DOMAIN.  */
5953         case DW_TAG_typedef:
5954         case DW_TAG_structure_type:
5955           break;
5956         default:
5957           goto again;
5958         }
5959       break;
5960     case STRUCT_DOMAIN:
5961       switch (indexval.dwarf_tag)
5962         {
5963         case DW_TAG_typedef:
5964         case DW_TAG_structure_type:
5965           break;
5966         default:
5967           goto again;
5968         }
5969       break;
5970     case LABEL_DOMAIN:
5971       switch (indexval.dwarf_tag)
5972         {
5973         case 0:
5974         case DW_TAG_variable:
5975           break;
5976         default:
5977           goto again;
5978         }
5979       break;
5980     default:
5981       break;
5982     }
5983
5984   /* Match dw2_expand_symtabs_matching, symbol_kind and
5985      debug_names::psymbol_tag.  */
5986   switch (m_search)
5987     {
5988     case VARIABLES_DOMAIN:
5989       switch (indexval.dwarf_tag)
5990         {
5991         case DW_TAG_variable:
5992           break;
5993         default:
5994           goto again;
5995         }
5996       break;
5997     case FUNCTIONS_DOMAIN:
5998       switch (indexval.dwarf_tag)
5999         {
6000         case DW_TAG_subprogram:
6001           break;
6002         default:
6003           goto again;
6004         }
6005       break;
6006     case TYPES_DOMAIN:
6007       switch (indexval.dwarf_tag)
6008         {
6009         case DW_TAG_typedef:
6010         case DW_TAG_structure_type:
6011           break;
6012         default:
6013           goto again;
6014         }
6015       break;
6016     default:
6017       break;
6018     }
6019
6020   return per_cu;
6021 }
6022
6023 static struct compunit_symtab *
6024 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6025                                const char *name, domain_enum domain)
6026 {
6027   const block_enum block_index = static_cast<block_enum> (block_index_int);
6028   struct dwarf2_per_objfile *dwarf2_per_objfile
6029     = get_dwarf2_per_objfile (objfile);
6030
6031   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6032   if (!mapp)
6033     {
6034       /* index is NULL if OBJF_READNOW.  */
6035       return NULL;
6036     }
6037   const auto &map = *mapp;
6038
6039   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6040                                  block_index, domain, name);
6041
6042   struct compunit_symtab *stab_best = NULL;
6043   struct dwarf2_per_cu_data *per_cu;
6044   while ((per_cu = iter.next ()) != NULL)
6045     {
6046       struct symbol *sym, *with_opaque = NULL;
6047       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
6048       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6049       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6050
6051       sym = block_find_symbol (block, name, domain,
6052                                block_find_non_opaque_type_preferred,
6053                                &with_opaque);
6054
6055       /* Some caution must be observed with overloaded functions and
6056          methods, since the index will not contain any overload
6057          information (but NAME might contain it).  */
6058
6059       if (sym != NULL
6060           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6061         return stab;
6062       if (with_opaque != NULL
6063           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6064         stab_best = stab;
6065
6066       /* Keep looking through other CUs.  */
6067     }
6068
6069   return stab_best;
6070 }
6071
6072 /* This dumps minimal information about .debug_names.  It is called
6073    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6074    uses this to verify that .debug_names has been loaded.  */
6075
6076 static void
6077 dw2_debug_names_dump (struct objfile *objfile)
6078 {
6079   struct dwarf2_per_objfile *dwarf2_per_objfile
6080     = get_dwarf2_per_objfile (objfile);
6081
6082   gdb_assert (dwarf2_per_objfile->using_index);
6083   printf_filtered (".debug_names:");
6084   if (dwarf2_per_objfile->debug_names_table)
6085     printf_filtered (" exists\n");
6086   else
6087     printf_filtered (" faked for \"readnow\"\n");
6088   printf_filtered ("\n");
6089 }
6090
6091 static void
6092 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6093                                              const char *func_name)
6094 {
6095   struct dwarf2_per_objfile *dwarf2_per_objfile
6096     = get_dwarf2_per_objfile (objfile);
6097
6098   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6099   if (dwarf2_per_objfile->debug_names_table)
6100     {
6101       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6102
6103       /* Note: It doesn't matter what we pass for block_index here.  */
6104       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6105                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6106
6107       struct dwarf2_per_cu_data *per_cu;
6108       while ((per_cu = iter.next ()) != NULL)
6109         dw2_instantiate_symtab (per_cu, false);
6110     }
6111 }
6112
6113 static void
6114 dw2_debug_names_expand_symtabs_matching
6115   (struct objfile *objfile,
6116    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6117    const lookup_name_info &lookup_name,
6118    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6119    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6120    enum search_domain kind)
6121 {
6122   struct dwarf2_per_objfile *dwarf2_per_objfile
6123     = get_dwarf2_per_objfile (objfile);
6124
6125   /* debug_names_table is NULL if OBJF_READNOW.  */
6126   if (!dwarf2_per_objfile->debug_names_table)
6127     return;
6128
6129   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6130
6131   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6132
6133   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6134                                       symbol_matcher,
6135                                       kind, [&] (offset_type namei)
6136     {
6137       /* The name was matched, now expand corresponding CUs that were
6138          marked.  */
6139       dw2_debug_names_iterator iter (map, kind, namei);
6140
6141       struct dwarf2_per_cu_data *per_cu;
6142       while ((per_cu = iter.next ()) != NULL)
6143         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6144                                          expansion_notify);
6145     });
6146 }
6147
6148 const struct quick_symbol_functions dwarf2_debug_names_functions =
6149 {
6150   dw2_has_symbols,
6151   dw2_find_last_source_symtab,
6152   dw2_forget_cached_source_info,
6153   dw2_map_symtabs_matching_filename,
6154   dw2_debug_names_lookup_symbol,
6155   dw2_print_stats,
6156   dw2_debug_names_dump,
6157   dw2_debug_names_expand_symtabs_for_function,
6158   dw2_expand_all_symtabs,
6159   dw2_expand_symtabs_with_fullname,
6160   dw2_map_matching_symbols,
6161   dw2_debug_names_expand_symtabs_matching,
6162   dw2_find_pc_sect_compunit_symtab,
6163   NULL,
6164   dw2_map_symbol_filenames
6165 };
6166
6167 /* Get the content of the .gdb_index section of OBJ.  SECTION_OWNER should point
6168    to either a dwarf2_per_objfile or dwz_file object.  */
6169
6170 template <typename T>
6171 static gdb::array_view<const gdb_byte>
6172 get_gdb_index_contents_from_section (objfile *obj, T *section_owner)
6173 {
6174   dwarf2_section_info *section = &section_owner->gdb_index;
6175
6176   if (dwarf2_section_empty_p (section))
6177     return {};
6178
6179   /* Older elfutils strip versions could keep the section in the main
6180      executable while splitting it for the separate debug info file.  */
6181   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
6182     return {};
6183
6184   dwarf2_read_section (obj, section);
6185
6186   return {section->buffer, section->size};
6187 }
6188
6189 /* See symfile.h.  */
6190
6191 bool
6192 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6193 {
6194   struct dwarf2_per_objfile *dwarf2_per_objfile
6195     = get_dwarf2_per_objfile (objfile);
6196
6197   /* If we're about to read full symbols, don't bother with the
6198      indices.  In this case we also don't care if some other debug
6199      format is making psymtabs, because they are all about to be
6200      expanded anyway.  */
6201   if ((objfile->flags & OBJF_READNOW))
6202     {
6203       dwarf2_per_objfile->using_index = 1;
6204       create_all_comp_units (dwarf2_per_objfile);
6205       create_all_type_units (dwarf2_per_objfile);
6206       dwarf2_per_objfile->quick_file_names_table
6207         = create_quick_file_names_table
6208             (dwarf2_per_objfile->all_comp_units.size ());
6209
6210       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6211                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6212         {
6213           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6214
6215           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6216                                             struct dwarf2_per_cu_quick_data);
6217         }
6218
6219       /* Return 1 so that gdb sees the "quick" functions.  However,
6220          these functions will be no-ops because we will have expanded
6221          all symtabs.  */
6222       *index_kind = dw_index_kind::GDB_INDEX;
6223       return true;
6224     }
6225
6226   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6227     {
6228       *index_kind = dw_index_kind::DEBUG_NAMES;
6229       return true;
6230     }
6231
6232   if (dwarf2_read_gdb_index (dwarf2_per_objfile,
6233                              get_gdb_index_contents_from_section<struct dwarf2_per_objfile>,
6234                              get_gdb_index_contents_from_section<dwz_file>))
6235     {
6236       *index_kind = dw_index_kind::GDB_INDEX;
6237       return true;
6238     }
6239
6240   return false;
6241 }
6242
6243 \f
6244
6245 /* Build a partial symbol table.  */
6246
6247 void
6248 dwarf2_build_psymtabs (struct objfile *objfile)
6249 {
6250   struct dwarf2_per_objfile *dwarf2_per_objfile
6251     = get_dwarf2_per_objfile (objfile);
6252
6253   if (objfile->global_psymbols.capacity () == 0
6254       && objfile->static_psymbols.capacity () == 0)
6255     init_psymbol_list (objfile, 1024);
6256
6257   TRY
6258     {
6259       /* This isn't really ideal: all the data we allocate on the
6260          objfile's obstack is still uselessly kept around.  However,
6261          freeing it seems unsafe.  */
6262       psymtab_discarder psymtabs (objfile);
6263       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6264       psymtabs.keep ();
6265     }
6266   CATCH (except, RETURN_MASK_ERROR)
6267     {
6268       exception_print (gdb_stderr, except);
6269     }
6270   END_CATCH
6271 }
6272
6273 /* Return the total length of the CU described by HEADER.  */
6274
6275 static unsigned int
6276 get_cu_length (const struct comp_unit_head *header)
6277 {
6278   return header->initial_length_size + header->length;
6279 }
6280
6281 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6282
6283 static inline bool
6284 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6285 {
6286   sect_offset bottom = cu_header->sect_off;
6287   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6288
6289   return sect_off >= bottom && sect_off < top;
6290 }
6291
6292 /* Find the base address of the compilation unit for range lists and
6293    location lists.  It will normally be specified by DW_AT_low_pc.
6294    In DWARF-3 draft 4, the base address could be overridden by
6295    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6296    compilation units with discontinuous ranges.  */
6297
6298 static void
6299 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6300 {
6301   struct attribute *attr;
6302
6303   cu->base_known = 0;
6304   cu->base_address = 0;
6305
6306   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6307   if (attr)
6308     {
6309       cu->base_address = attr_value_as_address (attr);
6310       cu->base_known = 1;
6311     }
6312   else
6313     {
6314       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6315       if (attr)
6316         {
6317           cu->base_address = attr_value_as_address (attr);
6318           cu->base_known = 1;
6319         }
6320     }
6321 }
6322
6323 /* Read in the comp unit header information from the debug_info at info_ptr.
6324    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6325    NOTE: This leaves members offset, first_die_offset to be filled in
6326    by the caller.  */
6327
6328 static const gdb_byte *
6329 read_comp_unit_head (struct comp_unit_head *cu_header,
6330                      const gdb_byte *info_ptr,
6331                      struct dwarf2_section_info *section,
6332                      rcuh_kind section_kind)
6333 {
6334   int signed_addr;
6335   unsigned int bytes_read;
6336   const char *filename = get_section_file_name (section);
6337   bfd *abfd = get_section_bfd_owner (section);
6338
6339   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6340   cu_header->initial_length_size = bytes_read;
6341   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6342   info_ptr += bytes_read;
6343   cu_header->version = read_2_bytes (abfd, info_ptr);
6344   if (cu_header->version < 2 || cu_header->version > 5)
6345     error (_("Dwarf Error: wrong version in compilation unit header "
6346            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6347            cu_header->version, filename);
6348   info_ptr += 2;
6349   if (cu_header->version < 5)
6350     switch (section_kind)
6351       {
6352       case rcuh_kind::COMPILE:
6353         cu_header->unit_type = DW_UT_compile;
6354         break;
6355       case rcuh_kind::TYPE:
6356         cu_header->unit_type = DW_UT_type;
6357         break;
6358       default:
6359         internal_error (__FILE__, __LINE__,
6360                         _("read_comp_unit_head: invalid section_kind"));
6361       }
6362   else
6363     {
6364       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6365                                                  (read_1_byte (abfd, info_ptr));
6366       info_ptr += 1;
6367       switch (cu_header->unit_type)
6368         {
6369         case DW_UT_compile:
6370           if (section_kind != rcuh_kind::COMPILE)
6371             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6372                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6373                    filename);
6374           break;
6375         case DW_UT_type:
6376           section_kind = rcuh_kind::TYPE;
6377           break;
6378         default:
6379           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6380                  "(is %d, should be %d or %d) [in module %s]"),
6381                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6382         }
6383
6384       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6385       info_ptr += 1;
6386     }
6387   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6388                                                           cu_header,
6389                                                           &bytes_read);
6390   info_ptr += bytes_read;
6391   if (cu_header->version < 5)
6392     {
6393       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6394       info_ptr += 1;
6395     }
6396   signed_addr = bfd_get_sign_extend_vma (abfd);
6397   if (signed_addr < 0)
6398     internal_error (__FILE__, __LINE__,
6399                     _("read_comp_unit_head: dwarf from non elf file"));
6400   cu_header->signed_addr_p = signed_addr;
6401
6402   if (section_kind == rcuh_kind::TYPE)
6403     {
6404       LONGEST type_offset;
6405
6406       cu_header->signature = read_8_bytes (abfd, info_ptr);
6407       info_ptr += 8;
6408
6409       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6410       info_ptr += bytes_read;
6411       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6412       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6413         error (_("Dwarf Error: Too big type_offset in compilation unit "
6414                "header (is %s) [in module %s]"), plongest (type_offset),
6415                filename);
6416     }
6417
6418   return info_ptr;
6419 }
6420
6421 /* Helper function that returns the proper abbrev section for
6422    THIS_CU.  */
6423
6424 static struct dwarf2_section_info *
6425 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6426 {
6427   struct dwarf2_section_info *abbrev;
6428   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6429
6430   if (this_cu->is_dwz)
6431     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6432   else
6433     abbrev = &dwarf2_per_objfile->abbrev;
6434
6435   return abbrev;
6436 }
6437
6438 /* Subroutine of read_and_check_comp_unit_head and
6439    read_and_check_type_unit_head to simplify them.
6440    Perform various error checking on the header.  */
6441
6442 static void
6443 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6444                             struct comp_unit_head *header,
6445                             struct dwarf2_section_info *section,
6446                             struct dwarf2_section_info *abbrev_section)
6447 {
6448   const char *filename = get_section_file_name (section);
6449
6450   if (to_underlying (header->abbrev_sect_off)
6451       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6452     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6453            "(offset %s + 6) [in module %s]"),
6454            sect_offset_str (header->abbrev_sect_off),
6455            sect_offset_str (header->sect_off),
6456            filename);
6457
6458   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6459      avoid potential 32-bit overflow.  */
6460   if (((ULONGEST) header->sect_off + get_cu_length (header))
6461       > section->size)
6462     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6463            "(offset %s + 0) [in module %s]"),
6464            header->length, sect_offset_str (header->sect_off),
6465            filename);
6466 }
6467
6468 /* Read in a CU/TU header and perform some basic error checking.
6469    The contents of the header are stored in HEADER.
6470    The result is a pointer to the start of the first DIE.  */
6471
6472 static const gdb_byte *
6473 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6474                                struct comp_unit_head *header,
6475                                struct dwarf2_section_info *section,
6476                                struct dwarf2_section_info *abbrev_section,
6477                                const gdb_byte *info_ptr,
6478                                rcuh_kind section_kind)
6479 {
6480   const gdb_byte *beg_of_comp_unit = info_ptr;
6481
6482   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6483
6484   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6485
6486   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6487
6488   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6489                               abbrev_section);
6490
6491   return info_ptr;
6492 }
6493
6494 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6495
6496 static sect_offset
6497 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6498                     struct dwarf2_section_info *section,
6499                     sect_offset sect_off)
6500 {
6501   bfd *abfd = get_section_bfd_owner (section);
6502   const gdb_byte *info_ptr;
6503   unsigned int initial_length_size, offset_size;
6504   uint16_t version;
6505
6506   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6507   info_ptr = section->buffer + to_underlying (sect_off);
6508   read_initial_length (abfd, info_ptr, &initial_length_size);
6509   offset_size = initial_length_size == 4 ? 4 : 8;
6510   info_ptr += initial_length_size;
6511
6512   version = read_2_bytes (abfd, info_ptr);
6513   info_ptr += 2;
6514   if (version >= 5)
6515     {
6516       /* Skip unit type and address size.  */
6517       info_ptr += 2;
6518     }
6519
6520   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6521 }
6522
6523 /* Allocate a new partial symtab for file named NAME and mark this new
6524    partial symtab as being an include of PST.  */
6525
6526 static void
6527 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6528                                struct objfile *objfile)
6529 {
6530   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6531
6532   if (!IS_ABSOLUTE_PATH (subpst->filename))
6533     {
6534       /* It shares objfile->objfile_obstack.  */
6535       subpst->dirname = pst->dirname;
6536     }
6537
6538   subpst->dependencies
6539     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6540   subpst->dependencies[0] = pst;
6541   subpst->number_of_dependencies = 1;
6542
6543   subpst->globals_offset = 0;
6544   subpst->n_global_syms = 0;
6545   subpst->statics_offset = 0;
6546   subpst->n_static_syms = 0;
6547   subpst->compunit_symtab = NULL;
6548   subpst->read_symtab = pst->read_symtab;
6549   subpst->readin = 0;
6550
6551   /* No private part is necessary for include psymtabs.  This property
6552      can be used to differentiate between such include psymtabs and
6553      the regular ones.  */
6554   subpst->read_symtab_private = NULL;
6555 }
6556
6557 /* Read the Line Number Program data and extract the list of files
6558    included by the source file represented by PST.  Build an include
6559    partial symtab for each of these included files.  */
6560
6561 static void
6562 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6563                                struct die_info *die,
6564                                struct partial_symtab *pst)
6565 {
6566   line_header_up lh;
6567   struct attribute *attr;
6568
6569   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6570   if (attr)
6571     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6572   if (lh == NULL)
6573     return;  /* No linetable, so no includes.  */
6574
6575   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  Also note
6576      that we pass in the raw text_low here; that is ok because we're
6577      only decoding the line table to make include partial symtabs, and
6578      so the addresses aren't really used.  */
6579   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst,
6580                       pst->raw_text_low (), 1);
6581 }
6582
6583 static hashval_t
6584 hash_signatured_type (const void *item)
6585 {
6586   const struct signatured_type *sig_type
6587     = (const struct signatured_type *) item;
6588
6589   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6590   return sig_type->signature;
6591 }
6592
6593 static int
6594 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6595 {
6596   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6597   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6598
6599   return lhs->signature == rhs->signature;
6600 }
6601
6602 /* Allocate a hash table for signatured types.  */
6603
6604 static htab_t
6605 allocate_signatured_type_table (struct objfile *objfile)
6606 {
6607   return htab_create_alloc_ex (41,
6608                                hash_signatured_type,
6609                                eq_signatured_type,
6610                                NULL,
6611                                &objfile->objfile_obstack,
6612                                hashtab_obstack_allocate,
6613                                dummy_obstack_deallocate);
6614 }
6615
6616 /* A helper function to add a signatured type CU to a table.  */
6617
6618 static int
6619 add_signatured_type_cu_to_table (void **slot, void *datum)
6620 {
6621   struct signatured_type *sigt = (struct signatured_type *) *slot;
6622   std::vector<signatured_type *> *all_type_units
6623     = (std::vector<signatured_type *> *) datum;
6624
6625   all_type_units->push_back (sigt);
6626
6627   return 1;
6628 }
6629
6630 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6631    and fill them into TYPES_HTAB.  It will process only type units,
6632    therefore DW_UT_type.  */
6633
6634 static void
6635 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6636                               struct dwo_file *dwo_file,
6637                               dwarf2_section_info *section, htab_t &types_htab,
6638                               rcuh_kind section_kind)
6639 {
6640   struct objfile *objfile = dwarf2_per_objfile->objfile;
6641   struct dwarf2_section_info *abbrev_section;
6642   bfd *abfd;
6643   const gdb_byte *info_ptr, *end_ptr;
6644
6645   abbrev_section = (dwo_file != NULL
6646                     ? &dwo_file->sections.abbrev
6647                     : &dwarf2_per_objfile->abbrev);
6648
6649   if (dwarf_read_debug)
6650     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6651                         get_section_name (section),
6652                         get_section_file_name (abbrev_section));
6653
6654   dwarf2_read_section (objfile, section);
6655   info_ptr = section->buffer;
6656
6657   if (info_ptr == NULL)
6658     return;
6659
6660   /* We can't set abfd until now because the section may be empty or
6661      not present, in which case the bfd is unknown.  */
6662   abfd = get_section_bfd_owner (section);
6663
6664   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6665      because we don't need to read any dies: the signature is in the
6666      header.  */
6667
6668   end_ptr = info_ptr + section->size;
6669   while (info_ptr < end_ptr)
6670     {
6671       struct signatured_type *sig_type;
6672       struct dwo_unit *dwo_tu;
6673       void **slot;
6674       const gdb_byte *ptr = info_ptr;
6675       struct comp_unit_head header;
6676       unsigned int length;
6677
6678       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6679
6680       /* Initialize it due to a false compiler warning.  */
6681       header.signature = -1;
6682       header.type_cu_offset_in_tu = (cu_offset) -1;
6683
6684       /* We need to read the type's signature in order to build the hash
6685          table, but we don't need anything else just yet.  */
6686
6687       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6688                                            abbrev_section, ptr, section_kind);
6689
6690       length = get_cu_length (&header);
6691
6692       /* Skip dummy type units.  */
6693       if (ptr >= info_ptr + length
6694           || peek_abbrev_code (abfd, ptr) == 0
6695           || header.unit_type != DW_UT_type)
6696         {
6697           info_ptr += length;
6698           continue;
6699         }
6700
6701       if (types_htab == NULL)
6702         {
6703           if (dwo_file)
6704             types_htab = allocate_dwo_unit_table (objfile);
6705           else
6706             types_htab = allocate_signatured_type_table (objfile);
6707         }
6708
6709       if (dwo_file)
6710         {
6711           sig_type = NULL;
6712           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6713                                    struct dwo_unit);
6714           dwo_tu->dwo_file = dwo_file;
6715           dwo_tu->signature = header.signature;
6716           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6717           dwo_tu->section = section;
6718           dwo_tu->sect_off = sect_off;
6719           dwo_tu->length = length;
6720         }
6721       else
6722         {
6723           /* N.B.: type_offset is not usable if this type uses a DWO file.
6724              The real type_offset is in the DWO file.  */
6725           dwo_tu = NULL;
6726           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6727                                      struct signatured_type);
6728           sig_type->signature = header.signature;
6729           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6730           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6731           sig_type->per_cu.is_debug_types = 1;
6732           sig_type->per_cu.section = section;
6733           sig_type->per_cu.sect_off = sect_off;
6734           sig_type->per_cu.length = length;
6735         }
6736
6737       slot = htab_find_slot (types_htab,
6738                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6739                              INSERT);
6740       gdb_assert (slot != NULL);
6741       if (*slot != NULL)
6742         {
6743           sect_offset dup_sect_off;
6744
6745           if (dwo_file)
6746             {
6747               const struct dwo_unit *dup_tu
6748                 = (const struct dwo_unit *) *slot;
6749
6750               dup_sect_off = dup_tu->sect_off;
6751             }
6752           else
6753             {
6754               const struct signatured_type *dup_tu
6755                 = (const struct signatured_type *) *slot;
6756
6757               dup_sect_off = dup_tu->per_cu.sect_off;
6758             }
6759
6760           complaint (_("debug type entry at offset %s is duplicate to"
6761                        " the entry at offset %s, signature %s"),
6762                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6763                      hex_string (header.signature));
6764         }
6765       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6766
6767       if (dwarf_read_debug > 1)
6768         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6769                             sect_offset_str (sect_off),
6770                             hex_string (header.signature));
6771
6772       info_ptr += length;
6773     }
6774 }
6775
6776 /* Create the hash table of all entries in the .debug_types
6777    (or .debug_types.dwo) section(s).
6778    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6779    otherwise it is NULL.
6780
6781    The result is a pointer to the hash table or NULL if there are no types.
6782
6783    Note: This function processes DWO files only, not DWP files.  */
6784
6785 static void
6786 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6787                                struct dwo_file *dwo_file,
6788                                VEC (dwarf2_section_info_def) *types,
6789                                htab_t &types_htab)
6790 {
6791   int ix;
6792   struct dwarf2_section_info *section;
6793
6794   if (VEC_empty (dwarf2_section_info_def, types))
6795     return;
6796
6797   for (ix = 0;
6798        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6799        ++ix)
6800     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6801                                   types_htab, rcuh_kind::TYPE);
6802 }
6803
6804 /* Create the hash table of all entries in the .debug_types section,
6805    and initialize all_type_units.
6806    The result is zero if there is an error (e.g. missing .debug_types section),
6807    otherwise non-zero.  */
6808
6809 static int
6810 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6811 {
6812   htab_t types_htab = NULL;
6813
6814   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6815                                 &dwarf2_per_objfile->info, types_htab,
6816                                 rcuh_kind::COMPILE);
6817   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6818                                  dwarf2_per_objfile->types, types_htab);
6819   if (types_htab == NULL)
6820     {
6821       dwarf2_per_objfile->signatured_types = NULL;
6822       return 0;
6823     }
6824
6825   dwarf2_per_objfile->signatured_types = types_htab;
6826
6827   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6828   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6829
6830   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6831                           &dwarf2_per_objfile->all_type_units);
6832
6833   return 1;
6834 }
6835
6836 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6837    If SLOT is non-NULL, it is the entry to use in the hash table.
6838    Otherwise we find one.  */
6839
6840 static struct signatured_type *
6841 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6842                void **slot)
6843 {
6844   struct objfile *objfile = dwarf2_per_objfile->objfile;
6845
6846   if (dwarf2_per_objfile->all_type_units.size ()
6847       == dwarf2_per_objfile->all_type_units.capacity ())
6848     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6849
6850   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6851                                               struct signatured_type);
6852
6853   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6854   sig_type->signature = sig;
6855   sig_type->per_cu.is_debug_types = 1;
6856   if (dwarf2_per_objfile->using_index)
6857     {
6858       sig_type->per_cu.v.quick =
6859         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6860                         struct dwarf2_per_cu_quick_data);
6861     }
6862
6863   if (slot == NULL)
6864     {
6865       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6866                              sig_type, INSERT);
6867     }
6868   gdb_assert (*slot == NULL);
6869   *slot = sig_type;
6870   /* The rest of sig_type must be filled in by the caller.  */
6871   return sig_type;
6872 }
6873
6874 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6875    Fill in SIG_ENTRY with DWO_ENTRY.  */
6876
6877 static void
6878 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6879                                   struct signatured_type *sig_entry,
6880                                   struct dwo_unit *dwo_entry)
6881 {
6882   /* Make sure we're not clobbering something we don't expect to.  */
6883   gdb_assert (! sig_entry->per_cu.queued);
6884   gdb_assert (sig_entry->per_cu.cu == NULL);
6885   if (dwarf2_per_objfile->using_index)
6886     {
6887       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6888       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6889     }
6890   else
6891       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6892   gdb_assert (sig_entry->signature == dwo_entry->signature);
6893   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6894   gdb_assert (sig_entry->type_unit_group == NULL);
6895   gdb_assert (sig_entry->dwo_unit == NULL);
6896
6897   sig_entry->per_cu.section = dwo_entry->section;
6898   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6899   sig_entry->per_cu.length = dwo_entry->length;
6900   sig_entry->per_cu.reading_dwo_directly = 1;
6901   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6902   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6903   sig_entry->dwo_unit = dwo_entry;
6904 }
6905
6906 /* Subroutine of lookup_signatured_type.
6907    If we haven't read the TU yet, create the signatured_type data structure
6908    for a TU to be read in directly from a DWO file, bypassing the stub.
6909    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6910    using .gdb_index, then when reading a CU we want to stay in the DWO file
6911    containing that CU.  Otherwise we could end up reading several other DWO
6912    files (due to comdat folding) to process the transitive closure of all the
6913    mentioned TUs, and that can be slow.  The current DWO file will have every
6914    type signature that it needs.
6915    We only do this for .gdb_index because in the psymtab case we already have
6916    to read all the DWOs to build the type unit groups.  */
6917
6918 static struct signatured_type *
6919 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6920 {
6921   struct dwarf2_per_objfile *dwarf2_per_objfile
6922     = cu->per_cu->dwarf2_per_objfile;
6923   struct objfile *objfile = dwarf2_per_objfile->objfile;
6924   struct dwo_file *dwo_file;
6925   struct dwo_unit find_dwo_entry, *dwo_entry;
6926   struct signatured_type find_sig_entry, *sig_entry;
6927   void **slot;
6928
6929   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6930
6931   /* If TU skeletons have been removed then we may not have read in any
6932      TUs yet.  */
6933   if (dwarf2_per_objfile->signatured_types == NULL)
6934     {
6935       dwarf2_per_objfile->signatured_types
6936         = allocate_signatured_type_table (objfile);
6937     }
6938
6939   /* We only ever need to read in one copy of a signatured type.
6940      Use the global signatured_types array to do our own comdat-folding
6941      of types.  If this is the first time we're reading this TU, and
6942      the TU has an entry in .gdb_index, replace the recorded data from
6943      .gdb_index with this TU.  */
6944
6945   find_sig_entry.signature = sig;
6946   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6947                          &find_sig_entry, INSERT);
6948   sig_entry = (struct signatured_type *) *slot;
6949
6950   /* We can get here with the TU already read, *or* in the process of being
6951      read.  Don't reassign the global entry to point to this DWO if that's
6952      the case.  Also note that if the TU is already being read, it may not
6953      have come from a DWO, the program may be a mix of Fission-compiled
6954      code and non-Fission-compiled code.  */
6955
6956   /* Have we already tried to read this TU?
6957      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6958      needn't exist in the global table yet).  */
6959   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6960     return sig_entry;
6961
6962   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6963      dwo_unit of the TU itself.  */
6964   dwo_file = cu->dwo_unit->dwo_file;
6965
6966   /* Ok, this is the first time we're reading this TU.  */
6967   if (dwo_file->tus == NULL)
6968     return NULL;
6969   find_dwo_entry.signature = sig;
6970   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
6971   if (dwo_entry == NULL)
6972     return NULL;
6973
6974   /* If the global table doesn't have an entry for this TU, add one.  */
6975   if (sig_entry == NULL)
6976     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6977
6978   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6979   sig_entry->per_cu.tu_read = 1;
6980   return sig_entry;
6981 }
6982
6983 /* Subroutine of lookup_signatured_type.
6984    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6985    then try the DWP file.  If the TU stub (skeleton) has been removed then
6986    it won't be in .gdb_index.  */
6987
6988 static struct signatured_type *
6989 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6990 {
6991   struct dwarf2_per_objfile *dwarf2_per_objfile
6992     = cu->per_cu->dwarf2_per_objfile;
6993   struct objfile *objfile = dwarf2_per_objfile->objfile;
6994   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
6995   struct dwo_unit *dwo_entry;
6996   struct signatured_type find_sig_entry, *sig_entry;
6997   void **slot;
6998
6999   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
7000   gdb_assert (dwp_file != NULL);
7001
7002   /* If TU skeletons have been removed then we may not have read in any
7003      TUs yet.  */
7004   if (dwarf2_per_objfile->signatured_types == NULL)
7005     {
7006       dwarf2_per_objfile->signatured_types
7007         = allocate_signatured_type_table (objfile);
7008     }
7009
7010   find_sig_entry.signature = sig;
7011   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
7012                          &find_sig_entry, INSERT);
7013   sig_entry = (struct signatured_type *) *slot;
7014
7015   /* Have we already tried to read this TU?
7016      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
7017      needn't exist in the global table yet).  */
7018   if (sig_entry != NULL)
7019     return sig_entry;
7020
7021   if (dwp_file->tus == NULL)
7022     return NULL;
7023   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
7024                                       sig, 1 /* is_debug_types */);
7025   if (dwo_entry == NULL)
7026     return NULL;
7027
7028   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
7029   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
7030
7031   return sig_entry;
7032 }
7033
7034 /* Lookup a signature based type for DW_FORM_ref_sig8.
7035    Returns NULL if signature SIG is not present in the table.
7036    It is up to the caller to complain about this.  */
7037
7038 static struct signatured_type *
7039 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7040 {
7041   struct dwarf2_per_objfile *dwarf2_per_objfile
7042     = cu->per_cu->dwarf2_per_objfile;
7043
7044   if (cu->dwo_unit
7045       && dwarf2_per_objfile->using_index)
7046     {
7047       /* We're in a DWO/DWP file, and we're using .gdb_index.
7048          These cases require special processing.  */
7049       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7050         return lookup_dwo_signatured_type (cu, sig);
7051       else
7052         return lookup_dwp_signatured_type (cu, sig);
7053     }
7054   else
7055     {
7056       struct signatured_type find_entry, *entry;
7057
7058       if (dwarf2_per_objfile->signatured_types == NULL)
7059         return NULL;
7060       find_entry.signature = sig;
7061       entry = ((struct signatured_type *)
7062                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7063       return entry;
7064     }
7065 }
7066 \f
7067 /* Low level DIE reading support.  */
7068
7069 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7070
7071 static void
7072 init_cu_die_reader (struct die_reader_specs *reader,
7073                     struct dwarf2_cu *cu,
7074                     struct dwarf2_section_info *section,
7075                     struct dwo_file *dwo_file,
7076                     struct abbrev_table *abbrev_table)
7077 {
7078   gdb_assert (section->readin && section->buffer != NULL);
7079   reader->abfd = get_section_bfd_owner (section);
7080   reader->cu = cu;
7081   reader->dwo_file = dwo_file;
7082   reader->die_section = section;
7083   reader->buffer = section->buffer;
7084   reader->buffer_end = section->buffer + section->size;
7085   reader->comp_dir = NULL;
7086   reader->abbrev_table = abbrev_table;
7087 }
7088
7089 /* Subroutine of init_cutu_and_read_dies to simplify it.
7090    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7091    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7092    already.
7093
7094    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7095    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7096    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7097    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7098    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7099    STUB_COMP_DIR may be non-NULL.
7100    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7101    are filled in with the info of the DIE from the DWO file.
7102    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7103    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7104    kept around for at least as long as *RESULT_READER.
7105
7106    The result is non-zero if a valid (non-dummy) DIE was found.  */
7107
7108 static int
7109 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7110                         struct dwo_unit *dwo_unit,
7111                         struct die_info *stub_comp_unit_die,
7112                         const char *stub_comp_dir,
7113                         struct die_reader_specs *result_reader,
7114                         const gdb_byte **result_info_ptr,
7115                         struct die_info **result_comp_unit_die,
7116                         int *result_has_children,
7117                         abbrev_table_up *result_dwo_abbrev_table)
7118 {
7119   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7120   struct objfile *objfile = dwarf2_per_objfile->objfile;
7121   struct dwarf2_cu *cu = this_cu->cu;
7122   bfd *abfd;
7123   const gdb_byte *begin_info_ptr, *info_ptr;
7124   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7125   int i,num_extra_attrs;
7126   struct dwarf2_section_info *dwo_abbrev_section;
7127   struct attribute *attr;
7128   struct die_info *comp_unit_die;
7129
7130   /* At most one of these may be provided.  */
7131   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7132
7133   /* These attributes aren't processed until later:
7134      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7135      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7136      referenced later.  However, these attributes are found in the stub
7137      which we won't have later.  In order to not impose this complication
7138      on the rest of the code, we read them here and copy them to the
7139      DWO CU/TU die.  */
7140
7141   stmt_list = NULL;
7142   low_pc = NULL;
7143   high_pc = NULL;
7144   ranges = NULL;
7145   comp_dir = NULL;
7146
7147   if (stub_comp_unit_die != NULL)
7148     {
7149       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7150          DWO file.  */
7151       if (! this_cu->is_debug_types)
7152         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7153       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7154       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7155       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7156       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7157
7158       /* There should be a DW_AT_addr_base attribute here (if needed).
7159          We need the value before we can process DW_FORM_GNU_addr_index.  */
7160       cu->addr_base = 0;
7161       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7162       if (attr)
7163         cu->addr_base = DW_UNSND (attr);
7164
7165       /* There should be a DW_AT_ranges_base attribute here (if needed).
7166          We need the value before we can process DW_AT_ranges.  */
7167       cu->ranges_base = 0;
7168       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7169       if (attr)
7170         cu->ranges_base = DW_UNSND (attr);
7171     }
7172   else if (stub_comp_dir != NULL)
7173     {
7174       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7175       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7176       comp_dir->name = DW_AT_comp_dir;
7177       comp_dir->form = DW_FORM_string;
7178       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7179       DW_STRING (comp_dir) = stub_comp_dir;
7180     }
7181
7182   /* Set up for reading the DWO CU/TU.  */
7183   cu->dwo_unit = dwo_unit;
7184   dwarf2_section_info *section = dwo_unit->section;
7185   dwarf2_read_section (objfile, section);
7186   abfd = get_section_bfd_owner (section);
7187   begin_info_ptr = info_ptr = (section->buffer
7188                                + to_underlying (dwo_unit->sect_off));
7189   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7190
7191   if (this_cu->is_debug_types)
7192     {
7193       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7194
7195       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7196                                                 &cu->header, section,
7197                                                 dwo_abbrev_section,
7198                                                 info_ptr, rcuh_kind::TYPE);
7199       /* This is not an assert because it can be caused by bad debug info.  */
7200       if (sig_type->signature != cu->header.signature)
7201         {
7202           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7203                    " TU at offset %s [in module %s]"),
7204                  hex_string (sig_type->signature),
7205                  hex_string (cu->header.signature),
7206                  sect_offset_str (dwo_unit->sect_off),
7207                  bfd_get_filename (abfd));
7208         }
7209       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7210       /* For DWOs coming from DWP files, we don't know the CU length
7211          nor the type's offset in the TU until now.  */
7212       dwo_unit->length = get_cu_length (&cu->header);
7213       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7214
7215       /* Establish the type offset that can be used to lookup the type.
7216          For DWO files, we don't know it until now.  */
7217       sig_type->type_offset_in_section
7218         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7219     }
7220   else
7221     {
7222       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7223                                                 &cu->header, section,
7224                                                 dwo_abbrev_section,
7225                                                 info_ptr, rcuh_kind::COMPILE);
7226       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7227       /* For DWOs coming from DWP files, we don't know the CU length
7228          until now.  */
7229       dwo_unit->length = get_cu_length (&cu->header);
7230     }
7231
7232   *result_dwo_abbrev_table
7233     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7234                                cu->header.abbrev_sect_off);
7235   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7236                       result_dwo_abbrev_table->get ());
7237
7238   /* Read in the die, but leave space to copy over the attributes
7239      from the stub.  This has the benefit of simplifying the rest of
7240      the code - all the work to maintain the illusion of a single
7241      DW_TAG_{compile,type}_unit DIE is done here.  */
7242   num_extra_attrs = ((stmt_list != NULL)
7243                      + (low_pc != NULL)
7244                      + (high_pc != NULL)
7245                      + (ranges != NULL)
7246                      + (comp_dir != NULL));
7247   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7248                               result_has_children, num_extra_attrs);
7249
7250   /* Copy over the attributes from the stub to the DIE we just read in.  */
7251   comp_unit_die = *result_comp_unit_die;
7252   i = comp_unit_die->num_attrs;
7253   if (stmt_list != NULL)
7254     comp_unit_die->attrs[i++] = *stmt_list;
7255   if (low_pc != NULL)
7256     comp_unit_die->attrs[i++] = *low_pc;
7257   if (high_pc != NULL)
7258     comp_unit_die->attrs[i++] = *high_pc;
7259   if (ranges != NULL)
7260     comp_unit_die->attrs[i++] = *ranges;
7261   if (comp_dir != NULL)
7262     comp_unit_die->attrs[i++] = *comp_dir;
7263   comp_unit_die->num_attrs += num_extra_attrs;
7264
7265   if (dwarf_die_debug)
7266     {
7267       fprintf_unfiltered (gdb_stdlog,
7268                           "Read die from %s@0x%x of %s:\n",
7269                           get_section_name (section),
7270                           (unsigned) (begin_info_ptr - section->buffer),
7271                           bfd_get_filename (abfd));
7272       dump_die (comp_unit_die, dwarf_die_debug);
7273     }
7274
7275   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7276      TUs by skipping the stub and going directly to the entry in the DWO file.
7277      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7278      to get it via circuitous means.  Blech.  */
7279   if (comp_dir != NULL)
7280     result_reader->comp_dir = DW_STRING (comp_dir);
7281
7282   /* Skip dummy compilation units.  */
7283   if (info_ptr >= begin_info_ptr + dwo_unit->length
7284       || peek_abbrev_code (abfd, info_ptr) == 0)
7285     return 0;
7286
7287   *result_info_ptr = info_ptr;
7288   return 1;
7289 }
7290
7291 /* Subroutine of init_cutu_and_read_dies to simplify it.
7292    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7293    Returns NULL if the specified DWO unit cannot be found.  */
7294
7295 static struct dwo_unit *
7296 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7297                  struct die_info *comp_unit_die)
7298 {
7299   struct dwarf2_cu *cu = this_cu->cu;
7300   ULONGEST signature;
7301   struct dwo_unit *dwo_unit;
7302   const char *comp_dir, *dwo_name;
7303
7304   gdb_assert (cu != NULL);
7305
7306   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7307   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7308   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7309
7310   if (this_cu->is_debug_types)
7311     {
7312       struct signatured_type *sig_type;
7313
7314       /* Since this_cu is the first member of struct signatured_type,
7315          we can go from a pointer to one to a pointer to the other.  */
7316       sig_type = (struct signatured_type *) this_cu;
7317       signature = sig_type->signature;
7318       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7319     }
7320   else
7321     {
7322       struct attribute *attr;
7323
7324       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7325       if (! attr)
7326         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7327                  " [in module %s]"),
7328                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7329       signature = DW_UNSND (attr);
7330       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7331                                        signature);
7332     }
7333
7334   return dwo_unit;
7335 }
7336
7337 /* Subroutine of init_cutu_and_read_dies to simplify it.
7338    See it for a description of the parameters.
7339    Read a TU directly from a DWO file, bypassing the stub.  */
7340
7341 static void
7342 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7343                            int use_existing_cu, int keep,
7344                            die_reader_func_ftype *die_reader_func,
7345                            void *data)
7346 {
7347   std::unique_ptr<dwarf2_cu> new_cu;
7348   struct signatured_type *sig_type;
7349   struct die_reader_specs reader;
7350   const gdb_byte *info_ptr;
7351   struct die_info *comp_unit_die;
7352   int has_children;
7353   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7354
7355   /* Verify we can do the following downcast, and that we have the
7356      data we need.  */
7357   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7358   sig_type = (struct signatured_type *) this_cu;
7359   gdb_assert (sig_type->dwo_unit != NULL);
7360
7361   if (use_existing_cu && this_cu->cu != NULL)
7362     {
7363       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7364       /* There's no need to do the rereading_dwo_cu handling that
7365          init_cutu_and_read_dies does since we don't read the stub.  */
7366     }
7367   else
7368     {
7369       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7370       gdb_assert (this_cu->cu == NULL);
7371       new_cu.reset (new dwarf2_cu (this_cu));
7372     }
7373
7374   /* A future optimization, if needed, would be to use an existing
7375      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7376      could share abbrev tables.  */
7377
7378   /* The abbreviation table used by READER, this must live at least as long as
7379      READER.  */
7380   abbrev_table_up dwo_abbrev_table;
7381
7382   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7383                               NULL /* stub_comp_unit_die */,
7384                               sig_type->dwo_unit->dwo_file->comp_dir,
7385                               &reader, &info_ptr,
7386                               &comp_unit_die, &has_children,
7387                               &dwo_abbrev_table) == 0)
7388     {
7389       /* Dummy die.  */
7390       return;
7391     }
7392
7393   /* All the "real" work is done here.  */
7394   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7395
7396   /* This duplicates the code in init_cutu_and_read_dies,
7397      but the alternative is making the latter more complex.
7398      This function is only for the special case of using DWO files directly:
7399      no point in overly complicating the general case just to handle this.  */
7400   if (new_cu != NULL && keep)
7401     {
7402       /* Link this CU into read_in_chain.  */
7403       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7404       dwarf2_per_objfile->read_in_chain = this_cu;
7405       /* The chain owns it now.  */
7406       new_cu.release ();
7407     }
7408 }
7409
7410 /* Initialize a CU (or TU) and read its DIEs.
7411    If the CU defers to a DWO file, read the DWO file as well.
7412
7413    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7414    Otherwise the table specified in the comp unit header is read in and used.
7415    This is an optimization for when we already have the abbrev table.
7416
7417    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7418    Otherwise, a new CU is allocated with xmalloc.
7419
7420    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7421    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7422
7423    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7424    linker) then DIE_READER_FUNC will not get called.  */
7425
7426 static void
7427 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7428                          struct abbrev_table *abbrev_table,
7429                          int use_existing_cu, int keep,
7430                          bool skip_partial,
7431                          die_reader_func_ftype *die_reader_func,
7432                          void *data)
7433 {
7434   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7435   struct objfile *objfile = dwarf2_per_objfile->objfile;
7436   struct dwarf2_section_info *section = this_cu->section;
7437   bfd *abfd = get_section_bfd_owner (section);
7438   struct dwarf2_cu *cu;
7439   const gdb_byte *begin_info_ptr, *info_ptr;
7440   struct die_reader_specs reader;
7441   struct die_info *comp_unit_die;
7442   int has_children;
7443   struct attribute *attr;
7444   struct signatured_type *sig_type = NULL;
7445   struct dwarf2_section_info *abbrev_section;
7446   /* Non-zero if CU currently points to a DWO file and we need to
7447      reread it.  When this happens we need to reread the skeleton die
7448      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7449   int rereading_dwo_cu = 0;
7450
7451   if (dwarf_die_debug)
7452     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7453                         this_cu->is_debug_types ? "type" : "comp",
7454                         sect_offset_str (this_cu->sect_off));
7455
7456   if (use_existing_cu)
7457     gdb_assert (keep);
7458
7459   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7460      file (instead of going through the stub), short-circuit all of this.  */
7461   if (this_cu->reading_dwo_directly)
7462     {
7463       /* Narrow down the scope of possibilities to have to understand.  */
7464       gdb_assert (this_cu->is_debug_types);
7465       gdb_assert (abbrev_table == NULL);
7466       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7467                                  die_reader_func, data);
7468       return;
7469     }
7470
7471   /* This is cheap if the section is already read in.  */
7472   dwarf2_read_section (objfile, section);
7473
7474   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7475
7476   abbrev_section = get_abbrev_section_for_cu (this_cu);
7477
7478   std::unique_ptr<dwarf2_cu> new_cu;
7479   if (use_existing_cu && this_cu->cu != NULL)
7480     {
7481       cu = this_cu->cu;
7482       /* If this CU is from a DWO file we need to start over, we need to
7483          refetch the attributes from the skeleton CU.
7484          This could be optimized by retrieving those attributes from when we
7485          were here the first time: the previous comp_unit_die was stored in
7486          comp_unit_obstack.  But there's no data yet that we need this
7487          optimization.  */
7488       if (cu->dwo_unit != NULL)
7489         rereading_dwo_cu = 1;
7490     }
7491   else
7492     {
7493       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7494       gdb_assert (this_cu->cu == NULL);
7495       new_cu.reset (new dwarf2_cu (this_cu));
7496       cu = new_cu.get ();
7497     }
7498
7499   /* Get the header.  */
7500   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7501     {
7502       /* We already have the header, there's no need to read it in again.  */
7503       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7504     }
7505   else
7506     {
7507       if (this_cu->is_debug_types)
7508         {
7509           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7510                                                     &cu->header, section,
7511                                                     abbrev_section, info_ptr,
7512                                                     rcuh_kind::TYPE);
7513
7514           /* Since per_cu is the first member of struct signatured_type,
7515              we can go from a pointer to one to a pointer to the other.  */
7516           sig_type = (struct signatured_type *) this_cu;
7517           gdb_assert (sig_type->signature == cu->header.signature);
7518           gdb_assert (sig_type->type_offset_in_tu
7519                       == cu->header.type_cu_offset_in_tu);
7520           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7521
7522           /* LENGTH has not been set yet for type units if we're
7523              using .gdb_index.  */
7524           this_cu->length = get_cu_length (&cu->header);
7525
7526           /* Establish the type offset that can be used to lookup the type.  */
7527           sig_type->type_offset_in_section =
7528             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7529
7530           this_cu->dwarf_version = cu->header.version;
7531         }
7532       else
7533         {
7534           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7535                                                     &cu->header, section,
7536                                                     abbrev_section,
7537                                                     info_ptr,
7538                                                     rcuh_kind::COMPILE);
7539
7540           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7541           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7542           this_cu->dwarf_version = cu->header.version;
7543         }
7544     }
7545
7546   /* Skip dummy compilation units.  */
7547   if (info_ptr >= begin_info_ptr + this_cu->length
7548       || peek_abbrev_code (abfd, info_ptr) == 0)
7549     return;
7550
7551   /* If we don't have them yet, read the abbrevs for this compilation unit.
7552      And if we need to read them now, make sure they're freed when we're
7553      done (own the table through ABBREV_TABLE_HOLDER).  */
7554   abbrev_table_up abbrev_table_holder;
7555   if (abbrev_table != NULL)
7556     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7557   else
7558     {
7559       abbrev_table_holder
7560         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7561                                    cu->header.abbrev_sect_off);
7562       abbrev_table = abbrev_table_holder.get ();
7563     }
7564
7565   /* Read the top level CU/TU die.  */
7566   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7567   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7568
7569   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7570     return;
7571
7572   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7573      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7574      table from the DWO file and pass the ownership over to us.  It will be
7575      referenced from READER, so we must make sure to free it after we're done
7576      with READER.
7577
7578      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7579      DWO CU, that this test will fail (the attribute will not be present).  */
7580   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7581   abbrev_table_up dwo_abbrev_table;
7582   if (attr)
7583     {
7584       struct dwo_unit *dwo_unit;
7585       struct die_info *dwo_comp_unit_die;
7586
7587       if (has_children)
7588         {
7589           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7590                        " has children (offset %s) [in module %s]"),
7591                      sect_offset_str (this_cu->sect_off),
7592                      bfd_get_filename (abfd));
7593         }
7594       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7595       if (dwo_unit != NULL)
7596         {
7597           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7598                                       comp_unit_die, NULL,
7599                                       &reader, &info_ptr,
7600                                       &dwo_comp_unit_die, &has_children,
7601                                       &dwo_abbrev_table) == 0)
7602             {
7603               /* Dummy die.  */
7604               return;
7605             }
7606           comp_unit_die = dwo_comp_unit_die;
7607         }
7608       else
7609         {
7610           /* Yikes, we couldn't find the rest of the DIE, we only have
7611              the stub.  A complaint has already been logged.  There's
7612              not much more we can do except pass on the stub DIE to
7613              die_reader_func.  We don't want to throw an error on bad
7614              debug info.  */
7615         }
7616     }
7617
7618   /* All of the above is setup for this call.  Yikes.  */
7619   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7620
7621   /* Done, clean up.  */
7622   if (new_cu != NULL && keep)
7623     {
7624       /* Link this CU into read_in_chain.  */
7625       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7626       dwarf2_per_objfile->read_in_chain = this_cu;
7627       /* The chain owns it now.  */
7628       new_cu.release ();
7629     }
7630 }
7631
7632 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7633    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7634    to have already done the lookup to find the DWO file).
7635
7636    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7637    THIS_CU->is_debug_types, but nothing else.
7638
7639    We fill in THIS_CU->length.
7640
7641    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7642    linker) then DIE_READER_FUNC will not get called.
7643
7644    THIS_CU->cu is always freed when done.
7645    This is done in order to not leave THIS_CU->cu in a state where we have
7646    to care whether it refers to the "main" CU or the DWO CU.  */
7647
7648 static void
7649 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7650                                    struct dwo_file *dwo_file,
7651                                    die_reader_func_ftype *die_reader_func,
7652                                    void *data)
7653 {
7654   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7655   struct objfile *objfile = dwarf2_per_objfile->objfile;
7656   struct dwarf2_section_info *section = this_cu->section;
7657   bfd *abfd = get_section_bfd_owner (section);
7658   struct dwarf2_section_info *abbrev_section;
7659   const gdb_byte *begin_info_ptr, *info_ptr;
7660   struct die_reader_specs reader;
7661   struct die_info *comp_unit_die;
7662   int has_children;
7663
7664   if (dwarf_die_debug)
7665     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7666                         this_cu->is_debug_types ? "type" : "comp",
7667                         sect_offset_str (this_cu->sect_off));
7668
7669   gdb_assert (this_cu->cu == NULL);
7670
7671   abbrev_section = (dwo_file != NULL
7672                     ? &dwo_file->sections.abbrev
7673                     : get_abbrev_section_for_cu (this_cu));
7674
7675   /* This is cheap if the section is already read in.  */
7676   dwarf2_read_section (objfile, section);
7677
7678   struct dwarf2_cu cu (this_cu);
7679
7680   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7681   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7682                                             &cu.header, section,
7683                                             abbrev_section, info_ptr,
7684                                             (this_cu->is_debug_types
7685                                              ? rcuh_kind::TYPE
7686                                              : rcuh_kind::COMPILE));
7687
7688   this_cu->length = get_cu_length (&cu.header);
7689
7690   /* Skip dummy compilation units.  */
7691   if (info_ptr >= begin_info_ptr + this_cu->length
7692       || peek_abbrev_code (abfd, info_ptr) == 0)
7693     return;
7694
7695   abbrev_table_up abbrev_table
7696     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7697                                cu.header.abbrev_sect_off);
7698
7699   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7700   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7701
7702   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7703 }
7704
7705 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7706    does not lookup the specified DWO file.
7707    This cannot be used to read DWO files.
7708
7709    THIS_CU->cu is always freed when done.
7710    This is done in order to not leave THIS_CU->cu in a state where we have
7711    to care whether it refers to the "main" CU or the DWO CU.
7712    We can revisit this if the data shows there's a performance issue.  */
7713
7714 static void
7715 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7716                                 die_reader_func_ftype *die_reader_func,
7717                                 void *data)
7718 {
7719   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7720 }
7721 \f
7722 /* Type Unit Groups.
7723
7724    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7725    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7726    so that all types coming from the same compilation (.o file) are grouped
7727    together.  A future step could be to put the types in the same symtab as
7728    the CU the types ultimately came from.  */
7729
7730 static hashval_t
7731 hash_type_unit_group (const void *item)
7732 {
7733   const struct type_unit_group *tu_group
7734     = (const struct type_unit_group *) item;
7735
7736   return hash_stmt_list_entry (&tu_group->hash);
7737 }
7738
7739 static int
7740 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7741 {
7742   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7743   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7744
7745   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7746 }
7747
7748 /* Allocate a hash table for type unit groups.  */
7749
7750 static htab_t
7751 allocate_type_unit_groups_table (struct objfile *objfile)
7752 {
7753   return htab_create_alloc_ex (3,
7754                                hash_type_unit_group,
7755                                eq_type_unit_group,
7756                                NULL,
7757                                &objfile->objfile_obstack,
7758                                hashtab_obstack_allocate,
7759                                dummy_obstack_deallocate);
7760 }
7761
7762 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7763    partial symtabs.  We combine several TUs per psymtab to not let the size
7764    of any one psymtab grow too big.  */
7765 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7766 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7767
7768 /* Helper routine for get_type_unit_group.
7769    Create the type_unit_group object used to hold one or more TUs.  */
7770
7771 static struct type_unit_group *
7772 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7773 {
7774   struct dwarf2_per_objfile *dwarf2_per_objfile
7775     = cu->per_cu->dwarf2_per_objfile;
7776   struct objfile *objfile = dwarf2_per_objfile->objfile;
7777   struct dwarf2_per_cu_data *per_cu;
7778   struct type_unit_group *tu_group;
7779
7780   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7781                              struct type_unit_group);
7782   per_cu = &tu_group->per_cu;
7783   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7784
7785   if (dwarf2_per_objfile->using_index)
7786     {
7787       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7788                                         struct dwarf2_per_cu_quick_data);
7789     }
7790   else
7791     {
7792       unsigned int line_offset = to_underlying (line_offset_struct);
7793       struct partial_symtab *pst;
7794       std::string name;
7795
7796       /* Give the symtab a useful name for debug purposes.  */
7797       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7798         name = string_printf ("<type_units_%d>",
7799                               (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7800       else
7801         name = string_printf ("<type_units_at_0x%x>", line_offset);
7802
7803       pst = create_partial_symtab (per_cu, name.c_str ());
7804       pst->anonymous = 1;
7805     }
7806
7807   tu_group->hash.dwo_unit = cu->dwo_unit;
7808   tu_group->hash.line_sect_off = line_offset_struct;
7809
7810   return tu_group;
7811 }
7812
7813 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7814    STMT_LIST is a DW_AT_stmt_list attribute.  */
7815
7816 static struct type_unit_group *
7817 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7818 {
7819   struct dwarf2_per_objfile *dwarf2_per_objfile
7820     = cu->per_cu->dwarf2_per_objfile;
7821   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7822   struct type_unit_group *tu_group;
7823   void **slot;
7824   unsigned int line_offset;
7825   struct type_unit_group type_unit_group_for_lookup;
7826
7827   if (dwarf2_per_objfile->type_unit_groups == NULL)
7828     {
7829       dwarf2_per_objfile->type_unit_groups =
7830         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7831     }
7832
7833   /* Do we need to create a new group, or can we use an existing one?  */
7834
7835   if (stmt_list)
7836     {
7837       line_offset = DW_UNSND (stmt_list);
7838       ++tu_stats->nr_symtab_sharers;
7839     }
7840   else
7841     {
7842       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7843          We can do various things here like create one group per TU or
7844          spread them over multiple groups to split up the expansion work.
7845          To avoid worst case scenarios (too many groups or too large groups)
7846          we, umm, group them in bunches.  */
7847       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7848                      | (tu_stats->nr_stmt_less_type_units
7849                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7850       ++tu_stats->nr_stmt_less_type_units;
7851     }
7852
7853   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7854   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7855   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7856                          &type_unit_group_for_lookup, INSERT);
7857   if (*slot != NULL)
7858     {
7859       tu_group = (struct type_unit_group *) *slot;
7860       gdb_assert (tu_group != NULL);
7861     }
7862   else
7863     {
7864       sect_offset line_offset_struct = (sect_offset) line_offset;
7865       tu_group = create_type_unit_group (cu, line_offset_struct);
7866       *slot = tu_group;
7867       ++tu_stats->nr_symtabs;
7868     }
7869
7870   return tu_group;
7871 }
7872 \f
7873 /* Partial symbol tables.  */
7874
7875 /* Create a psymtab named NAME and assign it to PER_CU.
7876
7877    The caller must fill in the following details:
7878    dirname, textlow, texthigh.  */
7879
7880 static struct partial_symtab *
7881 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7882 {
7883   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7884   struct partial_symtab *pst;
7885
7886   pst = start_psymtab_common (objfile, name, 0,
7887                               objfile->global_psymbols,
7888                               objfile->static_psymbols);
7889
7890   pst->psymtabs_addrmap_supported = 1;
7891
7892   /* This is the glue that links PST into GDB's symbol API.  */
7893   pst->read_symtab_private = per_cu;
7894   pst->read_symtab = dwarf2_read_symtab;
7895   per_cu->v.psymtab = pst;
7896
7897   return pst;
7898 }
7899
7900 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7901    type.  */
7902
7903 struct process_psymtab_comp_unit_data
7904 {
7905   /* True if we are reading a DW_TAG_partial_unit.  */
7906
7907   int want_partial_unit;
7908
7909   /* The "pretend" language that is used if the CU doesn't declare a
7910      language.  */
7911
7912   enum language pretend_language;
7913 };
7914
7915 /* die_reader_func for process_psymtab_comp_unit.  */
7916
7917 static void
7918 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7919                                   const gdb_byte *info_ptr,
7920                                   struct die_info *comp_unit_die,
7921                                   int has_children,
7922                                   void *data)
7923 {
7924   struct dwarf2_cu *cu = reader->cu;
7925   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7926   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7927   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7928   CORE_ADDR baseaddr;
7929   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7930   struct partial_symtab *pst;
7931   enum pc_bounds_kind cu_bounds_kind;
7932   const char *filename;
7933   struct process_psymtab_comp_unit_data *info
7934     = (struct process_psymtab_comp_unit_data *) data;
7935
7936   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7937     return;
7938
7939   gdb_assert (! per_cu->is_debug_types);
7940
7941   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7942
7943   /* Allocate a new partial symbol table structure.  */
7944   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7945   if (filename == NULL)
7946     filename = "";
7947
7948   pst = create_partial_symtab (per_cu, filename);
7949
7950   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7951   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7952
7953   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7954
7955   dwarf2_find_base_address (comp_unit_die, cu);
7956
7957   /* Possibly set the default values of LOWPC and HIGHPC from
7958      `DW_AT_ranges'.  */
7959   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7960                                          &best_highpc, cu, pst);
7961   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7962     {
7963       CORE_ADDR low
7964         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr)
7965            - baseaddr);
7966       CORE_ADDR high
7967         = (gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr)
7968            - baseaddr - 1);
7969       /* Store the contiguous range if it is not empty; it can be
7970          empty for CUs with no code.  */
7971       addrmap_set_empty (objfile->psymtabs_addrmap, low, high, pst);
7972     }
7973
7974   /* Check if comp unit has_children.
7975      If so, read the rest of the partial symbols from this comp unit.
7976      If not, there's no more debug_info for this comp unit.  */
7977   if (has_children)
7978     {
7979       struct partial_die_info *first_die;
7980       CORE_ADDR lowpc, highpc;
7981
7982       lowpc = ((CORE_ADDR) -1);
7983       highpc = ((CORE_ADDR) 0);
7984
7985       first_die = load_partial_dies (reader, info_ptr, 1);
7986
7987       scan_partial_symbols (first_die, &lowpc, &highpc,
7988                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7989
7990       /* If we didn't find a lowpc, set it to highpc to avoid
7991          complaints from `maint check'.  */
7992       if (lowpc == ((CORE_ADDR) -1))
7993         lowpc = highpc;
7994
7995       /* If the compilation unit didn't have an explicit address range,
7996          then use the information extracted from its child dies.  */
7997       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7998         {
7999           best_lowpc = lowpc;
8000           best_highpc = highpc;
8001         }
8002     }
8003   pst->set_text_low (gdbarch_adjust_dwarf2_addr (gdbarch,
8004                                                  best_lowpc + baseaddr)
8005                      - baseaddr);
8006   pst->set_text_high (gdbarch_adjust_dwarf2_addr (gdbarch,
8007                                                   best_highpc + baseaddr)
8008                       - baseaddr);
8009
8010   end_psymtab_common (objfile, pst);
8011
8012   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
8013     {
8014       int i;
8015       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8016       struct dwarf2_per_cu_data *iter;
8017
8018       /* Fill in 'dependencies' here; we fill in 'users' in a
8019          post-pass.  */
8020       pst->number_of_dependencies = len;
8021       pst->dependencies =
8022         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8023       for (i = 0;
8024            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8025                         i, iter);
8026            ++i)
8027         pst->dependencies[i] = iter->v.psymtab;
8028
8029       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
8030     }
8031
8032   /* Get the list of files included in the current compilation unit,
8033      and build a psymtab for each of them.  */
8034   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
8035
8036   if (dwarf_read_debug)
8037     {
8038       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8039
8040       fprintf_unfiltered (gdb_stdlog,
8041                           "Psymtab for %s unit @%s: %s - %s"
8042                           ", %d global, %d static syms\n",
8043                           per_cu->is_debug_types ? "type" : "comp",
8044                           sect_offset_str (per_cu->sect_off),
8045                           paddress (gdbarch, pst->text_low (objfile)),
8046                           paddress (gdbarch, pst->text_high (objfile)),
8047                           pst->n_global_syms, pst->n_static_syms);
8048     }
8049 }
8050
8051 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8052    Process compilation unit THIS_CU for a psymtab.  */
8053
8054 static void
8055 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8056                            int want_partial_unit,
8057                            enum language pretend_language)
8058 {
8059   /* If this compilation unit was already read in, free the
8060      cached copy in order to read it in again.  This is
8061      necessary because we skipped some symbols when we first
8062      read in the compilation unit (see load_partial_dies).
8063      This problem could be avoided, but the benefit is unclear.  */
8064   if (this_cu->cu != NULL)
8065     free_one_cached_comp_unit (this_cu);
8066
8067   if (this_cu->is_debug_types)
8068     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8069                              build_type_psymtabs_reader, NULL);
8070   else
8071     {
8072       process_psymtab_comp_unit_data info;
8073       info.want_partial_unit = want_partial_unit;
8074       info.pretend_language = pretend_language;
8075       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8076                                process_psymtab_comp_unit_reader, &info);
8077     }
8078
8079   /* Age out any secondary CUs.  */
8080   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8081 }
8082
8083 /* Reader function for build_type_psymtabs.  */
8084
8085 static void
8086 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8087                             const gdb_byte *info_ptr,
8088                             struct die_info *type_unit_die,
8089                             int has_children,
8090                             void *data)
8091 {
8092   struct dwarf2_per_objfile *dwarf2_per_objfile
8093     = reader->cu->per_cu->dwarf2_per_objfile;
8094   struct objfile *objfile = dwarf2_per_objfile->objfile;
8095   struct dwarf2_cu *cu = reader->cu;
8096   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8097   struct signatured_type *sig_type;
8098   struct type_unit_group *tu_group;
8099   struct attribute *attr;
8100   struct partial_die_info *first_die;
8101   CORE_ADDR lowpc, highpc;
8102   struct partial_symtab *pst;
8103
8104   gdb_assert (data == NULL);
8105   gdb_assert (per_cu->is_debug_types);
8106   sig_type = (struct signatured_type *) per_cu;
8107
8108   if (! has_children)
8109     return;
8110
8111   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8112   tu_group = get_type_unit_group (cu, attr);
8113
8114   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8115
8116   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8117   pst = create_partial_symtab (per_cu, "");
8118   pst->anonymous = 1;
8119
8120   first_die = load_partial_dies (reader, info_ptr, 1);
8121
8122   lowpc = (CORE_ADDR) -1;
8123   highpc = (CORE_ADDR) 0;
8124   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8125
8126   end_psymtab_common (objfile, pst);
8127 }
8128
8129 /* Struct used to sort TUs by their abbreviation table offset.  */
8130
8131 struct tu_abbrev_offset
8132 {
8133   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8134   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8135   {}
8136
8137   signatured_type *sig_type;
8138   sect_offset abbrev_offset;
8139 };
8140
8141 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8142
8143 static bool
8144 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8145                           const struct tu_abbrev_offset &b)
8146 {
8147   return a.abbrev_offset < b.abbrev_offset;
8148 }
8149
8150 /* Efficiently read all the type units.
8151    This does the bulk of the work for build_type_psymtabs.
8152
8153    The efficiency is because we sort TUs by the abbrev table they use and
8154    only read each abbrev table once.  In one program there are 200K TUs
8155    sharing 8K abbrev tables.
8156
8157    The main purpose of this function is to support building the
8158    dwarf2_per_objfile->type_unit_groups table.
8159    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8160    can collapse the search space by grouping them by stmt_list.
8161    The savings can be significant, in the same program from above the 200K TUs
8162    share 8K stmt_list tables.
8163
8164    FUNC is expected to call get_type_unit_group, which will create the
8165    struct type_unit_group if necessary and add it to
8166    dwarf2_per_objfile->type_unit_groups.  */
8167
8168 static void
8169 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8170 {
8171   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8172   abbrev_table_up abbrev_table;
8173   sect_offset abbrev_offset;
8174
8175   /* It's up to the caller to not call us multiple times.  */
8176   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8177
8178   if (dwarf2_per_objfile->all_type_units.empty ())
8179     return;
8180
8181   /* TUs typically share abbrev tables, and there can be way more TUs than
8182      abbrev tables.  Sort by abbrev table to reduce the number of times we
8183      read each abbrev table in.
8184      Alternatives are to punt or to maintain a cache of abbrev tables.
8185      This is simpler and efficient enough for now.
8186
8187      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8188      symtab to use).  Typically TUs with the same abbrev offset have the same
8189      stmt_list value too so in practice this should work well.
8190
8191      The basic algorithm here is:
8192
8193       sort TUs by abbrev table
8194       for each TU with same abbrev table:
8195         read abbrev table if first user
8196         read TU top level DIE
8197           [IWBN if DWO skeletons had DW_AT_stmt_list]
8198         call FUNC  */
8199
8200   if (dwarf_read_debug)
8201     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8202
8203   /* Sort in a separate table to maintain the order of all_type_units
8204      for .gdb_index: TU indices directly index all_type_units.  */
8205   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8206   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8207
8208   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8209     sorted_by_abbrev.emplace_back
8210       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8211                                      sig_type->per_cu.section,
8212                                      sig_type->per_cu.sect_off));
8213
8214   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8215              sort_tu_by_abbrev_offset);
8216
8217   abbrev_offset = (sect_offset) ~(unsigned) 0;
8218
8219   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8220     {
8221       /* Switch to the next abbrev table if necessary.  */
8222       if (abbrev_table == NULL
8223           || tu.abbrev_offset != abbrev_offset)
8224         {
8225           abbrev_offset = tu.abbrev_offset;
8226           abbrev_table =
8227             abbrev_table_read_table (dwarf2_per_objfile,
8228                                      &dwarf2_per_objfile->abbrev,
8229                                      abbrev_offset);
8230           ++tu_stats->nr_uniq_abbrev_tables;
8231         }
8232
8233       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8234                                0, 0, false, build_type_psymtabs_reader, NULL);
8235     }
8236 }
8237
8238 /* Print collected type unit statistics.  */
8239
8240 static void
8241 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8242 {
8243   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8244
8245   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8246   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8247                       dwarf2_per_objfile->all_type_units.size ());
8248   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8249                       tu_stats->nr_uniq_abbrev_tables);
8250   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8251                       tu_stats->nr_symtabs);
8252   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8253                       tu_stats->nr_symtab_sharers);
8254   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8255                       tu_stats->nr_stmt_less_type_units);
8256   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8257                       tu_stats->nr_all_type_units_reallocs);
8258 }
8259
8260 /* Traversal function for build_type_psymtabs.  */
8261
8262 static int
8263 build_type_psymtab_dependencies (void **slot, void *info)
8264 {
8265   struct dwarf2_per_objfile *dwarf2_per_objfile
8266     = (struct dwarf2_per_objfile *) info;
8267   struct objfile *objfile = dwarf2_per_objfile->objfile;
8268   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8269   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8270   struct partial_symtab *pst = per_cu->v.psymtab;
8271   int len = VEC_length (sig_type_ptr, tu_group->tus);
8272   struct signatured_type *iter;
8273   int i;
8274
8275   gdb_assert (len > 0);
8276   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8277
8278   pst->number_of_dependencies = len;
8279   pst->dependencies =
8280     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8281   for (i = 0;
8282        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8283        ++i)
8284     {
8285       gdb_assert (iter->per_cu.is_debug_types);
8286       pst->dependencies[i] = iter->per_cu.v.psymtab;
8287       iter->type_unit_group = tu_group;
8288     }
8289
8290   VEC_free (sig_type_ptr, tu_group->tus);
8291
8292   return 1;
8293 }
8294
8295 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8296    Build partial symbol tables for the .debug_types comp-units.  */
8297
8298 static void
8299 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8300 {
8301   if (! create_all_type_units (dwarf2_per_objfile))
8302     return;
8303
8304   build_type_psymtabs_1 (dwarf2_per_objfile);
8305 }
8306
8307 /* Traversal function for process_skeletonless_type_unit.
8308    Read a TU in a DWO file and build partial symbols for it.  */
8309
8310 static int
8311 process_skeletonless_type_unit (void **slot, void *info)
8312 {
8313   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8314   struct dwarf2_per_objfile *dwarf2_per_objfile
8315     = (struct dwarf2_per_objfile *) info;
8316   struct signatured_type find_entry, *entry;
8317
8318   /* If this TU doesn't exist in the global table, add it and read it in.  */
8319
8320   if (dwarf2_per_objfile->signatured_types == NULL)
8321     {
8322       dwarf2_per_objfile->signatured_types
8323         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8324     }
8325
8326   find_entry.signature = dwo_unit->signature;
8327   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8328                          INSERT);
8329   /* If we've already seen this type there's nothing to do.  What's happening
8330      is we're doing our own version of comdat-folding here.  */
8331   if (*slot != NULL)
8332     return 1;
8333
8334   /* This does the job that create_all_type_units would have done for
8335      this TU.  */
8336   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8337   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8338   *slot = entry;
8339
8340   /* This does the job that build_type_psymtabs_1 would have done.  */
8341   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8342                            build_type_psymtabs_reader, NULL);
8343
8344   return 1;
8345 }
8346
8347 /* Traversal function for process_skeletonless_type_units.  */
8348
8349 static int
8350 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8351 {
8352   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8353
8354   if (dwo_file->tus != NULL)
8355     {
8356       htab_traverse_noresize (dwo_file->tus,
8357                               process_skeletonless_type_unit, info);
8358     }
8359
8360   return 1;
8361 }
8362
8363 /* Scan all TUs of DWO files, verifying we've processed them.
8364    This is needed in case a TU was emitted without its skeleton.
8365    Note: This can't be done until we know what all the DWO files are.  */
8366
8367 static void
8368 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8369 {
8370   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8371   if (get_dwp_file (dwarf2_per_objfile) == NULL
8372       && dwarf2_per_objfile->dwo_files != NULL)
8373     {
8374       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8375                               process_dwo_file_for_skeletonless_type_units,
8376                               dwarf2_per_objfile);
8377     }
8378 }
8379
8380 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8381
8382 static void
8383 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8384 {
8385   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8386     {
8387       struct partial_symtab *pst = per_cu->v.psymtab;
8388
8389       if (pst == NULL)
8390         continue;
8391
8392       for (int j = 0; j < pst->number_of_dependencies; ++j)
8393         {
8394           /* Set the 'user' field only if it is not already set.  */
8395           if (pst->dependencies[j]->user == NULL)
8396             pst->dependencies[j]->user = pst;
8397         }
8398     }
8399 }
8400
8401 /* Build the partial symbol table by doing a quick pass through the
8402    .debug_info and .debug_abbrev sections.  */
8403
8404 static void
8405 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8406 {
8407   struct objfile *objfile = dwarf2_per_objfile->objfile;
8408
8409   if (dwarf_read_debug)
8410     {
8411       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8412                           objfile_name (objfile));
8413     }
8414
8415   dwarf2_per_objfile->reading_partial_symbols = 1;
8416
8417   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8418
8419   /* Any cached compilation units will be linked by the per-objfile
8420      read_in_chain.  Make sure to free them when we're done.  */
8421   free_cached_comp_units freer (dwarf2_per_objfile);
8422
8423   build_type_psymtabs (dwarf2_per_objfile);
8424
8425   create_all_comp_units (dwarf2_per_objfile);
8426
8427   /* Create a temporary address map on a temporary obstack.  We later
8428      copy this to the final obstack.  */
8429   auto_obstack temp_obstack;
8430
8431   scoped_restore save_psymtabs_addrmap
8432     = make_scoped_restore (&objfile->psymtabs_addrmap,
8433                            addrmap_create_mutable (&temp_obstack));
8434
8435   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8436     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8437
8438   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8439   process_skeletonless_type_units (dwarf2_per_objfile);
8440
8441   /* Now that all TUs have been processed we can fill in the dependencies.  */
8442   if (dwarf2_per_objfile->type_unit_groups != NULL)
8443     {
8444       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8445                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8446     }
8447
8448   if (dwarf_read_debug)
8449     print_tu_stats (dwarf2_per_objfile);
8450
8451   set_partial_user (dwarf2_per_objfile);
8452
8453   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8454                                                     &objfile->objfile_obstack);
8455   /* At this point we want to keep the address map.  */
8456   save_psymtabs_addrmap.release ();
8457
8458   if (dwarf_read_debug)
8459     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8460                         objfile_name (objfile));
8461 }
8462
8463 /* die_reader_func for load_partial_comp_unit.  */
8464
8465 static void
8466 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8467                                const gdb_byte *info_ptr,
8468                                struct die_info *comp_unit_die,
8469                                int has_children,
8470                                void *data)
8471 {
8472   struct dwarf2_cu *cu = reader->cu;
8473
8474   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8475
8476   /* Check if comp unit has_children.
8477      If so, read the rest of the partial symbols from this comp unit.
8478      If not, there's no more debug_info for this comp unit.  */
8479   if (has_children)
8480     load_partial_dies (reader, info_ptr, 0);
8481 }
8482
8483 /* Load the partial DIEs for a secondary CU into memory.
8484    This is also used when rereading a primary CU with load_all_dies.  */
8485
8486 static void
8487 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8488 {
8489   init_cutu_and_read_dies (this_cu, NULL, 1, 1, false,
8490                            load_partial_comp_unit_reader, NULL);
8491 }
8492
8493 static void
8494 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8495                               struct dwarf2_section_info *section,
8496                               struct dwarf2_section_info *abbrev_section,
8497                               unsigned int is_dwz)
8498 {
8499   const gdb_byte *info_ptr;
8500   struct objfile *objfile = dwarf2_per_objfile->objfile;
8501
8502   if (dwarf_read_debug)
8503     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8504                         get_section_name (section),
8505                         get_section_file_name (section));
8506
8507   dwarf2_read_section (objfile, section);
8508
8509   info_ptr = section->buffer;
8510
8511   while (info_ptr < section->buffer + section->size)
8512     {
8513       struct dwarf2_per_cu_data *this_cu;
8514
8515       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8516
8517       comp_unit_head cu_header;
8518       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8519                                      abbrev_section, info_ptr,
8520                                      rcuh_kind::COMPILE);
8521
8522       /* Save the compilation unit for later lookup.  */
8523       if (cu_header.unit_type != DW_UT_type)
8524         {
8525           this_cu = XOBNEW (&objfile->objfile_obstack,
8526                             struct dwarf2_per_cu_data);
8527           memset (this_cu, 0, sizeof (*this_cu));
8528         }
8529       else
8530         {
8531           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8532                                   struct signatured_type);
8533           memset (sig_type, 0, sizeof (*sig_type));
8534           sig_type->signature = cu_header.signature;
8535           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8536           this_cu = &sig_type->per_cu;
8537         }
8538       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8539       this_cu->sect_off = sect_off;
8540       this_cu->length = cu_header.length + cu_header.initial_length_size;
8541       this_cu->is_dwz = is_dwz;
8542       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8543       this_cu->section = section;
8544
8545       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8546
8547       info_ptr = info_ptr + this_cu->length;
8548     }
8549 }
8550
8551 /* Create a list of all compilation units in OBJFILE.
8552    This is only done for -readnow and building partial symtabs.  */
8553
8554 static void
8555 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8556 {
8557   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8558   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8559                                 &dwarf2_per_objfile->abbrev, 0);
8560
8561   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8562   if (dwz != NULL)
8563     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8564                                   1);
8565 }
8566
8567 /* Process all loaded DIEs for compilation unit CU, starting at
8568    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8569    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8570    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8571    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8572
8573 static void
8574 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8575                       CORE_ADDR *highpc, int set_addrmap,
8576                       struct dwarf2_cu *cu)
8577 {
8578   struct partial_die_info *pdi;
8579
8580   /* Now, march along the PDI's, descending into ones which have
8581      interesting children but skipping the children of the other ones,
8582      until we reach the end of the compilation unit.  */
8583
8584   pdi = first_die;
8585
8586   while (pdi != NULL)
8587     {
8588       pdi->fixup (cu);
8589
8590       /* Anonymous namespaces or modules have no name but have interesting
8591          children, so we need to look at them.  Ditto for anonymous
8592          enums.  */
8593
8594       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8595           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8596           || pdi->tag == DW_TAG_imported_unit
8597           || pdi->tag == DW_TAG_inlined_subroutine)
8598         {
8599           switch (pdi->tag)
8600             {
8601             case DW_TAG_subprogram:
8602             case DW_TAG_inlined_subroutine:
8603               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8604               break;
8605             case DW_TAG_constant:
8606             case DW_TAG_variable:
8607             case DW_TAG_typedef:
8608             case DW_TAG_union_type:
8609               if (!pdi->is_declaration)
8610                 {
8611                   add_partial_symbol (pdi, cu);
8612                 }
8613               break;
8614             case DW_TAG_class_type:
8615             case DW_TAG_interface_type:
8616             case DW_TAG_structure_type:
8617               if (!pdi->is_declaration)
8618                 {
8619                   add_partial_symbol (pdi, cu);
8620                 }
8621               if ((cu->language == language_rust
8622                    || cu->language == language_cplus) && pdi->has_children)
8623                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8624                                       set_addrmap, cu);
8625               break;
8626             case DW_TAG_enumeration_type:
8627               if (!pdi->is_declaration)
8628                 add_partial_enumeration (pdi, cu);
8629               break;
8630             case DW_TAG_base_type:
8631             case DW_TAG_subrange_type:
8632               /* File scope base type definitions are added to the partial
8633                  symbol table.  */
8634               add_partial_symbol (pdi, cu);
8635               break;
8636             case DW_TAG_namespace:
8637               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8638               break;
8639             case DW_TAG_module:
8640               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8641               break;
8642             case DW_TAG_imported_unit:
8643               {
8644                 struct dwarf2_per_cu_data *per_cu;
8645
8646                 /* For now we don't handle imported units in type units.  */
8647                 if (cu->per_cu->is_debug_types)
8648                   {
8649                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8650                              " supported in type units [in module %s]"),
8651                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8652                   }
8653
8654                 per_cu = dwarf2_find_containing_comp_unit
8655                            (pdi->d.sect_off, pdi->is_dwz,
8656                             cu->per_cu->dwarf2_per_objfile);
8657
8658                 /* Go read the partial unit, if needed.  */
8659                 if (per_cu->v.psymtab == NULL)
8660                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8661
8662                 VEC_safe_push (dwarf2_per_cu_ptr,
8663                                cu->per_cu->imported_symtabs, per_cu);
8664               }
8665               break;
8666             case DW_TAG_imported_declaration:
8667               add_partial_symbol (pdi, cu);
8668               break;
8669             default:
8670               break;
8671             }
8672         }
8673
8674       /* If the die has a sibling, skip to the sibling.  */
8675
8676       pdi = pdi->die_sibling;
8677     }
8678 }
8679
8680 /* Functions used to compute the fully scoped name of a partial DIE.
8681
8682    Normally, this is simple.  For C++, the parent DIE's fully scoped
8683    name is concatenated with "::" and the partial DIE's name.
8684    Enumerators are an exception; they use the scope of their parent
8685    enumeration type, i.e. the name of the enumeration type is not
8686    prepended to the enumerator.
8687
8688    There are two complexities.  One is DW_AT_specification; in this
8689    case "parent" means the parent of the target of the specification,
8690    instead of the direct parent of the DIE.  The other is compilers
8691    which do not emit DW_TAG_namespace; in this case we try to guess
8692    the fully qualified name of structure types from their members'
8693    linkage names.  This must be done using the DIE's children rather
8694    than the children of any DW_AT_specification target.  We only need
8695    to do this for structures at the top level, i.e. if the target of
8696    any DW_AT_specification (if any; otherwise the DIE itself) does not
8697    have a parent.  */
8698
8699 /* Compute the scope prefix associated with PDI's parent, in
8700    compilation unit CU.  The result will be allocated on CU's
8701    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8702    field.  NULL is returned if no prefix is necessary.  */
8703 static const char *
8704 partial_die_parent_scope (struct partial_die_info *pdi,
8705                           struct dwarf2_cu *cu)
8706 {
8707   const char *grandparent_scope;
8708   struct partial_die_info *parent, *real_pdi;
8709
8710   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8711      then this means the parent of the specification DIE.  */
8712
8713   real_pdi = pdi;
8714   while (real_pdi->has_specification)
8715     real_pdi = find_partial_die (real_pdi->spec_offset,
8716                                  real_pdi->spec_is_dwz, cu);
8717
8718   parent = real_pdi->die_parent;
8719   if (parent == NULL)
8720     return NULL;
8721
8722   if (parent->scope_set)
8723     return parent->scope;
8724
8725   parent->fixup (cu);
8726
8727   grandparent_scope = partial_die_parent_scope (parent, cu);
8728
8729   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8730      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8731      Work around this problem here.  */
8732   if (cu->language == language_cplus
8733       && parent->tag == DW_TAG_namespace
8734       && strcmp (parent->name, "::") == 0
8735       && grandparent_scope == NULL)
8736     {
8737       parent->scope = NULL;
8738       parent->scope_set = 1;
8739       return NULL;
8740     }
8741
8742   if (pdi->tag == DW_TAG_enumerator)
8743     /* Enumerators should not get the name of the enumeration as a prefix.  */
8744     parent->scope = grandparent_scope;
8745   else if (parent->tag == DW_TAG_namespace
8746       || parent->tag == DW_TAG_module
8747       || parent->tag == DW_TAG_structure_type
8748       || parent->tag == DW_TAG_class_type
8749       || parent->tag == DW_TAG_interface_type
8750       || parent->tag == DW_TAG_union_type
8751       || parent->tag == DW_TAG_enumeration_type)
8752     {
8753       if (grandparent_scope == NULL)
8754         parent->scope = parent->name;
8755       else
8756         parent->scope = typename_concat (&cu->comp_unit_obstack,
8757                                          grandparent_scope,
8758                                          parent->name, 0, cu);
8759     }
8760   else
8761     {
8762       /* FIXME drow/2004-04-01: What should we be doing with
8763          function-local names?  For partial symbols, we should probably be
8764          ignoring them.  */
8765       complaint (_("unhandled containing DIE tag %d for DIE at %s"),
8766                  parent->tag, sect_offset_str (pdi->sect_off));
8767       parent->scope = grandparent_scope;
8768     }
8769
8770   parent->scope_set = 1;
8771   return parent->scope;
8772 }
8773
8774 /* Return the fully scoped name associated with PDI, from compilation unit
8775    CU.  The result will be allocated with malloc.  */
8776
8777 static char *
8778 partial_die_full_name (struct partial_die_info *pdi,
8779                        struct dwarf2_cu *cu)
8780 {
8781   const char *parent_scope;
8782
8783   /* If this is a template instantiation, we can not work out the
8784      template arguments from partial DIEs.  So, unfortunately, we have
8785      to go through the full DIEs.  At least any work we do building
8786      types here will be reused if full symbols are loaded later.  */
8787   if (pdi->has_template_arguments)
8788     {
8789       pdi->fixup (cu);
8790
8791       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8792         {
8793           struct die_info *die;
8794           struct attribute attr;
8795           struct dwarf2_cu *ref_cu = cu;
8796
8797           /* DW_FORM_ref_addr is using section offset.  */
8798           attr.name = (enum dwarf_attribute) 0;
8799           attr.form = DW_FORM_ref_addr;
8800           attr.u.unsnd = to_underlying (pdi->sect_off);
8801           die = follow_die_ref (NULL, &attr, &ref_cu);
8802
8803           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8804         }
8805     }
8806
8807   parent_scope = partial_die_parent_scope (pdi, cu);
8808   if (parent_scope == NULL)
8809     return NULL;
8810   else
8811     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8812 }
8813
8814 static void
8815 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8816 {
8817   struct dwarf2_per_objfile *dwarf2_per_objfile
8818     = cu->per_cu->dwarf2_per_objfile;
8819   struct objfile *objfile = dwarf2_per_objfile->objfile;
8820   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8821   CORE_ADDR addr = 0;
8822   const char *actual_name = NULL;
8823   CORE_ADDR baseaddr;
8824   char *built_actual_name;
8825
8826   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8827
8828   built_actual_name = partial_die_full_name (pdi, cu);
8829   if (built_actual_name != NULL)
8830     actual_name = built_actual_name;
8831
8832   if (actual_name == NULL)
8833     actual_name = pdi->name;
8834
8835   switch (pdi->tag)
8836     {
8837     case DW_TAG_inlined_subroutine:
8838     case DW_TAG_subprogram:
8839       addr = (gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr)
8840               - baseaddr);
8841       if (pdi->is_external || cu->language == language_ada)
8842         {
8843           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8844              of the global scope.  But in Ada, we want to be able to access
8845              nested procedures globally.  So all Ada subprograms are stored
8846              in the global scope.  */
8847           add_psymbol_to_list (actual_name, strlen (actual_name),
8848                                built_actual_name != NULL,
8849                                VAR_DOMAIN, LOC_BLOCK,
8850                                SECT_OFF_TEXT (objfile),
8851                                &objfile->global_psymbols,
8852                                addr,
8853                                cu->language, objfile);
8854         }
8855       else
8856         {
8857           add_psymbol_to_list (actual_name, strlen (actual_name),
8858                                built_actual_name != NULL,
8859                                VAR_DOMAIN, LOC_BLOCK,
8860                                SECT_OFF_TEXT (objfile),
8861                                &objfile->static_psymbols,
8862                                addr, cu->language, objfile);
8863         }
8864
8865       if (pdi->main_subprogram && actual_name != NULL)
8866         set_objfile_main_name (objfile, actual_name, cu->language);
8867       break;
8868     case DW_TAG_constant:
8869       {
8870         std::vector<partial_symbol *> *list;
8871
8872         if (pdi->is_external)
8873           list = &objfile->global_psymbols;
8874         else
8875           list = &objfile->static_psymbols;
8876         add_psymbol_to_list (actual_name, strlen (actual_name),
8877                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8878                              -1, list, 0, cu->language, objfile);
8879       }
8880       break;
8881     case DW_TAG_variable:
8882       if (pdi->d.locdesc)
8883         addr = decode_locdesc (pdi->d.locdesc, cu);
8884
8885       if (pdi->d.locdesc
8886           && addr == 0
8887           && !dwarf2_per_objfile->has_section_at_zero)
8888         {
8889           /* A global or static variable may also have been stripped
8890              out by the linker if unused, in which case its address
8891              will be nullified; do not add such variables into partial
8892              symbol table then.  */
8893         }
8894       else if (pdi->is_external)
8895         {
8896           /* Global Variable.
8897              Don't enter into the minimal symbol tables as there is
8898              a minimal symbol table entry from the ELF symbols already.
8899              Enter into partial symbol table if it has a location
8900              descriptor or a type.
8901              If the location descriptor is missing, new_symbol will create
8902              a LOC_UNRESOLVED symbol, the address of the variable will then
8903              be determined from the minimal symbol table whenever the variable
8904              is referenced.
8905              The address for the partial symbol table entry is not
8906              used by GDB, but it comes in handy for debugging partial symbol
8907              table building.  */
8908
8909           if (pdi->d.locdesc || pdi->has_type)
8910             add_psymbol_to_list (actual_name, strlen (actual_name),
8911                                  built_actual_name != NULL,
8912                                  VAR_DOMAIN, LOC_STATIC,
8913                                  SECT_OFF_TEXT (objfile),
8914                                  &objfile->global_psymbols,
8915                                  addr, cu->language, objfile);
8916         }
8917       else
8918         {
8919           int has_loc = pdi->d.locdesc != NULL;
8920
8921           /* Static Variable.  Skip symbols whose value we cannot know (those
8922              without location descriptors or constant values).  */
8923           if (!has_loc && !pdi->has_const_value)
8924             {
8925               xfree (built_actual_name);
8926               return;
8927             }
8928
8929           add_psymbol_to_list (actual_name, strlen (actual_name),
8930                                built_actual_name != NULL,
8931                                VAR_DOMAIN, LOC_STATIC,
8932                                SECT_OFF_TEXT (objfile),
8933                                &objfile->static_psymbols,
8934                                has_loc ? addr : 0,
8935                                cu->language, objfile);
8936         }
8937       break;
8938     case DW_TAG_typedef:
8939     case DW_TAG_base_type:
8940     case DW_TAG_subrange_type:
8941       add_psymbol_to_list (actual_name, strlen (actual_name),
8942                            built_actual_name != NULL,
8943                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8944                            &objfile->static_psymbols,
8945                            0, cu->language, objfile);
8946       break;
8947     case DW_TAG_imported_declaration:
8948     case DW_TAG_namespace:
8949       add_psymbol_to_list (actual_name, strlen (actual_name),
8950                            built_actual_name != NULL,
8951                            VAR_DOMAIN, LOC_TYPEDEF, -1,
8952                            &objfile->global_psymbols,
8953                            0, cu->language, objfile);
8954       break;
8955     case DW_TAG_module:
8956       add_psymbol_to_list (actual_name, strlen (actual_name),
8957                            built_actual_name != NULL,
8958                            MODULE_DOMAIN, LOC_TYPEDEF, -1,
8959                            &objfile->global_psymbols,
8960                            0, cu->language, objfile);
8961       break;
8962     case DW_TAG_class_type:
8963     case DW_TAG_interface_type:
8964     case DW_TAG_structure_type:
8965     case DW_TAG_union_type:
8966     case DW_TAG_enumeration_type:
8967       /* Skip external references.  The DWARF standard says in the section
8968          about "Structure, Union, and Class Type Entries": "An incomplete
8969          structure, union or class type is represented by a structure,
8970          union or class entry that does not have a byte size attribute
8971          and that has a DW_AT_declaration attribute."  */
8972       if (!pdi->has_byte_size && pdi->is_declaration)
8973         {
8974           xfree (built_actual_name);
8975           return;
8976         }
8977
8978       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8979          static vs. global.  */
8980       add_psymbol_to_list (actual_name, strlen (actual_name),
8981                            built_actual_name != NULL,
8982                            STRUCT_DOMAIN, LOC_TYPEDEF, -1,
8983                            cu->language == language_cplus
8984                            ? &objfile->global_psymbols
8985                            : &objfile->static_psymbols,
8986                            0, cu->language, objfile);
8987
8988       break;
8989     case DW_TAG_enumerator:
8990       add_psymbol_to_list (actual_name, strlen (actual_name),
8991                            built_actual_name != NULL,
8992                            VAR_DOMAIN, LOC_CONST, -1,
8993                            cu->language == language_cplus
8994                            ? &objfile->global_psymbols
8995                            : &objfile->static_psymbols,
8996                            0, cu->language, objfile);
8997       break;
8998     default:
8999       break;
9000     }
9001
9002   xfree (built_actual_name);
9003 }
9004
9005 /* Read a partial die corresponding to a namespace; also, add a symbol
9006    corresponding to that namespace to the symbol table.  NAMESPACE is
9007    the name of the enclosing namespace.  */
9008
9009 static void
9010 add_partial_namespace (struct partial_die_info *pdi,
9011                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
9012                        int set_addrmap, struct dwarf2_cu *cu)
9013 {
9014   /* Add a symbol for the namespace.  */
9015
9016   add_partial_symbol (pdi, cu);
9017
9018   /* Now scan partial symbols in that namespace.  */
9019
9020   if (pdi->has_children)
9021     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9022 }
9023
9024 /* Read a partial die corresponding to a Fortran module.  */
9025
9026 static void
9027 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
9028                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
9029 {
9030   /* Add a symbol for the namespace.  */
9031
9032   add_partial_symbol (pdi, cu);
9033
9034   /* Now scan partial symbols in that module.  */
9035
9036   if (pdi->has_children)
9037     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
9038 }
9039
9040 /* Read a partial die corresponding to a subprogram or an inlined
9041    subprogram and create a partial symbol for that subprogram.
9042    When the CU language allows it, this routine also defines a partial
9043    symbol for each nested subprogram that this subprogram contains.
9044    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9045    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9046
9047    PDI may also be a lexical block, in which case we simply search
9048    recursively for subprograms defined inside that lexical block.
9049    Again, this is only performed when the CU language allows this
9050    type of definitions.  */
9051
9052 static void
9053 add_partial_subprogram (struct partial_die_info *pdi,
9054                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9055                         int set_addrmap, struct dwarf2_cu *cu)
9056 {
9057   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9058     {
9059       if (pdi->has_pc_info)
9060         {
9061           if (pdi->lowpc < *lowpc)
9062             *lowpc = pdi->lowpc;
9063           if (pdi->highpc > *highpc)
9064             *highpc = pdi->highpc;
9065           if (set_addrmap)
9066             {
9067               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9068               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9069               CORE_ADDR baseaddr;
9070               CORE_ADDR highpc;
9071               CORE_ADDR lowpc;
9072
9073               baseaddr = ANOFFSET (objfile->section_offsets,
9074                                    SECT_OFF_TEXT (objfile));
9075               lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
9076                                                    pdi->lowpc + baseaddr)
9077                        - baseaddr);
9078               highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
9079                                                     pdi->highpc + baseaddr)
9080                         - baseaddr);
9081               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9082                                  cu->per_cu->v.psymtab);
9083             }
9084         }
9085
9086       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9087         {
9088           if (!pdi->is_declaration)
9089             /* Ignore subprogram DIEs that do not have a name, they are
9090                illegal.  Do not emit a complaint at this point, we will
9091                do so when we convert this psymtab into a symtab.  */
9092             if (pdi->name)
9093               add_partial_symbol (pdi, cu);
9094         }
9095     }
9096
9097   if (! pdi->has_children)
9098     return;
9099
9100   if (cu->language == language_ada)
9101     {
9102       pdi = pdi->die_child;
9103       while (pdi != NULL)
9104         {
9105           pdi->fixup (cu);
9106           if (pdi->tag == DW_TAG_subprogram
9107               || pdi->tag == DW_TAG_inlined_subroutine
9108               || pdi->tag == DW_TAG_lexical_block)
9109             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9110           pdi = pdi->die_sibling;
9111         }
9112     }
9113 }
9114
9115 /* Read a partial die corresponding to an enumeration type.  */
9116
9117 static void
9118 add_partial_enumeration (struct partial_die_info *enum_pdi,
9119                          struct dwarf2_cu *cu)
9120 {
9121   struct partial_die_info *pdi;
9122
9123   if (enum_pdi->name != NULL)
9124     add_partial_symbol (enum_pdi, cu);
9125
9126   pdi = enum_pdi->die_child;
9127   while (pdi)
9128     {
9129       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9130         complaint (_("malformed enumerator DIE ignored"));
9131       else
9132         add_partial_symbol (pdi, cu);
9133       pdi = pdi->die_sibling;
9134     }
9135 }
9136
9137 /* Return the initial uleb128 in the die at INFO_PTR.  */
9138
9139 static unsigned int
9140 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9141 {
9142   unsigned int bytes_read;
9143
9144   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9145 }
9146
9147 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9148    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9149
9150    Return the corresponding abbrev, or NULL if the number is zero (indicating
9151    an empty DIE).  In either case *BYTES_READ will be set to the length of
9152    the initial number.  */
9153
9154 static struct abbrev_info *
9155 peek_die_abbrev (const die_reader_specs &reader,
9156                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9157 {
9158   dwarf2_cu *cu = reader.cu;
9159   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9160   unsigned int abbrev_number
9161     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9162
9163   if (abbrev_number == 0)
9164     return NULL;
9165
9166   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9167   if (!abbrev)
9168     {
9169       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9170                " at offset %s [in module %s]"),
9171              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9172              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9173     }
9174
9175   return abbrev;
9176 }
9177
9178 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9179    Returns a pointer to the end of a series of DIEs, terminated by an empty
9180    DIE.  Any children of the skipped DIEs will also be skipped.  */
9181
9182 static const gdb_byte *
9183 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9184 {
9185   while (1)
9186     {
9187       unsigned int bytes_read;
9188       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9189
9190       if (abbrev == NULL)
9191         return info_ptr + bytes_read;
9192       else
9193         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9194     }
9195 }
9196
9197 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9198    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9199    abbrev corresponding to that skipped uleb128 should be passed in
9200    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9201    children.  */
9202
9203 static const gdb_byte *
9204 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9205               struct abbrev_info *abbrev)
9206 {
9207   unsigned int bytes_read;
9208   struct attribute attr;
9209   bfd *abfd = reader->abfd;
9210   struct dwarf2_cu *cu = reader->cu;
9211   const gdb_byte *buffer = reader->buffer;
9212   const gdb_byte *buffer_end = reader->buffer_end;
9213   unsigned int form, i;
9214
9215   for (i = 0; i < abbrev->num_attrs; i++)
9216     {
9217       /* The only abbrev we care about is DW_AT_sibling.  */
9218       if (abbrev->attrs[i].name == DW_AT_sibling)
9219         {
9220           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9221           if (attr.form == DW_FORM_ref_addr)
9222             complaint (_("ignoring absolute DW_AT_sibling"));
9223           else
9224             {
9225               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9226               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9227
9228               if (sibling_ptr < info_ptr)
9229                 complaint (_("DW_AT_sibling points backwards"));
9230               else if (sibling_ptr > reader->buffer_end)
9231                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9232               else
9233                 return sibling_ptr;
9234             }
9235         }
9236
9237       /* If it isn't DW_AT_sibling, skip this attribute.  */
9238       form = abbrev->attrs[i].form;
9239     skip_attribute:
9240       switch (form)
9241         {
9242         case DW_FORM_ref_addr:
9243           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9244              and later it is offset sized.  */
9245           if (cu->header.version == 2)
9246             info_ptr += cu->header.addr_size;
9247           else
9248             info_ptr += cu->header.offset_size;
9249           break;
9250         case DW_FORM_GNU_ref_alt:
9251           info_ptr += cu->header.offset_size;
9252           break;
9253         case DW_FORM_addr:
9254           info_ptr += cu->header.addr_size;
9255           break;
9256         case DW_FORM_data1:
9257         case DW_FORM_ref1:
9258         case DW_FORM_flag:
9259           info_ptr += 1;
9260           break;
9261         case DW_FORM_flag_present:
9262         case DW_FORM_implicit_const:
9263           break;
9264         case DW_FORM_data2:
9265         case DW_FORM_ref2:
9266           info_ptr += 2;
9267           break;
9268         case DW_FORM_data4:
9269         case DW_FORM_ref4:
9270           info_ptr += 4;
9271           break;
9272         case DW_FORM_data8:
9273         case DW_FORM_ref8:
9274         case DW_FORM_ref_sig8:
9275           info_ptr += 8;
9276           break;
9277         case DW_FORM_data16:
9278           info_ptr += 16;
9279           break;
9280         case DW_FORM_string:
9281           read_direct_string (abfd, info_ptr, &bytes_read);
9282           info_ptr += bytes_read;
9283           break;
9284         case DW_FORM_sec_offset:
9285         case DW_FORM_strp:
9286         case DW_FORM_GNU_strp_alt:
9287           info_ptr += cu->header.offset_size;
9288           break;
9289         case DW_FORM_exprloc:
9290         case DW_FORM_block:
9291           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9292           info_ptr += bytes_read;
9293           break;
9294         case DW_FORM_block1:
9295           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9296           break;
9297         case DW_FORM_block2:
9298           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9299           break;
9300         case DW_FORM_block4:
9301           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9302           break;
9303         case DW_FORM_sdata:
9304         case DW_FORM_udata:
9305         case DW_FORM_ref_udata:
9306         case DW_FORM_GNU_addr_index:
9307         case DW_FORM_GNU_str_index:
9308           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9309           break;
9310         case DW_FORM_indirect:
9311           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9312           info_ptr += bytes_read;
9313           /* We need to continue parsing from here, so just go back to
9314              the top.  */
9315           goto skip_attribute;
9316
9317         default:
9318           error (_("Dwarf Error: Cannot handle %s "
9319                    "in DWARF reader [in module %s]"),
9320                  dwarf_form_name (form),
9321                  bfd_get_filename (abfd));
9322         }
9323     }
9324
9325   if (abbrev->has_children)
9326     return skip_children (reader, info_ptr);
9327   else
9328     return info_ptr;
9329 }
9330
9331 /* Locate ORIG_PDI's sibling.
9332    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9333
9334 static const gdb_byte *
9335 locate_pdi_sibling (const struct die_reader_specs *reader,
9336                     struct partial_die_info *orig_pdi,
9337                     const gdb_byte *info_ptr)
9338 {
9339   /* Do we know the sibling already?  */
9340
9341   if (orig_pdi->sibling)
9342     return orig_pdi->sibling;
9343
9344   /* Are there any children to deal with?  */
9345
9346   if (!orig_pdi->has_children)
9347     return info_ptr;
9348
9349   /* Skip the children the long way.  */
9350
9351   return skip_children (reader, info_ptr);
9352 }
9353
9354 /* Expand this partial symbol table into a full symbol table.  SELF is
9355    not NULL.  */
9356
9357 static void
9358 dwarf2_read_symtab (struct partial_symtab *self,
9359                     struct objfile *objfile)
9360 {
9361   struct dwarf2_per_objfile *dwarf2_per_objfile
9362     = get_dwarf2_per_objfile (objfile);
9363
9364   if (self->readin)
9365     {
9366       warning (_("bug: psymtab for %s is already read in."),
9367                self->filename);
9368     }
9369   else
9370     {
9371       if (info_verbose)
9372         {
9373           printf_filtered (_("Reading in symbols for %s..."),
9374                            self->filename);
9375           gdb_flush (gdb_stdout);
9376         }
9377
9378       /* If this psymtab is constructed from a debug-only objfile, the
9379          has_section_at_zero flag will not necessarily be correct.  We
9380          can get the correct value for this flag by looking at the data
9381          associated with the (presumably stripped) associated objfile.  */
9382       if (objfile->separate_debug_objfile_backlink)
9383         {
9384           struct dwarf2_per_objfile *dpo_backlink
9385             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9386
9387           dwarf2_per_objfile->has_section_at_zero
9388             = dpo_backlink->has_section_at_zero;
9389         }
9390
9391       dwarf2_per_objfile->reading_partial_symbols = 0;
9392
9393       psymtab_to_symtab_1 (self);
9394
9395       /* Finish up the debug error message.  */
9396       if (info_verbose)
9397         printf_filtered (_("done.\n"));
9398     }
9399
9400   process_cu_includes (dwarf2_per_objfile);
9401 }
9402 \f
9403 /* Reading in full CUs.  */
9404
9405 /* Add PER_CU to the queue.  */
9406
9407 static void
9408 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9409                  enum language pretend_language)
9410 {
9411   struct dwarf2_queue_item *item;
9412
9413   per_cu->queued = 1;
9414   item = XNEW (struct dwarf2_queue_item);
9415   item->per_cu = per_cu;
9416   item->pretend_language = pretend_language;
9417   item->next = NULL;
9418
9419   if (dwarf2_queue == NULL)
9420     dwarf2_queue = item;
9421   else
9422     dwarf2_queue_tail->next = item;
9423
9424   dwarf2_queue_tail = item;
9425 }
9426
9427 /* If PER_CU is not yet queued, add it to the queue.
9428    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9429    dependency.
9430    The result is non-zero if PER_CU was queued, otherwise the result is zero
9431    meaning either PER_CU is already queued or it is already loaded.
9432
9433    N.B. There is an invariant here that if a CU is queued then it is loaded.
9434    The caller is required to load PER_CU if we return non-zero.  */
9435
9436 static int
9437 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9438                        struct dwarf2_per_cu_data *per_cu,
9439                        enum language pretend_language)
9440 {
9441   /* We may arrive here during partial symbol reading, if we need full
9442      DIEs to process an unusual case (e.g. template arguments).  Do
9443      not queue PER_CU, just tell our caller to load its DIEs.  */
9444   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9445     {
9446       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9447         return 1;
9448       return 0;
9449     }
9450
9451   /* Mark the dependence relation so that we don't flush PER_CU
9452      too early.  */
9453   if (dependent_cu != NULL)
9454     dwarf2_add_dependence (dependent_cu, per_cu);
9455
9456   /* If it's already on the queue, we have nothing to do.  */
9457   if (per_cu->queued)
9458     return 0;
9459
9460   /* If the compilation unit is already loaded, just mark it as
9461      used.  */
9462   if (per_cu->cu != NULL)
9463     {
9464       per_cu->cu->last_used = 0;
9465       return 0;
9466     }
9467
9468   /* Add it to the queue.  */
9469   queue_comp_unit (per_cu, pretend_language);
9470
9471   return 1;
9472 }
9473
9474 /* Process the queue.  */
9475
9476 static void
9477 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9478 {
9479   struct dwarf2_queue_item *item, *next_item;
9480
9481   if (dwarf_read_debug)
9482     {
9483       fprintf_unfiltered (gdb_stdlog,
9484                           "Expanding one or more symtabs of objfile %s ...\n",
9485                           objfile_name (dwarf2_per_objfile->objfile));
9486     }
9487
9488   /* The queue starts out with one item, but following a DIE reference
9489      may load a new CU, adding it to the end of the queue.  */
9490   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9491     {
9492       if ((dwarf2_per_objfile->using_index
9493            ? !item->per_cu->v.quick->compunit_symtab
9494            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9495           /* Skip dummy CUs.  */
9496           && item->per_cu->cu != NULL)
9497         {
9498           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9499           unsigned int debug_print_threshold;
9500           char buf[100];
9501
9502           if (per_cu->is_debug_types)
9503             {
9504               struct signatured_type *sig_type =
9505                 (struct signatured_type *) per_cu;
9506
9507               sprintf (buf, "TU %s at offset %s",
9508                        hex_string (sig_type->signature),
9509                        sect_offset_str (per_cu->sect_off));
9510               /* There can be 100s of TUs.
9511                  Only print them in verbose mode.  */
9512               debug_print_threshold = 2;
9513             }
9514           else
9515             {
9516               sprintf (buf, "CU at offset %s",
9517                        sect_offset_str (per_cu->sect_off));
9518               debug_print_threshold = 1;
9519             }
9520
9521           if (dwarf_read_debug >= debug_print_threshold)
9522             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9523
9524           if (per_cu->is_debug_types)
9525             process_full_type_unit (per_cu, item->pretend_language);
9526           else
9527             process_full_comp_unit (per_cu, item->pretend_language);
9528
9529           if (dwarf_read_debug >= debug_print_threshold)
9530             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9531         }
9532
9533       item->per_cu->queued = 0;
9534       next_item = item->next;
9535       xfree (item);
9536     }
9537
9538   dwarf2_queue_tail = NULL;
9539
9540   if (dwarf_read_debug)
9541     {
9542       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9543                           objfile_name (dwarf2_per_objfile->objfile));
9544     }
9545 }
9546
9547 /* Read in full symbols for PST, and anything it depends on.  */
9548
9549 static void
9550 psymtab_to_symtab_1 (struct partial_symtab *pst)
9551 {
9552   struct dwarf2_per_cu_data *per_cu;
9553   int i;
9554
9555   if (pst->readin)
9556     return;
9557
9558   for (i = 0; i < pst->number_of_dependencies; i++)
9559     if (!pst->dependencies[i]->readin
9560         && pst->dependencies[i]->user == NULL)
9561       {
9562         /* Inform about additional files that need to be read in.  */
9563         if (info_verbose)
9564           {
9565             /* FIXME: i18n: Need to make this a single string.  */
9566             fputs_filtered (" ", gdb_stdout);
9567             wrap_here ("");
9568             fputs_filtered ("and ", gdb_stdout);
9569             wrap_here ("");
9570             printf_filtered ("%s...", pst->dependencies[i]->filename);
9571             wrap_here ("");     /* Flush output.  */
9572             gdb_flush (gdb_stdout);
9573           }
9574         psymtab_to_symtab_1 (pst->dependencies[i]);
9575       }
9576
9577   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9578
9579   if (per_cu == NULL)
9580     {
9581       /* It's an include file, no symbols to read for it.
9582          Everything is in the parent symtab.  */
9583       pst->readin = 1;
9584       return;
9585     }
9586
9587   dw2_do_instantiate_symtab (per_cu, false);
9588 }
9589
9590 /* Trivial hash function for die_info: the hash value of a DIE
9591    is its offset in .debug_info for this objfile.  */
9592
9593 static hashval_t
9594 die_hash (const void *item)
9595 {
9596   const struct die_info *die = (const struct die_info *) item;
9597
9598   return to_underlying (die->sect_off);
9599 }
9600
9601 /* Trivial comparison function for die_info structures: two DIEs
9602    are equal if they have the same offset.  */
9603
9604 static int
9605 die_eq (const void *item_lhs, const void *item_rhs)
9606 {
9607   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9608   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9609
9610   return die_lhs->sect_off == die_rhs->sect_off;
9611 }
9612
9613 /* die_reader_func for load_full_comp_unit.
9614    This is identical to read_signatured_type_reader,
9615    but is kept separate for now.  */
9616
9617 static void
9618 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9619                             const gdb_byte *info_ptr,
9620                             struct die_info *comp_unit_die,
9621                             int has_children,
9622                             void *data)
9623 {
9624   struct dwarf2_cu *cu = reader->cu;
9625   enum language *language_ptr = (enum language *) data;
9626
9627   gdb_assert (cu->die_hash == NULL);
9628   cu->die_hash =
9629     htab_create_alloc_ex (cu->header.length / 12,
9630                           die_hash,
9631                           die_eq,
9632                           NULL,
9633                           &cu->comp_unit_obstack,
9634                           hashtab_obstack_allocate,
9635                           dummy_obstack_deallocate);
9636
9637   if (has_children)
9638     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9639                                                   &info_ptr, comp_unit_die);
9640   cu->dies = comp_unit_die;
9641   /* comp_unit_die is not stored in die_hash, no need.  */
9642
9643   /* We try not to read any attributes in this function, because not
9644      all CUs needed for references have been loaded yet, and symbol
9645      table processing isn't initialized.  But we have to set the CU language,
9646      or we won't be able to build types correctly.
9647      Similarly, if we do not read the producer, we can not apply
9648      producer-specific interpretation.  */
9649   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9650 }
9651
9652 /* Load the DIEs associated with PER_CU into memory.  */
9653
9654 static void
9655 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9656                      bool skip_partial,
9657                      enum language pretend_language)
9658 {
9659   gdb_assert (! this_cu->is_debug_types);
9660
9661   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9662                            load_full_comp_unit_reader, &pretend_language);
9663 }
9664
9665 /* Add a DIE to the delayed physname list.  */
9666
9667 static void
9668 add_to_method_list (struct type *type, int fnfield_index, int index,
9669                     const char *name, struct die_info *die,
9670                     struct dwarf2_cu *cu)
9671 {
9672   struct delayed_method_info mi;
9673   mi.type = type;
9674   mi.fnfield_index = fnfield_index;
9675   mi.index = index;
9676   mi.name = name;
9677   mi.die = die;
9678   cu->method_list.push_back (mi);
9679 }
9680
9681 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9682    "const" / "volatile".  If so, decrements LEN by the length of the
9683    modifier and return true.  Otherwise return false.  */
9684
9685 template<size_t N>
9686 static bool
9687 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9688 {
9689   size_t mod_len = sizeof (mod) - 1;
9690   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9691     {
9692       len -= mod_len;
9693       return true;
9694     }
9695   return false;
9696 }
9697
9698 /* Compute the physnames of any methods on the CU's method list.
9699
9700    The computation of method physnames is delayed in order to avoid the
9701    (bad) condition that one of the method's formal parameters is of an as yet
9702    incomplete type.  */
9703
9704 static void
9705 compute_delayed_physnames (struct dwarf2_cu *cu)
9706 {
9707   /* Only C++ delays computing physnames.  */
9708   if (cu->method_list.empty ())
9709     return;
9710   gdb_assert (cu->language == language_cplus);
9711
9712   for (const delayed_method_info &mi : cu->method_list)
9713     {
9714       const char *physname;
9715       struct fn_fieldlist *fn_flp
9716         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9717       physname = dwarf2_physname (mi.name, mi.die, cu);
9718       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9719         = physname ? physname : "";
9720
9721       /* Since there's no tag to indicate whether a method is a
9722          const/volatile overload, extract that information out of the
9723          demangled name.  */
9724       if (physname != NULL)
9725         {
9726           size_t len = strlen (physname);
9727
9728           while (1)
9729             {
9730               if (physname[len] == ')') /* shortcut */
9731                 break;
9732               else if (check_modifier (physname, len, " const"))
9733                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9734               else if (check_modifier (physname, len, " volatile"))
9735                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9736               else
9737                 break;
9738             }
9739         }
9740     }
9741
9742   /* The list is no longer needed.  */
9743   cu->method_list.clear ();
9744 }
9745
9746 /* A wrapper for add_symbol_to_list to ensure that SYMBOL's language is
9747    the same as all other symbols in LISTHEAD.  If a new symbol is added
9748    with a different language, this function asserts.  */
9749
9750 static inline void
9751 dw2_add_symbol_to_list (struct symbol *symbol, struct pending **listhead)
9752 {
9753   /* Only assert if LISTHEAD already contains symbols of a different
9754      language (dict_create_hashed/insert_symbol_hashed requires that all
9755      symbols in this list are of the same language).  */
9756   gdb_assert ((*listhead) == NULL
9757               || (SYMBOL_LANGUAGE ((*listhead)->symbol[0])
9758                   == SYMBOL_LANGUAGE (symbol)));
9759
9760   add_symbol_to_list (symbol, listhead);
9761 }
9762
9763 /* Go objects should be embedded in a DW_TAG_module DIE,
9764    and it's not clear if/how imported objects will appear.
9765    To keep Go support simple until that's worked out,
9766    go back through what we've read and create something usable.
9767    We could do this while processing each DIE, and feels kinda cleaner,
9768    but that way is more invasive.
9769    This is to, for example, allow the user to type "p var" or "b main"
9770    without having to specify the package name, and allow lookups
9771    of module.object to work in contexts that use the expression
9772    parser.  */
9773
9774 static void
9775 fixup_go_packaging (struct dwarf2_cu *cu)
9776 {
9777   char *package_name = NULL;
9778   struct pending *list;
9779   int i;
9780
9781   for (list = *cu->builder->get_global_symbols ();
9782        list != NULL;
9783        list = list->next)
9784     {
9785       for (i = 0; i < list->nsyms; ++i)
9786         {
9787           struct symbol *sym = list->symbol[i];
9788
9789           if (SYMBOL_LANGUAGE (sym) == language_go
9790               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9791             {
9792               char *this_package_name = go_symbol_package_name (sym);
9793
9794               if (this_package_name == NULL)
9795                 continue;
9796               if (package_name == NULL)
9797                 package_name = this_package_name;
9798               else
9799                 {
9800                   struct objfile *objfile
9801                     = cu->per_cu->dwarf2_per_objfile->objfile;
9802                   if (strcmp (package_name, this_package_name) != 0)
9803                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9804                                (symbol_symtab (sym) != NULL
9805                                 ? symtab_to_filename_for_display
9806                                     (symbol_symtab (sym))
9807                                 : objfile_name (objfile)),
9808                                this_package_name, package_name);
9809                   xfree (this_package_name);
9810                 }
9811             }
9812         }
9813     }
9814
9815   if (package_name != NULL)
9816     {
9817       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9818       const char *saved_package_name
9819         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9820                                         package_name,
9821                                         strlen (package_name));
9822       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9823                                      saved_package_name);
9824       struct symbol *sym;
9825
9826       sym = allocate_symbol (objfile);
9827       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9828       SYMBOL_SET_NAMES (sym, saved_package_name,
9829                         strlen (saved_package_name), 0, objfile);
9830       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9831          e.g., "main" finds the "main" module and not C's main().  */
9832       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9833       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9834       SYMBOL_TYPE (sym) = type;
9835
9836       dw2_add_symbol_to_list (sym, cu->builder->get_global_symbols ());
9837
9838       xfree (package_name);
9839     }
9840 }
9841
9842 /* Allocate a fully-qualified name consisting of the two parts on the
9843    obstack.  */
9844
9845 static const char *
9846 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9847 {
9848   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9849 }
9850
9851 /* A helper that allocates a struct discriminant_info to attach to a
9852    union type.  */
9853
9854 static struct discriminant_info *
9855 alloc_discriminant_info (struct type *type, int discriminant_index,
9856                          int default_index)
9857 {
9858   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9859   gdb_assert (discriminant_index == -1
9860               || (discriminant_index >= 0
9861                   && discriminant_index < TYPE_NFIELDS (type)));
9862   gdb_assert (default_index == -1
9863               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9864
9865   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9866
9867   struct discriminant_info *disc
9868     = ((struct discriminant_info *)
9869        TYPE_ZALLOC (type,
9870                     offsetof (struct discriminant_info, discriminants)
9871                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9872   disc->default_index = default_index;
9873   disc->discriminant_index = discriminant_index;
9874
9875   struct dynamic_prop prop;
9876   prop.kind = PROP_UNDEFINED;
9877   prop.data.baton = disc;
9878
9879   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9880
9881   return disc;
9882 }
9883
9884 /* Some versions of rustc emitted enums in an unusual way.
9885
9886    Ordinary enums were emitted as unions.  The first element of each
9887    structure in the union was named "RUST$ENUM$DISR".  This element
9888    held the discriminant.
9889
9890    These versions of Rust also implemented the "non-zero"
9891    optimization.  When the enum had two values, and one is empty and
9892    the other holds a pointer that cannot be zero, the pointer is used
9893    as the discriminant, with a zero value meaning the empty variant.
9894    Here, the union's first member is of the form
9895    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9896    where the fieldnos are the indices of the fields that should be
9897    traversed in order to find the field (which may be several fields deep)
9898    and the variantname is the name of the variant of the case when the
9899    field is zero.
9900
9901    This function recognizes whether TYPE is of one of these forms,
9902    and, if so, smashes it to be a variant type.  */
9903
9904 static void
9905 quirk_rust_enum (struct type *type, struct objfile *objfile)
9906 {
9907   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9908
9909   /* We don't need to deal with empty enums.  */
9910   if (TYPE_NFIELDS (type) == 0)
9911     return;
9912
9913 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9914   if (TYPE_NFIELDS (type) == 1
9915       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9916     {
9917       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9918
9919       /* Decode the field name to find the offset of the
9920          discriminant.  */
9921       ULONGEST bit_offset = 0;
9922       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9923       while (name[0] >= '0' && name[0] <= '9')
9924         {
9925           char *tail;
9926           unsigned long index = strtoul (name, &tail, 10);
9927           name = tail;
9928           if (*name != '$'
9929               || index >= TYPE_NFIELDS (field_type)
9930               || (TYPE_FIELD_LOC_KIND (field_type, index)
9931                   != FIELD_LOC_KIND_BITPOS))
9932             {
9933               complaint (_("Could not parse Rust enum encoding string \"%s\""
9934                            "[in module %s]"),
9935                          TYPE_FIELD_NAME (type, 0),
9936                          objfile_name (objfile));
9937               return;
9938             }
9939           ++name;
9940
9941           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9942           field_type = TYPE_FIELD_TYPE (field_type, index);
9943         }
9944
9945       /* Make a union to hold the variants.  */
9946       struct type *union_type = alloc_type (objfile);
9947       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9948       TYPE_NFIELDS (union_type) = 3;
9949       TYPE_FIELDS (union_type)
9950         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9951       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9952       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9953
9954       /* Put the discriminant must at index 0.  */
9955       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9956       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9957       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9958       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9959
9960       /* The order of fields doesn't really matter, so put the real
9961          field at index 1 and the data-less field at index 2.  */
9962       struct discriminant_info *disc
9963         = alloc_discriminant_info (union_type, 0, 1);
9964       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9965       TYPE_FIELD_NAME (union_type, 1)
9966         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9967       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9968         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9969                               TYPE_FIELD_NAME (union_type, 1));
9970
9971       const char *dataless_name
9972         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9973                               name);
9974       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9975                                               dataless_name);
9976       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9977       /* NAME points into the original discriminant name, which
9978          already has the correct lifetime.  */
9979       TYPE_FIELD_NAME (union_type, 2) = name;
9980       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9981       disc->discriminants[2] = 0;
9982
9983       /* Smash this type to be a structure type.  We have to do this
9984          because the type has already been recorded.  */
9985       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9986       TYPE_NFIELDS (type) = 1;
9987       TYPE_FIELDS (type)
9988         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9989
9990       /* Install the variant part.  */
9991       TYPE_FIELD_TYPE (type, 0) = union_type;
9992       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9993       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9994     }
9995   else if (TYPE_NFIELDS (type) == 1)
9996     {
9997       /* We assume that a union with a single field is a univariant
9998          enum.  */
9999       /* Smash this type to be a structure type.  We have to do this
10000          because the type has already been recorded.  */
10001       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10002
10003       /* Make a union to hold the variants.  */
10004       struct type *union_type = alloc_type (objfile);
10005       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10006       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
10007       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10008       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10009       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
10010
10011       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
10012       const char *variant_name
10013         = rust_last_path_segment (TYPE_NAME (field_type));
10014       TYPE_FIELD_NAME (union_type, 0) = variant_name;
10015       TYPE_NAME (field_type)
10016         = rust_fully_qualify (&objfile->objfile_obstack,
10017                               TYPE_NAME (type), variant_name);
10018
10019       /* Install the union in the outer struct type.  */
10020       TYPE_NFIELDS (type) = 1;
10021       TYPE_FIELDS (type)
10022         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
10023       TYPE_FIELD_TYPE (type, 0) = union_type;
10024       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10025       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10026
10027       alloc_discriminant_info (union_type, -1, 0);
10028     }
10029   else
10030     {
10031       struct type *disr_type = nullptr;
10032       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
10033         {
10034           disr_type = TYPE_FIELD_TYPE (type, i);
10035
10036           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
10037             {
10038               /* All fields of a true enum will be structs.  */
10039               return;
10040             }
10041           else if (TYPE_NFIELDS (disr_type) == 0)
10042             {
10043               /* Could be data-less variant, so keep going.  */
10044               disr_type = nullptr;
10045             }
10046           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
10047                            "RUST$ENUM$DISR") != 0)
10048             {
10049               /* Not a Rust enum.  */
10050               return;
10051             }
10052           else
10053             {
10054               /* Found one.  */
10055               break;
10056             }
10057         }
10058
10059       /* If we got here without a discriminant, then it's probably
10060          just a union.  */
10061       if (disr_type == nullptr)
10062         return;
10063
10064       /* Smash this type to be a structure type.  We have to do this
10065          because the type has already been recorded.  */
10066       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10067
10068       /* Make a union to hold the variants.  */
10069       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10070       struct type *union_type = alloc_type (objfile);
10071       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10072       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10073       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10074       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10075       TYPE_FIELDS (union_type)
10076         = (struct field *) TYPE_ZALLOC (union_type,
10077                                         (TYPE_NFIELDS (union_type)
10078                                          * sizeof (struct field)));
10079
10080       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10081               TYPE_NFIELDS (type) * sizeof (struct field));
10082
10083       /* Install the discriminant at index 0 in the union.  */
10084       TYPE_FIELD (union_type, 0) = *disr_field;
10085       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10086       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10087
10088       /* Install the union in the outer struct type.  */
10089       TYPE_FIELD_TYPE (type, 0) = union_type;
10090       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10091       TYPE_NFIELDS (type) = 1;
10092
10093       /* Set the size and offset of the union type.  */
10094       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10095
10096       /* We need a way to find the correct discriminant given a
10097          variant name.  For convenience we build a map here.  */
10098       struct type *enum_type = FIELD_TYPE (*disr_field);
10099       std::unordered_map<std::string, ULONGEST> discriminant_map;
10100       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10101         {
10102           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10103             {
10104               const char *name
10105                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10106               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10107             }
10108         }
10109
10110       int n_fields = TYPE_NFIELDS (union_type);
10111       struct discriminant_info *disc
10112         = alloc_discriminant_info (union_type, 0, -1);
10113       /* Skip the discriminant here.  */
10114       for (int i = 1; i < n_fields; ++i)
10115         {
10116           /* Find the final word in the name of this variant's type.
10117              That name can be used to look up the correct
10118              discriminant.  */
10119           const char *variant_name
10120             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10121                                                                   i)));
10122
10123           auto iter = discriminant_map.find (variant_name);
10124           if (iter != discriminant_map.end ())
10125             disc->discriminants[i] = iter->second;
10126
10127           /* Remove the discriminant field, if it exists.  */
10128           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10129           if (TYPE_NFIELDS (sub_type) > 0)
10130             {
10131               --TYPE_NFIELDS (sub_type);
10132               ++TYPE_FIELDS (sub_type);
10133             }
10134           TYPE_FIELD_NAME (union_type, i) = variant_name;
10135           TYPE_NAME (sub_type)
10136             = rust_fully_qualify (&objfile->objfile_obstack,
10137                                   TYPE_NAME (type), variant_name);
10138         }
10139     }
10140 }
10141
10142 /* Rewrite some Rust unions to be structures with variants parts.  */
10143
10144 static void
10145 rust_union_quirks (struct dwarf2_cu *cu)
10146 {
10147   gdb_assert (cu->language == language_rust);
10148   for (type *type_ : cu->rust_unions)
10149     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10150   /* We don't need this any more.  */
10151   cu->rust_unions.clear ();
10152 }
10153
10154 /* Return the symtab for PER_CU.  This works properly regardless of
10155    whether we're using the index or psymtabs.  */
10156
10157 static struct compunit_symtab *
10158 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10159 {
10160   return (per_cu->dwarf2_per_objfile->using_index
10161           ? per_cu->v.quick->compunit_symtab
10162           : per_cu->v.psymtab->compunit_symtab);
10163 }
10164
10165 /* A helper function for computing the list of all symbol tables
10166    included by PER_CU.  */
10167
10168 static void
10169 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10170                                 htab_t all_children, htab_t all_type_symtabs,
10171                                 struct dwarf2_per_cu_data *per_cu,
10172                                 struct compunit_symtab *immediate_parent)
10173 {
10174   void **slot;
10175   int ix;
10176   struct compunit_symtab *cust;
10177   struct dwarf2_per_cu_data *iter;
10178
10179   slot = htab_find_slot (all_children, per_cu, INSERT);
10180   if (*slot != NULL)
10181     {
10182       /* This inclusion and its children have been processed.  */
10183       return;
10184     }
10185
10186   *slot = per_cu;
10187   /* Only add a CU if it has a symbol table.  */
10188   cust = get_compunit_symtab (per_cu);
10189   if (cust != NULL)
10190     {
10191       /* If this is a type unit only add its symbol table if we haven't
10192          seen it yet (type unit per_cu's can share symtabs).  */
10193       if (per_cu->is_debug_types)
10194         {
10195           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10196           if (*slot == NULL)
10197             {
10198               *slot = cust;
10199               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10200               if (cust->user == NULL)
10201                 cust->user = immediate_parent;
10202             }
10203         }
10204       else
10205         {
10206           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10207           if (cust->user == NULL)
10208             cust->user = immediate_parent;
10209         }
10210     }
10211
10212   for (ix = 0;
10213        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10214        ++ix)
10215     {
10216       recursively_compute_inclusions (result, all_children,
10217                                       all_type_symtabs, iter, cust);
10218     }
10219 }
10220
10221 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10222    PER_CU.  */
10223
10224 static void
10225 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10226 {
10227   gdb_assert (! per_cu->is_debug_types);
10228
10229   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10230     {
10231       int ix, len;
10232       struct dwarf2_per_cu_data *per_cu_iter;
10233       struct compunit_symtab *compunit_symtab_iter;
10234       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10235       htab_t all_children, all_type_symtabs;
10236       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10237
10238       /* If we don't have a symtab, we can just skip this case.  */
10239       if (cust == NULL)
10240         return;
10241
10242       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10243                                         NULL, xcalloc, xfree);
10244       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10245                                             NULL, xcalloc, xfree);
10246
10247       for (ix = 0;
10248            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10249                         ix, per_cu_iter);
10250            ++ix)
10251         {
10252           recursively_compute_inclusions (&result_symtabs, all_children,
10253                                           all_type_symtabs, per_cu_iter,
10254                                           cust);
10255         }
10256
10257       /* Now we have a transitive closure of all the included symtabs.  */
10258       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10259       cust->includes
10260         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10261                      struct compunit_symtab *, len + 1);
10262       for (ix = 0;
10263            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10264                         compunit_symtab_iter);
10265            ++ix)
10266         cust->includes[ix] = compunit_symtab_iter;
10267       cust->includes[len] = NULL;
10268
10269       VEC_free (compunit_symtab_ptr, result_symtabs);
10270       htab_delete (all_children);
10271       htab_delete (all_type_symtabs);
10272     }
10273 }
10274
10275 /* Compute the 'includes' field for the symtabs of all the CUs we just
10276    read.  */
10277
10278 static void
10279 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10280 {
10281   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10282     {
10283       if (! iter->is_debug_types)
10284         compute_compunit_symtab_includes (iter);
10285     }
10286
10287   dwarf2_per_objfile->just_read_cus.clear ();
10288 }
10289
10290 /* Generate full symbol information for PER_CU, whose DIEs have
10291    already been loaded into memory.  */
10292
10293 static void
10294 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10295                         enum language pretend_language)
10296 {
10297   struct dwarf2_cu *cu = per_cu->cu;
10298   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10299   struct objfile *objfile = dwarf2_per_objfile->objfile;
10300   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10301   CORE_ADDR lowpc, highpc;
10302   struct compunit_symtab *cust;
10303   CORE_ADDR baseaddr;
10304   struct block *static_block;
10305   CORE_ADDR addr;
10306
10307   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10308
10309   /* Clear the list here in case something was left over.  */
10310   cu->method_list.clear ();
10311
10312   cu->language = pretend_language;
10313   cu->language_defn = language_def (cu->language);
10314
10315   /* Do line number decoding in read_file_scope () */
10316   process_die (cu->dies, cu);
10317
10318   /* For now fudge the Go package.  */
10319   if (cu->language == language_go)
10320     fixup_go_packaging (cu);
10321
10322   /* Now that we have processed all the DIEs in the CU, all the types 
10323      should be complete, and it should now be safe to compute all of the
10324      physnames.  */
10325   compute_delayed_physnames (cu);
10326
10327   if (cu->language == language_rust)
10328     rust_union_quirks (cu);
10329
10330   /* Some compilers don't define a DW_AT_high_pc attribute for the
10331      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10332      it, by scanning the DIE's below the compilation unit.  */
10333   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10334
10335   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10336   static_block = cu->builder->end_symtab_get_static_block (addr, 0, 1);
10337
10338   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10339      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10340      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10341      addrmap to help ensure it has an accurate map of pc values belonging to
10342      this comp unit.  */
10343   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10344
10345   cust = cu->builder->end_symtab_from_static_block (static_block,
10346                                                     SECT_OFF_TEXT (objfile),
10347                                                     0);
10348
10349   if (cust != NULL)
10350     {
10351       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10352
10353       /* Set symtab language to language from DW_AT_language.  If the
10354          compilation is from a C file generated by language preprocessors, do
10355          not set the language if it was already deduced by start_subfile.  */
10356       if (!(cu->language == language_c
10357             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10358         COMPUNIT_FILETABS (cust)->language = cu->language;
10359
10360       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10361          produce DW_AT_location with location lists but it can be possibly
10362          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10363          there were bugs in prologue debug info, fixed later in GCC-4.5
10364          by "unwind info for epilogues" patch (which is not directly related).
10365
10366          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10367          needed, it would be wrong due to missing DW_AT_producer there.
10368
10369          Still one can confuse GDB by using non-standard GCC compilation
10370          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10371          */ 
10372       if (cu->has_loclist && gcc_4_minor >= 5)
10373         cust->locations_valid = 1;
10374
10375       if (gcc_4_minor >= 5)
10376         cust->epilogue_unwind_valid = 1;
10377
10378       cust->call_site_htab = cu->call_site_htab;
10379     }
10380
10381   if (dwarf2_per_objfile->using_index)
10382     per_cu->v.quick->compunit_symtab = cust;
10383   else
10384     {
10385       struct partial_symtab *pst = per_cu->v.psymtab;
10386       pst->compunit_symtab = cust;
10387       pst->readin = 1;
10388     }
10389
10390   /* Push it for inclusion processing later.  */
10391   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10392
10393   /* Not needed any more.  */
10394   cu->builder.reset ();
10395 }
10396
10397 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10398    already been loaded into memory.  */
10399
10400 static void
10401 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10402                         enum language pretend_language)
10403 {
10404   struct dwarf2_cu *cu = per_cu->cu;
10405   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10406   struct objfile *objfile = dwarf2_per_objfile->objfile;
10407   struct compunit_symtab *cust;
10408   struct signatured_type *sig_type;
10409
10410   gdb_assert (per_cu->is_debug_types);
10411   sig_type = (struct signatured_type *) per_cu;
10412
10413   /* Clear the list here in case something was left over.  */
10414   cu->method_list.clear ();
10415
10416   cu->language = pretend_language;
10417   cu->language_defn = language_def (cu->language);
10418
10419   /* The symbol tables are set up in read_type_unit_scope.  */
10420   process_die (cu->dies, cu);
10421
10422   /* For now fudge the Go package.  */
10423   if (cu->language == language_go)
10424     fixup_go_packaging (cu);
10425
10426   /* Now that we have processed all the DIEs in the CU, all the types 
10427      should be complete, and it should now be safe to compute all of the
10428      physnames.  */
10429   compute_delayed_physnames (cu);
10430
10431   if (cu->language == language_rust)
10432     rust_union_quirks (cu);
10433
10434   /* TUs share symbol tables.
10435      If this is the first TU to use this symtab, complete the construction
10436      of it with end_expandable_symtab.  Otherwise, complete the addition of
10437      this TU's symbols to the existing symtab.  */
10438   if (sig_type->type_unit_group->compunit_symtab == NULL)
10439     {
10440       cust = cu->builder->end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10441       sig_type->type_unit_group->compunit_symtab = cust;
10442
10443       if (cust != NULL)
10444         {
10445           /* Set symtab language to language from DW_AT_language.  If the
10446              compilation is from a C file generated by language preprocessors,
10447              do not set the language if it was already deduced by
10448              start_subfile.  */
10449           if (!(cu->language == language_c
10450                 && COMPUNIT_FILETABS (cust)->language != language_c))
10451             COMPUNIT_FILETABS (cust)->language = cu->language;
10452         }
10453     }
10454   else
10455     {
10456       cu->builder->augment_type_symtab ();
10457       cust = sig_type->type_unit_group->compunit_symtab;
10458     }
10459
10460   if (dwarf2_per_objfile->using_index)
10461     per_cu->v.quick->compunit_symtab = cust;
10462   else
10463     {
10464       struct partial_symtab *pst = per_cu->v.psymtab;
10465       pst->compunit_symtab = cust;
10466       pst->readin = 1;
10467     }
10468
10469   /* Not needed any more.  */
10470   cu->builder.reset ();
10471 }
10472
10473 /* Process an imported unit DIE.  */
10474
10475 static void
10476 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10477 {
10478   struct attribute *attr;
10479
10480   /* For now we don't handle imported units in type units.  */
10481   if (cu->per_cu->is_debug_types)
10482     {
10483       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10484                " supported in type units [in module %s]"),
10485              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10486     }
10487
10488   attr = dwarf2_attr (die, DW_AT_import, cu);
10489   if (attr != NULL)
10490     {
10491       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10492       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10493       dwarf2_per_cu_data *per_cu
10494         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10495                                             cu->per_cu->dwarf2_per_objfile);
10496
10497       /* If necessary, add it to the queue and load its DIEs.  */
10498       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10499         load_full_comp_unit (per_cu, false, cu->language);
10500
10501       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10502                      per_cu);
10503     }
10504 }
10505
10506 /* RAII object that represents a process_die scope: i.e.,
10507    starts/finishes processing a DIE.  */
10508 class process_die_scope
10509 {
10510 public:
10511   process_die_scope (die_info *die, dwarf2_cu *cu)
10512     : m_die (die), m_cu (cu)
10513   {
10514     /* We should only be processing DIEs not already in process.  */
10515     gdb_assert (!m_die->in_process);
10516     m_die->in_process = true;
10517   }
10518
10519   ~process_die_scope ()
10520   {
10521     m_die->in_process = false;
10522
10523     /* If we're done processing the DIE for the CU that owns the line
10524        header, we don't need the line header anymore.  */
10525     if (m_cu->line_header_die_owner == m_die)
10526       {
10527         delete m_cu->line_header;
10528         m_cu->line_header = NULL;
10529         m_cu->line_header_die_owner = NULL;
10530       }
10531   }
10532
10533 private:
10534   die_info *m_die;
10535   dwarf2_cu *m_cu;
10536 };
10537
10538 /* Process a die and its children.  */
10539
10540 static void
10541 process_die (struct die_info *die, struct dwarf2_cu *cu)
10542 {
10543   process_die_scope scope (die, cu);
10544
10545   switch (die->tag)
10546     {
10547     case DW_TAG_padding:
10548       break;
10549     case DW_TAG_compile_unit:
10550     case DW_TAG_partial_unit:
10551       read_file_scope (die, cu);
10552       break;
10553     case DW_TAG_type_unit:
10554       read_type_unit_scope (die, cu);
10555       break;
10556     case DW_TAG_subprogram:
10557     case DW_TAG_inlined_subroutine:
10558       read_func_scope (die, cu);
10559       break;
10560     case DW_TAG_lexical_block:
10561     case DW_TAG_try_block:
10562     case DW_TAG_catch_block:
10563       read_lexical_block_scope (die, cu);
10564       break;
10565     case DW_TAG_call_site:
10566     case DW_TAG_GNU_call_site:
10567       read_call_site_scope (die, cu);
10568       break;
10569     case DW_TAG_class_type:
10570     case DW_TAG_interface_type:
10571     case DW_TAG_structure_type:
10572     case DW_TAG_union_type:
10573       process_structure_scope (die, cu);
10574       break;
10575     case DW_TAG_enumeration_type:
10576       process_enumeration_scope (die, cu);
10577       break;
10578
10579     /* These dies have a type, but processing them does not create
10580        a symbol or recurse to process the children.  Therefore we can
10581        read them on-demand through read_type_die.  */
10582     case DW_TAG_subroutine_type:
10583     case DW_TAG_set_type:
10584     case DW_TAG_array_type:
10585     case DW_TAG_pointer_type:
10586     case DW_TAG_ptr_to_member_type:
10587     case DW_TAG_reference_type:
10588     case DW_TAG_rvalue_reference_type:
10589     case DW_TAG_string_type:
10590       break;
10591
10592     case DW_TAG_base_type:
10593     case DW_TAG_subrange_type:
10594     case DW_TAG_typedef:
10595       /* Add a typedef symbol for the type definition, if it has a
10596          DW_AT_name.  */
10597       new_symbol (die, read_type_die (die, cu), cu);
10598       break;
10599     case DW_TAG_common_block:
10600       read_common_block (die, cu);
10601       break;
10602     case DW_TAG_common_inclusion:
10603       break;
10604     case DW_TAG_namespace:
10605       cu->processing_has_namespace_info = 1;
10606       read_namespace (die, cu);
10607       break;
10608     case DW_TAG_module:
10609       cu->processing_has_namespace_info = 1;
10610       read_module (die, cu);
10611       break;
10612     case DW_TAG_imported_declaration:
10613       cu->processing_has_namespace_info = 1;
10614       if (read_namespace_alias (die, cu))
10615         break;
10616       /* The declaration is not a global namespace alias.  */
10617       /* Fall through.  */
10618     case DW_TAG_imported_module:
10619       cu->processing_has_namespace_info = 1;
10620       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10621                                  || cu->language != language_fortran))
10622         complaint (_("Tag '%s' has unexpected children"),
10623                    dwarf_tag_name (die->tag));
10624       read_import_statement (die, cu);
10625       break;
10626
10627     case DW_TAG_imported_unit:
10628       process_imported_unit_die (die, cu);
10629       break;
10630
10631     case DW_TAG_variable:
10632       read_variable (die, cu);
10633       break;
10634
10635     default:
10636       new_symbol (die, NULL, cu);
10637       break;
10638     }
10639 }
10640 \f
10641 /* DWARF name computation.  */
10642
10643 /* A helper function for dwarf2_compute_name which determines whether DIE
10644    needs to have the name of the scope prepended to the name listed in the
10645    die.  */
10646
10647 static int
10648 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10649 {
10650   struct attribute *attr;
10651
10652   switch (die->tag)
10653     {
10654     case DW_TAG_namespace:
10655     case DW_TAG_typedef:
10656     case DW_TAG_class_type:
10657     case DW_TAG_interface_type:
10658     case DW_TAG_structure_type:
10659     case DW_TAG_union_type:
10660     case DW_TAG_enumeration_type:
10661     case DW_TAG_enumerator:
10662     case DW_TAG_subprogram:
10663     case DW_TAG_inlined_subroutine:
10664     case DW_TAG_member:
10665     case DW_TAG_imported_declaration:
10666       return 1;
10667
10668     case DW_TAG_variable:
10669     case DW_TAG_constant:
10670       /* We only need to prefix "globally" visible variables.  These include
10671          any variable marked with DW_AT_external or any variable that
10672          lives in a namespace.  [Variables in anonymous namespaces
10673          require prefixing, but they are not DW_AT_external.]  */
10674
10675       if (dwarf2_attr (die, DW_AT_specification, cu))
10676         {
10677           struct dwarf2_cu *spec_cu = cu;
10678
10679           return die_needs_namespace (die_specification (die, &spec_cu),
10680                                       spec_cu);
10681         }
10682
10683       attr = dwarf2_attr (die, DW_AT_external, cu);
10684       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10685           && die->parent->tag != DW_TAG_module)
10686         return 0;
10687       /* A variable in a lexical block of some kind does not need a
10688          namespace, even though in C++ such variables may be external
10689          and have a mangled name.  */
10690       if (die->parent->tag ==  DW_TAG_lexical_block
10691           || die->parent->tag ==  DW_TAG_try_block
10692           || die->parent->tag ==  DW_TAG_catch_block
10693           || die->parent->tag == DW_TAG_subprogram)
10694         return 0;
10695       return 1;
10696
10697     default:
10698       return 0;
10699     }
10700 }
10701
10702 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10703    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10704    defined for the given DIE.  */
10705
10706 static struct attribute *
10707 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10708 {
10709   struct attribute *attr;
10710
10711   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10712   if (attr == NULL)
10713     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10714
10715   return attr;
10716 }
10717
10718 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10719    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10720    defined for the given DIE.  */
10721
10722 static const char *
10723 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10724 {
10725   const char *linkage_name;
10726
10727   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10728   if (linkage_name == NULL)
10729     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10730
10731   return linkage_name;
10732 }
10733
10734 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10735    compute the physname for the object, which include a method's:
10736    - formal parameters (C++),
10737    - receiver type (Go),
10738
10739    The term "physname" is a bit confusing.
10740    For C++, for example, it is the demangled name.
10741    For Go, for example, it's the mangled name.
10742
10743    For Ada, return the DIE's linkage name rather than the fully qualified
10744    name.  PHYSNAME is ignored..
10745
10746    The result is allocated on the objfile_obstack and canonicalized.  */
10747
10748 static const char *
10749 dwarf2_compute_name (const char *name,
10750                      struct die_info *die, struct dwarf2_cu *cu,
10751                      int physname)
10752 {
10753   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10754
10755   if (name == NULL)
10756     name = dwarf2_name (die, cu);
10757
10758   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10759      but otherwise compute it by typename_concat inside GDB.
10760      FIXME: Actually this is not really true, or at least not always true.
10761      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10762      Fortran names because there is no mangling standard.  So new_symbol
10763      will set the demangled name to the result of dwarf2_full_name, and it is
10764      the demangled name that GDB uses if it exists.  */
10765   if (cu->language == language_ada
10766       || (cu->language == language_fortran && physname))
10767     {
10768       /* For Ada unit, we prefer the linkage name over the name, as
10769          the former contains the exported name, which the user expects
10770          to be able to reference.  Ideally, we want the user to be able
10771          to reference this entity using either natural or linkage name,
10772          but we haven't started looking at this enhancement yet.  */
10773       const char *linkage_name = dw2_linkage_name (die, cu);
10774
10775       if (linkage_name != NULL)
10776         return linkage_name;
10777     }
10778
10779   /* These are the only languages we know how to qualify names in.  */
10780   if (name != NULL
10781       && (cu->language == language_cplus
10782           || cu->language == language_fortran || cu->language == language_d
10783           || cu->language == language_rust))
10784     {
10785       if (die_needs_namespace (die, cu))
10786         {
10787           const char *prefix;
10788           const char *canonical_name = NULL;
10789
10790           string_file buf;
10791
10792           prefix = determine_prefix (die, cu);
10793           if (*prefix != '\0')
10794             {
10795               char *prefixed_name = typename_concat (NULL, prefix, name,
10796                                                      physname, cu);
10797
10798               buf.puts (prefixed_name);
10799               xfree (prefixed_name);
10800             }
10801           else
10802             buf.puts (name);
10803
10804           /* Template parameters may be specified in the DIE's DW_AT_name, or
10805              as children with DW_TAG_template_type_param or
10806              DW_TAG_value_type_param.  If the latter, add them to the name
10807              here.  If the name already has template parameters, then
10808              skip this step; some versions of GCC emit both, and
10809              it is more efficient to use the pre-computed name.
10810
10811              Something to keep in mind about this process: it is very
10812              unlikely, or in some cases downright impossible, to produce
10813              something that will match the mangled name of a function.
10814              If the definition of the function has the same debug info,
10815              we should be able to match up with it anyway.  But fallbacks
10816              using the minimal symbol, for instance to find a method
10817              implemented in a stripped copy of libstdc++, will not work.
10818              If we do not have debug info for the definition, we will have to
10819              match them up some other way.
10820
10821              When we do name matching there is a related problem with function
10822              templates; two instantiated function templates are allowed to
10823              differ only by their return types, which we do not add here.  */
10824
10825           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10826             {
10827               struct attribute *attr;
10828               struct die_info *child;
10829               int first = 1;
10830
10831               die->building_fullname = 1;
10832
10833               for (child = die->child; child != NULL; child = child->sibling)
10834                 {
10835                   struct type *type;
10836                   LONGEST value;
10837                   const gdb_byte *bytes;
10838                   struct dwarf2_locexpr_baton *baton;
10839                   struct value *v;
10840
10841                   if (child->tag != DW_TAG_template_type_param
10842                       && child->tag != DW_TAG_template_value_param)
10843                     continue;
10844
10845                   if (first)
10846                     {
10847                       buf.puts ("<");
10848                       first = 0;
10849                     }
10850                   else
10851                     buf.puts (", ");
10852
10853                   attr = dwarf2_attr (child, DW_AT_type, cu);
10854                   if (attr == NULL)
10855                     {
10856                       complaint (_("template parameter missing DW_AT_type"));
10857                       buf.puts ("UNKNOWN_TYPE");
10858                       continue;
10859                     }
10860                   type = die_type (child, cu);
10861
10862                   if (child->tag == DW_TAG_template_type_param)
10863                     {
10864                       c_print_type (type, "", &buf, -1, 0, cu->language,
10865                                     &type_print_raw_options);
10866                       continue;
10867                     }
10868
10869                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10870                   if (attr == NULL)
10871                     {
10872                       complaint (_("template parameter missing "
10873                                    "DW_AT_const_value"));
10874                       buf.puts ("UNKNOWN_VALUE");
10875                       continue;
10876                     }
10877
10878                   dwarf2_const_value_attr (attr, type, name,
10879                                            &cu->comp_unit_obstack, cu,
10880                                            &value, &bytes, &baton);
10881
10882                   if (TYPE_NOSIGN (type))
10883                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10884                        changed, this can use value_print instead.  */
10885                     c_printchar (value, type, &buf);
10886                   else
10887                     {
10888                       struct value_print_options opts;
10889
10890                       if (baton != NULL)
10891                         v = dwarf2_evaluate_loc_desc (type, NULL,
10892                                                       baton->data,
10893                                                       baton->size,
10894                                                       baton->per_cu);
10895                       else if (bytes != NULL)
10896                         {
10897                           v = allocate_value (type);
10898                           memcpy (value_contents_writeable (v), bytes,
10899                                   TYPE_LENGTH (type));
10900                         }
10901                       else
10902                         v = value_from_longest (type, value);
10903
10904                       /* Specify decimal so that we do not depend on
10905                          the radix.  */
10906                       get_formatted_print_options (&opts, 'd');
10907                       opts.raw = 1;
10908                       value_print (v, &buf, &opts);
10909                       release_value (v);
10910                     }
10911                 }
10912
10913               die->building_fullname = 0;
10914
10915               if (!first)
10916                 {
10917                   /* Close the argument list, with a space if necessary
10918                      (nested templates).  */
10919                   if (!buf.empty () && buf.string ().back () == '>')
10920                     buf.puts (" >");
10921                   else
10922                     buf.puts (">");
10923                 }
10924             }
10925
10926           /* For C++ methods, append formal parameter type
10927              information, if PHYSNAME.  */
10928
10929           if (physname && die->tag == DW_TAG_subprogram
10930               && cu->language == language_cplus)
10931             {
10932               struct type *type = read_type_die (die, cu);
10933
10934               c_type_print_args (type, &buf, 1, cu->language,
10935                                  &type_print_raw_options);
10936
10937               if (cu->language == language_cplus)
10938                 {
10939                   /* Assume that an artificial first parameter is
10940                      "this", but do not crash if it is not.  RealView
10941                      marks unnamed (and thus unused) parameters as
10942                      artificial; there is no way to differentiate
10943                      the two cases.  */
10944                   if (TYPE_NFIELDS (type) > 0
10945                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10946                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10947                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10948                                                                         0))))
10949                     buf.puts (" const");
10950                 }
10951             }
10952
10953           const std::string &intermediate_name = buf.string ();
10954
10955           if (cu->language == language_cplus)
10956             canonical_name
10957               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10958                                           &objfile->per_bfd->storage_obstack);
10959
10960           /* If we only computed INTERMEDIATE_NAME, or if
10961              INTERMEDIATE_NAME is already canonical, then we need to
10962              copy it to the appropriate obstack.  */
10963           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10964             name = ((const char *)
10965                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10966                                    intermediate_name.c_str (),
10967                                    intermediate_name.length ()));
10968           else
10969             name = canonical_name;
10970         }
10971     }
10972
10973   return name;
10974 }
10975
10976 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10977    If scope qualifiers are appropriate they will be added.  The result
10978    will be allocated on the storage_obstack, or NULL if the DIE does
10979    not have a name.  NAME may either be from a previous call to
10980    dwarf2_name or NULL.
10981
10982    The output string will be canonicalized (if C++).  */
10983
10984 static const char *
10985 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10986 {
10987   return dwarf2_compute_name (name, die, cu, 0);
10988 }
10989
10990 /* Construct a physname for the given DIE in CU.  NAME may either be
10991    from a previous call to dwarf2_name or NULL.  The result will be
10992    allocated on the objfile_objstack or NULL if the DIE does not have a
10993    name.
10994
10995    The output string will be canonicalized (if C++).  */
10996
10997 static const char *
10998 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10999 {
11000   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11001   const char *retval, *mangled = NULL, *canon = NULL;
11002   int need_copy = 1;
11003
11004   /* In this case dwarf2_compute_name is just a shortcut not building anything
11005      on its own.  */
11006   if (!die_needs_namespace (die, cu))
11007     return dwarf2_compute_name (name, die, cu, 1);
11008
11009   mangled = dw2_linkage_name (die, cu);
11010
11011   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
11012      See https://github.com/rust-lang/rust/issues/32925.  */
11013   if (cu->language == language_rust && mangled != NULL
11014       && strchr (mangled, '{') != NULL)
11015     mangled = NULL;
11016
11017   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
11018      has computed.  */
11019   gdb::unique_xmalloc_ptr<char> demangled;
11020   if (mangled != NULL)
11021     {
11022
11023       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
11024         {
11025           /* Do nothing (do not demangle the symbol name).  */
11026         }
11027       else if (cu->language == language_go)
11028         {
11029           /* This is a lie, but we already lie to the caller new_symbol.
11030              new_symbol assumes we return the mangled name.
11031              This just undoes that lie until things are cleaned up.  */
11032         }
11033       else
11034         {
11035           /* Use DMGL_RET_DROP for C++ template functions to suppress
11036              their return type.  It is easier for GDB users to search
11037              for such functions as `name(params)' than `long name(params)'.
11038              In such case the minimal symbol names do not match the full
11039              symbol names but for template functions there is never a need
11040              to look up their definition from their declaration so
11041              the only disadvantage remains the minimal symbol variant
11042              `long name(params)' does not have the proper inferior type.  */
11043           demangled.reset (gdb_demangle (mangled,
11044                                          (DMGL_PARAMS | DMGL_ANSI
11045                                           | DMGL_RET_DROP)));
11046         }
11047       if (demangled)
11048         canon = demangled.get ();
11049       else
11050         {
11051           canon = mangled;
11052           need_copy = 0;
11053         }
11054     }
11055
11056   if (canon == NULL || check_physname)
11057     {
11058       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11059
11060       if (canon != NULL && strcmp (physname, canon) != 0)
11061         {
11062           /* It may not mean a bug in GDB.  The compiler could also
11063              compute DW_AT_linkage_name incorrectly.  But in such case
11064              GDB would need to be bug-to-bug compatible.  */
11065
11066           complaint (_("Computed physname <%s> does not match demangled <%s> "
11067                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11068                      physname, canon, mangled, sect_offset_str (die->sect_off),
11069                      objfile_name (objfile));
11070
11071           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11072              is available here - over computed PHYSNAME.  It is safer
11073              against both buggy GDB and buggy compilers.  */
11074
11075           retval = canon;
11076         }
11077       else
11078         {
11079           retval = physname;
11080           need_copy = 0;
11081         }
11082     }
11083   else
11084     retval = canon;
11085
11086   if (need_copy)
11087     retval = ((const char *)
11088               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11089                              retval, strlen (retval)));
11090
11091   return retval;
11092 }
11093
11094 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11095    a new symbol for it.
11096
11097    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11098
11099 static int
11100 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11101 {
11102   struct attribute *attr;
11103
11104   /* If the die does not have a name, this is not a namespace
11105      alias.  */
11106   attr = dwarf2_attr (die, DW_AT_name, cu);
11107   if (attr != NULL)
11108     {
11109       int num;
11110       struct die_info *d = die;
11111       struct dwarf2_cu *imported_cu = cu;
11112
11113       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11114          keep inspecting DIEs until we hit the underlying import.  */
11115 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11116       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11117         {
11118           attr = dwarf2_attr (d, DW_AT_import, cu);
11119           if (attr == NULL)
11120             break;
11121
11122           d = follow_die_ref (d, attr, &imported_cu);
11123           if (d->tag != DW_TAG_imported_declaration)
11124             break;
11125         }
11126
11127       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11128         {
11129           complaint (_("DIE at %s has too many recursively imported "
11130                        "declarations"), sect_offset_str (d->sect_off));
11131           return 0;
11132         }
11133
11134       if (attr != NULL)
11135         {
11136           struct type *type;
11137           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11138
11139           type = get_die_type_at_offset (sect_off, cu->per_cu);
11140           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11141             {
11142               /* This declaration is a global namespace alias.  Add
11143                  a symbol for it whose type is the aliased namespace.  */
11144               new_symbol (die, type, cu);
11145               return 1;
11146             }
11147         }
11148     }
11149
11150   return 0;
11151 }
11152
11153 /* Return the using directives repository (global or local?) to use in the
11154    current context for CU.
11155
11156    For Ada, imported declarations can materialize renamings, which *may* be
11157    global.  However it is impossible (for now?) in DWARF to distinguish
11158    "external" imported declarations and "static" ones.  As all imported
11159    declarations seem to be static in all other languages, make them all CU-wide
11160    global only in Ada.  */
11161
11162 static struct using_direct **
11163 using_directives (struct dwarf2_cu *cu)
11164 {
11165   if (cu->language == language_ada && cu->builder->outermost_context_p ())
11166     return cu->builder->get_global_using_directives ();
11167   else
11168     return cu->builder->get_local_using_directives ();
11169 }
11170
11171 /* Read the import statement specified by the given die and record it.  */
11172
11173 static void
11174 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11175 {
11176   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11177   struct attribute *import_attr;
11178   struct die_info *imported_die, *child_die;
11179   struct dwarf2_cu *imported_cu;
11180   const char *imported_name;
11181   const char *imported_name_prefix;
11182   const char *canonical_name;
11183   const char *import_alias;
11184   const char *imported_declaration = NULL;
11185   const char *import_prefix;
11186   std::vector<const char *> excludes;
11187
11188   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11189   if (import_attr == NULL)
11190     {
11191       complaint (_("Tag '%s' has no DW_AT_import"),
11192                  dwarf_tag_name (die->tag));
11193       return;
11194     }
11195
11196   imported_cu = cu;
11197   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11198   imported_name = dwarf2_name (imported_die, imported_cu);
11199   if (imported_name == NULL)
11200     {
11201       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11202
11203         The import in the following code:
11204         namespace A
11205           {
11206             typedef int B;
11207           }
11208
11209         int main ()
11210           {
11211             using A::B;
11212             B b;
11213             return b;
11214           }
11215
11216         ...
11217          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11218             <52>   DW_AT_decl_file   : 1
11219             <53>   DW_AT_decl_line   : 6
11220             <54>   DW_AT_import      : <0x75>
11221          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11222             <59>   DW_AT_name        : B
11223             <5b>   DW_AT_decl_file   : 1
11224             <5c>   DW_AT_decl_line   : 2
11225             <5d>   DW_AT_type        : <0x6e>
11226         ...
11227          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11228             <76>   DW_AT_byte_size   : 4
11229             <77>   DW_AT_encoding    : 5        (signed)
11230
11231         imports the wrong die ( 0x75 instead of 0x58 ).
11232         This case will be ignored until the gcc bug is fixed.  */
11233       return;
11234     }
11235
11236   /* Figure out the local name after import.  */
11237   import_alias = dwarf2_name (die, cu);
11238
11239   /* Figure out where the statement is being imported to.  */
11240   import_prefix = determine_prefix (die, cu);
11241
11242   /* Figure out what the scope of the imported die is and prepend it
11243      to the name of the imported die.  */
11244   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11245
11246   if (imported_die->tag != DW_TAG_namespace
11247       && imported_die->tag != DW_TAG_module)
11248     {
11249       imported_declaration = imported_name;
11250       canonical_name = imported_name_prefix;
11251     }
11252   else if (strlen (imported_name_prefix) > 0)
11253     canonical_name = obconcat (&objfile->objfile_obstack,
11254                                imported_name_prefix,
11255                                (cu->language == language_d ? "." : "::"),
11256                                imported_name, (char *) NULL);
11257   else
11258     canonical_name = imported_name;
11259
11260   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11261     for (child_die = die->child; child_die && child_die->tag;
11262          child_die = sibling_die (child_die))
11263       {
11264         /* DWARF-4: A Fortran use statement with a “rename list” may be
11265            represented by an imported module entry with an import attribute
11266            referring to the module and owned entries corresponding to those
11267            entities that are renamed as part of being imported.  */
11268
11269         if (child_die->tag != DW_TAG_imported_declaration)
11270           {
11271             complaint (_("child DW_TAG_imported_declaration expected "
11272                          "- DIE at %s [in module %s]"),
11273                        sect_offset_str (child_die->sect_off),
11274                        objfile_name (objfile));
11275             continue;
11276           }
11277
11278         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11279         if (import_attr == NULL)
11280           {
11281             complaint (_("Tag '%s' has no DW_AT_import"),
11282                        dwarf_tag_name (child_die->tag));
11283             continue;
11284           }
11285
11286         imported_cu = cu;
11287         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11288                                               &imported_cu);
11289         imported_name = dwarf2_name (imported_die, imported_cu);
11290         if (imported_name == NULL)
11291           {
11292             complaint (_("child DW_TAG_imported_declaration has unknown "
11293                          "imported name - DIE at %s [in module %s]"),
11294                        sect_offset_str (child_die->sect_off),
11295                        objfile_name (objfile));
11296             continue;
11297           }
11298
11299         excludes.push_back (imported_name);
11300
11301         process_die (child_die, cu);
11302       }
11303
11304   add_using_directive (using_directives (cu),
11305                        import_prefix,
11306                        canonical_name,
11307                        import_alias,
11308                        imported_declaration,
11309                        excludes,
11310                        0,
11311                        &objfile->objfile_obstack);
11312 }
11313
11314 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11315    types, but gives them a size of zero.  Starting with version 14,
11316    ICC is compatible with GCC.  */
11317
11318 static int
11319 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11320 {
11321   if (!cu->checked_producer)
11322     check_producer (cu);
11323
11324   return cu->producer_is_icc_lt_14;
11325 }
11326
11327 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11328    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11329    this, it was first present in GCC release 4.3.0.  */
11330
11331 static int
11332 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11333 {
11334   if (!cu->checked_producer)
11335     check_producer (cu);
11336
11337   return cu->producer_is_gcc_lt_4_3;
11338 }
11339
11340 static file_and_directory
11341 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11342 {
11343   file_and_directory res;
11344
11345   /* Find the filename.  Do not use dwarf2_name here, since the filename
11346      is not a source language identifier.  */
11347   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11348   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11349
11350   if (res.comp_dir == NULL
11351       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11352       && IS_ABSOLUTE_PATH (res.name))
11353     {
11354       res.comp_dir_storage = ldirname (res.name);
11355       if (!res.comp_dir_storage.empty ())
11356         res.comp_dir = res.comp_dir_storage.c_str ();
11357     }
11358   if (res.comp_dir != NULL)
11359     {
11360       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11361          directory, get rid of it.  */
11362       const char *cp = strchr (res.comp_dir, ':');
11363
11364       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11365         res.comp_dir = cp + 1;
11366     }
11367
11368   if (res.name == NULL)
11369     res.name = "<unknown>";
11370
11371   return res;
11372 }
11373
11374 /* Handle DW_AT_stmt_list for a compilation unit.
11375    DIE is the DW_TAG_compile_unit die for CU.
11376    COMP_DIR is the compilation directory.  LOWPC is passed to
11377    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11378
11379 static void
11380 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11381                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11382 {
11383   struct dwarf2_per_objfile *dwarf2_per_objfile
11384     = cu->per_cu->dwarf2_per_objfile;
11385   struct objfile *objfile = dwarf2_per_objfile->objfile;
11386   struct attribute *attr;
11387   struct line_header line_header_local;
11388   hashval_t line_header_local_hash;
11389   void **slot;
11390   int decode_mapping;
11391
11392   gdb_assert (! cu->per_cu->is_debug_types);
11393
11394   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11395   if (attr == NULL)
11396     return;
11397
11398   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11399
11400   /* The line header hash table is only created if needed (it exists to
11401      prevent redundant reading of the line table for partial_units).
11402      If we're given a partial_unit, we'll need it.  If we're given a
11403      compile_unit, then use the line header hash table if it's already
11404      created, but don't create one just yet.  */
11405
11406   if (dwarf2_per_objfile->line_header_hash == NULL
11407       && die->tag == DW_TAG_partial_unit)
11408     {
11409       dwarf2_per_objfile->line_header_hash
11410         = htab_create_alloc_ex (127, line_header_hash_voidp,
11411                                 line_header_eq_voidp,
11412                                 free_line_header_voidp,
11413                                 &objfile->objfile_obstack,
11414                                 hashtab_obstack_allocate,
11415                                 dummy_obstack_deallocate);
11416     }
11417
11418   line_header_local.sect_off = line_offset;
11419   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11420   line_header_local_hash = line_header_hash (&line_header_local);
11421   if (dwarf2_per_objfile->line_header_hash != NULL)
11422     {
11423       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11424                                        &line_header_local,
11425                                        line_header_local_hash, NO_INSERT);
11426
11427       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11428          is not present in *SLOT (since if there is something in *SLOT then
11429          it will be for a partial_unit).  */
11430       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11431         {
11432           gdb_assert (*slot != NULL);
11433           cu->line_header = (struct line_header *) *slot;
11434           return;
11435         }
11436     }
11437
11438   /* dwarf_decode_line_header does not yet provide sufficient information.
11439      We always have to call also dwarf_decode_lines for it.  */
11440   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11441   if (lh == NULL)
11442     return;
11443
11444   cu->line_header = lh.release ();
11445   cu->line_header_die_owner = die;
11446
11447   if (dwarf2_per_objfile->line_header_hash == NULL)
11448     slot = NULL;
11449   else
11450     {
11451       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11452                                        &line_header_local,
11453                                        line_header_local_hash, INSERT);
11454       gdb_assert (slot != NULL);
11455     }
11456   if (slot != NULL && *slot == NULL)
11457     {
11458       /* This newly decoded line number information unit will be owned
11459          by line_header_hash hash table.  */
11460       *slot = cu->line_header;
11461       cu->line_header_die_owner = NULL;
11462     }
11463   else
11464     {
11465       /* We cannot free any current entry in (*slot) as that struct line_header
11466          may be already used by multiple CUs.  Create only temporary decoded
11467          line_header for this CU - it may happen at most once for each line
11468          number information unit.  And if we're not using line_header_hash
11469          then this is what we want as well.  */
11470       gdb_assert (die->tag != DW_TAG_partial_unit);
11471     }
11472   decode_mapping = (die->tag != DW_TAG_partial_unit);
11473   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11474                       decode_mapping);
11475
11476 }
11477
11478 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11479
11480 static void
11481 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11482 {
11483   struct dwarf2_per_objfile *dwarf2_per_objfile
11484     = cu->per_cu->dwarf2_per_objfile;
11485   struct objfile *objfile = dwarf2_per_objfile->objfile;
11486   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11487   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11488   CORE_ADDR highpc = ((CORE_ADDR) 0);
11489   struct attribute *attr;
11490   struct die_info *child_die;
11491   CORE_ADDR baseaddr;
11492
11493   prepare_one_comp_unit (cu, die, cu->language);
11494   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11495
11496   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11497
11498   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11499      from finish_block.  */
11500   if (lowpc == ((CORE_ADDR) -1))
11501     lowpc = highpc;
11502   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11503
11504   file_and_directory fnd = find_file_and_directory (die, cu);
11505
11506   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11507      standardised yet.  As a workaround for the language detection we fall
11508      back to the DW_AT_producer string.  */
11509   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11510     cu->language = language_opencl;
11511
11512   /* Similar hack for Go.  */
11513   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11514     set_cu_language (DW_LANG_Go, cu);
11515
11516   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11517
11518   /* Decode line number information if present.  We do this before
11519      processing child DIEs, so that the line header table is available
11520      for DW_AT_decl_file.  */
11521   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11522
11523   /* Process all dies in compilation unit.  */
11524   if (die->child != NULL)
11525     {
11526       child_die = die->child;
11527       while (child_die && child_die->tag)
11528         {
11529           process_die (child_die, cu);
11530           child_die = sibling_die (child_die);
11531         }
11532     }
11533
11534   /* Decode macro information, if present.  Dwarf 2 macro information
11535      refers to information in the line number info statement program
11536      header, so we can only read it if we've read the header
11537      successfully.  */
11538   attr = dwarf2_attr (die, DW_AT_macros, cu);
11539   if (attr == NULL)
11540     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11541   if (attr && cu->line_header)
11542     {
11543       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11544         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11545
11546       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11547     }
11548   else
11549     {
11550       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11551       if (attr && cu->line_header)
11552         {
11553           unsigned int macro_offset = DW_UNSND (attr);
11554
11555           dwarf_decode_macros (cu, macro_offset, 0);
11556         }
11557     }
11558 }
11559
11560 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11561    Create the set of symtabs used by this TU, or if this TU is sharing
11562    symtabs with another TU and the symtabs have already been created
11563    then restore those symtabs in the line header.
11564    We don't need the pc/line-number mapping for type units.  */
11565
11566 static void
11567 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11568 {
11569   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11570   struct type_unit_group *tu_group;
11571   int first_time;
11572   struct attribute *attr;
11573   unsigned int i;
11574   struct signatured_type *sig_type;
11575
11576   gdb_assert (per_cu->is_debug_types);
11577   sig_type = (struct signatured_type *) per_cu;
11578
11579   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11580
11581   /* If we're using .gdb_index (includes -readnow) then
11582      per_cu->type_unit_group may not have been set up yet.  */
11583   if (sig_type->type_unit_group == NULL)
11584     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11585   tu_group = sig_type->type_unit_group;
11586
11587   /* If we've already processed this stmt_list there's no real need to
11588      do it again, we could fake it and just recreate the part we need
11589      (file name,index -> symtab mapping).  If data shows this optimization
11590      is useful we can do it then.  */
11591   first_time = tu_group->compunit_symtab == NULL;
11592
11593   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11594      debug info.  */
11595   line_header_up lh;
11596   if (attr != NULL)
11597     {
11598       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11599       lh = dwarf_decode_line_header (line_offset, cu);
11600     }
11601   if (lh == NULL)
11602     {
11603       if (first_time)
11604         dwarf2_start_symtab (cu, "", NULL, 0);
11605       else
11606         {
11607           gdb_assert (tu_group->symtabs == NULL);
11608           gdb_assert (cu->builder == nullptr);
11609           struct compunit_symtab *cust = tu_group->compunit_symtab;
11610           cu->builder.reset (new struct buildsym_compunit
11611                              (COMPUNIT_OBJFILE (cust), "",
11612                               COMPUNIT_DIRNAME (cust),
11613                               compunit_language (cust),
11614                               0, cust));
11615         }
11616       return;
11617     }
11618
11619   cu->line_header = lh.release ();
11620   cu->line_header_die_owner = die;
11621
11622   if (first_time)
11623     {
11624       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11625
11626       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11627          still initializing it, and our caller (a few levels up)
11628          process_full_type_unit still needs to know if this is the first
11629          time.  */
11630
11631       tu_group->num_symtabs = cu->line_header->file_names.size ();
11632       tu_group->symtabs = XNEWVEC (struct symtab *,
11633                                    cu->line_header->file_names.size ());
11634
11635       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11636         {
11637           file_entry &fe = cu->line_header->file_names[i];
11638
11639           dwarf2_start_subfile (cu, fe.name, fe.include_dir (cu->line_header));
11640
11641           if (cu->builder->get_current_subfile ()->symtab == NULL)
11642             {
11643               /* NOTE: start_subfile will recognize when it's been
11644                  passed a file it has already seen.  So we can't
11645                  assume there's a simple mapping from
11646                  cu->line_header->file_names to subfiles, plus
11647                  cu->line_header->file_names may contain dups.  */
11648               cu->builder->get_current_subfile ()->symtab
11649                 = allocate_symtab (cust,
11650                                    cu->builder->get_current_subfile ()->name);
11651             }
11652
11653           fe.symtab = cu->builder->get_current_subfile ()->symtab;
11654           tu_group->symtabs[i] = fe.symtab;
11655         }
11656     }
11657   else
11658     {
11659       gdb_assert (cu->builder == nullptr);
11660       struct compunit_symtab *cust = tu_group->compunit_symtab;
11661       cu->builder.reset (new struct buildsym_compunit
11662                          (COMPUNIT_OBJFILE (cust), "",
11663                           COMPUNIT_DIRNAME (cust),
11664                           compunit_language (cust),
11665                           0, cust));
11666
11667       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11668         {
11669           file_entry &fe = cu->line_header->file_names[i];
11670
11671           fe.symtab = tu_group->symtabs[i];
11672         }
11673     }
11674
11675   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11676      so they don't have a "real" (so to speak) symtab anyway.
11677      There is later code that will assign the main symtab to all symbols
11678      that don't have one.  We need to handle the case of a symbol with a
11679      missing symtab (DW_AT_decl_file) anyway.  */
11680 }
11681
11682 /* Process DW_TAG_type_unit.
11683    For TUs we want to skip the first top level sibling if it's not the
11684    actual type being defined by this TU.  In this case the first top
11685    level sibling is there to provide context only.  */
11686
11687 static void
11688 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11689 {
11690   struct die_info *child_die;
11691
11692   prepare_one_comp_unit (cu, die, language_minimal);
11693
11694   /* Initialize (or reinitialize) the machinery for building symtabs.
11695      We do this before processing child DIEs, so that the line header table
11696      is available for DW_AT_decl_file.  */
11697   setup_type_unit_groups (die, cu);
11698
11699   if (die->child != NULL)
11700     {
11701       child_die = die->child;
11702       while (child_die && child_die->tag)
11703         {
11704           process_die (child_die, cu);
11705           child_die = sibling_die (child_die);
11706         }
11707     }
11708 }
11709 \f
11710 /* DWO/DWP files.
11711
11712    http://gcc.gnu.org/wiki/DebugFission
11713    http://gcc.gnu.org/wiki/DebugFissionDWP
11714
11715    To simplify handling of both DWO files ("object" files with the DWARF info)
11716    and DWP files (a file with the DWOs packaged up into one file), we treat
11717    DWP files as having a collection of virtual DWO files.  */
11718
11719 static hashval_t
11720 hash_dwo_file (const void *item)
11721 {
11722   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11723   hashval_t hash;
11724
11725   hash = htab_hash_string (dwo_file->dwo_name);
11726   if (dwo_file->comp_dir != NULL)
11727     hash += htab_hash_string (dwo_file->comp_dir);
11728   return hash;
11729 }
11730
11731 static int
11732 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11733 {
11734   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11735   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11736
11737   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11738     return 0;
11739   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11740     return lhs->comp_dir == rhs->comp_dir;
11741   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11742 }
11743
11744 /* Allocate a hash table for DWO files.  */
11745
11746 static htab_t
11747 allocate_dwo_file_hash_table (struct objfile *objfile)
11748 {
11749   return htab_create_alloc_ex (41,
11750                                hash_dwo_file,
11751                                eq_dwo_file,
11752                                NULL,
11753                                &objfile->objfile_obstack,
11754                                hashtab_obstack_allocate,
11755                                dummy_obstack_deallocate);
11756 }
11757
11758 /* Lookup DWO file DWO_NAME.  */
11759
11760 static void **
11761 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11762                       const char *dwo_name,
11763                       const char *comp_dir)
11764 {
11765   struct dwo_file find_entry;
11766   void **slot;
11767
11768   if (dwarf2_per_objfile->dwo_files == NULL)
11769     dwarf2_per_objfile->dwo_files
11770       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11771
11772   memset (&find_entry, 0, sizeof (find_entry));
11773   find_entry.dwo_name = dwo_name;
11774   find_entry.comp_dir = comp_dir;
11775   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11776
11777   return slot;
11778 }
11779
11780 static hashval_t
11781 hash_dwo_unit (const void *item)
11782 {
11783   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11784
11785   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11786   return dwo_unit->signature;
11787 }
11788
11789 static int
11790 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11791 {
11792   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11793   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11794
11795   /* The signature is assumed to be unique within the DWO file.
11796      So while object file CU dwo_id's always have the value zero,
11797      that's OK, assuming each object file DWO file has only one CU,
11798      and that's the rule for now.  */
11799   return lhs->signature == rhs->signature;
11800 }
11801
11802 /* Allocate a hash table for DWO CUs,TUs.
11803    There is one of these tables for each of CUs,TUs for each DWO file.  */
11804
11805 static htab_t
11806 allocate_dwo_unit_table (struct objfile *objfile)
11807 {
11808   /* Start out with a pretty small number.
11809      Generally DWO files contain only one CU and maybe some TUs.  */
11810   return htab_create_alloc_ex (3,
11811                                hash_dwo_unit,
11812                                eq_dwo_unit,
11813                                NULL,
11814                                &objfile->objfile_obstack,
11815                                hashtab_obstack_allocate,
11816                                dummy_obstack_deallocate);
11817 }
11818
11819 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11820
11821 struct create_dwo_cu_data
11822 {
11823   struct dwo_file *dwo_file;
11824   struct dwo_unit dwo_unit;
11825 };
11826
11827 /* die_reader_func for create_dwo_cu.  */
11828
11829 static void
11830 create_dwo_cu_reader (const struct die_reader_specs *reader,
11831                       const gdb_byte *info_ptr,
11832                       struct die_info *comp_unit_die,
11833                       int has_children,
11834                       void *datap)
11835 {
11836   struct dwarf2_cu *cu = reader->cu;
11837   sect_offset sect_off = cu->per_cu->sect_off;
11838   struct dwarf2_section_info *section = cu->per_cu->section;
11839   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11840   struct dwo_file *dwo_file = data->dwo_file;
11841   struct dwo_unit *dwo_unit = &data->dwo_unit;
11842   struct attribute *attr;
11843
11844   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11845   if (attr == NULL)
11846     {
11847       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11848                    " its dwo_id [in module %s]"),
11849                  sect_offset_str (sect_off), dwo_file->dwo_name);
11850       return;
11851     }
11852
11853   dwo_unit->dwo_file = dwo_file;
11854   dwo_unit->signature = DW_UNSND (attr);
11855   dwo_unit->section = section;
11856   dwo_unit->sect_off = sect_off;
11857   dwo_unit->length = cu->per_cu->length;
11858
11859   if (dwarf_read_debug)
11860     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11861                         sect_offset_str (sect_off),
11862                         hex_string (dwo_unit->signature));
11863 }
11864
11865 /* Create the dwo_units for the CUs in a DWO_FILE.
11866    Note: This function processes DWO files only, not DWP files.  */
11867
11868 static void
11869 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11870                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11871                        htab_t &cus_htab)
11872 {
11873   struct objfile *objfile = dwarf2_per_objfile->objfile;
11874   const gdb_byte *info_ptr, *end_ptr;
11875
11876   dwarf2_read_section (objfile, &section);
11877   info_ptr = section.buffer;
11878
11879   if (info_ptr == NULL)
11880     return;
11881
11882   if (dwarf_read_debug)
11883     {
11884       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11885                           get_section_name (&section),
11886                           get_section_file_name (&section));
11887     }
11888
11889   end_ptr = info_ptr + section.size;
11890   while (info_ptr < end_ptr)
11891     {
11892       struct dwarf2_per_cu_data per_cu;
11893       struct create_dwo_cu_data create_dwo_cu_data;
11894       struct dwo_unit *dwo_unit;
11895       void **slot;
11896       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11897
11898       memset (&create_dwo_cu_data.dwo_unit, 0,
11899               sizeof (create_dwo_cu_data.dwo_unit));
11900       memset (&per_cu, 0, sizeof (per_cu));
11901       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11902       per_cu.is_debug_types = 0;
11903       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11904       per_cu.section = &section;
11905       create_dwo_cu_data.dwo_file = &dwo_file;
11906
11907       init_cutu_and_read_dies_no_follow (
11908           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11909       info_ptr += per_cu.length;
11910
11911       // If the unit could not be parsed, skip it.
11912       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11913         continue;
11914
11915       if (cus_htab == NULL)
11916         cus_htab = allocate_dwo_unit_table (objfile);
11917
11918       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11919       *dwo_unit = create_dwo_cu_data.dwo_unit;
11920       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11921       gdb_assert (slot != NULL);
11922       if (*slot != NULL)
11923         {
11924           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11925           sect_offset dup_sect_off = dup_cu->sect_off;
11926
11927           complaint (_("debug cu entry at offset %s is duplicate to"
11928                        " the entry at offset %s, signature %s"),
11929                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11930                      hex_string (dwo_unit->signature));
11931         }
11932       *slot = (void *)dwo_unit;
11933     }
11934 }
11935
11936 /* DWP file .debug_{cu,tu}_index section format:
11937    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11938
11939    DWP Version 1:
11940
11941    Both index sections have the same format, and serve to map a 64-bit
11942    signature to a set of section numbers.  Each section begins with a header,
11943    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11944    indexes, and a pool of 32-bit section numbers.  The index sections will be
11945    aligned at 8-byte boundaries in the file.
11946
11947    The index section header consists of:
11948
11949     V, 32 bit version number
11950     -, 32 bits unused
11951     N, 32 bit number of compilation units or type units in the index
11952     M, 32 bit number of slots in the hash table
11953
11954    Numbers are recorded using the byte order of the application binary.
11955
11956    The hash table begins at offset 16 in the section, and consists of an array
11957    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11958    order of the application binary).  Unused slots in the hash table are 0.
11959    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11960
11961    The parallel table begins immediately after the hash table
11962    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11963    array of 32-bit indexes (using the byte order of the application binary),
11964    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11965    table contains a 32-bit index into the pool of section numbers.  For unused
11966    hash table slots, the corresponding entry in the parallel table will be 0.
11967
11968    The pool of section numbers begins immediately following the hash table
11969    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11970    section numbers consists of an array of 32-bit words (using the byte order
11971    of the application binary).  Each item in the array is indexed starting
11972    from 0.  The hash table entry provides the index of the first section
11973    number in the set.  Additional section numbers in the set follow, and the
11974    set is terminated by a 0 entry (section number 0 is not used in ELF).
11975
11976    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11977    section must be the first entry in the set, and the .debug_abbrev.dwo must
11978    be the second entry. Other members of the set may follow in any order.
11979
11980    ---
11981
11982    DWP Version 2:
11983
11984    DWP Version 2 combines all the .debug_info, etc. sections into one,
11985    and the entries in the index tables are now offsets into these sections.
11986    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11987    section.
11988
11989    Index Section Contents:
11990     Header
11991     Hash Table of Signatures   dwp_hash_table.hash_table
11992     Parallel Table of Indices  dwp_hash_table.unit_table
11993     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11994     Table of Section Sizes     dwp_hash_table.v2.sizes
11995
11996    The index section header consists of:
11997
11998     V, 32 bit version number
11999     L, 32 bit number of columns in the table of section offsets
12000     N, 32 bit number of compilation units or type units in the index
12001     M, 32 bit number of slots in the hash table
12002
12003    Numbers are recorded using the byte order of the application binary.
12004
12005    The hash table has the same format as version 1.
12006    The parallel table of indices has the same format as version 1,
12007    except that the entries are origin-1 indices into the table of sections
12008    offsets and the table of section sizes.
12009
12010    The table of offsets begins immediately following the parallel table
12011    (at offset 16 + 12 * M from the beginning of the section).  The table is
12012    a two-dimensional array of 32-bit words (using the byte order of the
12013    application binary), with L columns and N+1 rows, in row-major order.
12014    Each row in the array is indexed starting from 0.  The first row provides
12015    a key to the remaining rows: each column in this row provides an identifier
12016    for a debug section, and the offsets in the same column of subsequent rows
12017    refer to that section.  The section identifiers are:
12018
12019     DW_SECT_INFO         1  .debug_info.dwo
12020     DW_SECT_TYPES        2  .debug_types.dwo
12021     DW_SECT_ABBREV       3  .debug_abbrev.dwo
12022     DW_SECT_LINE         4  .debug_line.dwo
12023     DW_SECT_LOC          5  .debug_loc.dwo
12024     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
12025     DW_SECT_MACINFO      7  .debug_macinfo.dwo
12026     DW_SECT_MACRO        8  .debug_macro.dwo
12027
12028    The offsets provided by the CU and TU index sections are the base offsets
12029    for the contributions made by each CU or TU to the corresponding section
12030    in the package file.  Each CU and TU header contains an abbrev_offset
12031    field, used to find the abbreviations table for that CU or TU within the
12032    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
12033    be interpreted as relative to the base offset given in the index section.
12034    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
12035    should be interpreted as relative to the base offset for .debug_line.dwo,
12036    and offsets into other debug sections obtained from DWARF attributes should
12037    also be interpreted as relative to the corresponding base offset.
12038
12039    The table of sizes begins immediately following the table of offsets.
12040    Like the table of offsets, it is a two-dimensional array of 32-bit words,
12041    with L columns and N rows, in row-major order.  Each row in the array is
12042    indexed starting from 1 (row 0 is shared by the two tables).
12043
12044    ---
12045
12046    Hash table lookup is handled the same in version 1 and 2:
12047
12048    We assume that N and M will not exceed 2^32 - 1.
12049    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
12050
12051    Given a 64-bit compilation unit signature or a type signature S, an entry
12052    in the hash table is located as follows:
12053
12054    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
12055       the low-order k bits all set to 1.
12056
12057    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
12058
12059    3) If the hash table entry at index H matches the signature, use that
12060       entry.  If the hash table entry at index H is unused (all zeroes),
12061       terminate the search: the signature is not present in the table.
12062
12063    4) Let H = (H + H') modulo M. Repeat at Step 3.
12064
12065    Because M > N and H' and M are relatively prime, the search is guaranteed
12066    to stop at an unused slot or find the match.  */
12067
12068 /* Create a hash table to map DWO IDs to their CU/TU entry in
12069    .debug_{info,types}.dwo in DWP_FILE.
12070    Returns NULL if there isn't one.
12071    Note: This function processes DWP files only, not DWO files.  */
12072
12073 static struct dwp_hash_table *
12074 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12075                        struct dwp_file *dwp_file, int is_debug_types)
12076 {
12077   struct objfile *objfile = dwarf2_per_objfile->objfile;
12078   bfd *dbfd = dwp_file->dbfd.get ();
12079   const gdb_byte *index_ptr, *index_end;
12080   struct dwarf2_section_info *index;
12081   uint32_t version, nr_columns, nr_units, nr_slots;
12082   struct dwp_hash_table *htab;
12083
12084   if (is_debug_types)
12085     index = &dwp_file->sections.tu_index;
12086   else
12087     index = &dwp_file->sections.cu_index;
12088
12089   if (dwarf2_section_empty_p (index))
12090     return NULL;
12091   dwarf2_read_section (objfile, index);
12092
12093   index_ptr = index->buffer;
12094   index_end = index_ptr + index->size;
12095
12096   version = read_4_bytes (dbfd, index_ptr);
12097   index_ptr += 4;
12098   if (version == 2)
12099     nr_columns = read_4_bytes (dbfd, index_ptr);
12100   else
12101     nr_columns = 0;
12102   index_ptr += 4;
12103   nr_units = read_4_bytes (dbfd, index_ptr);
12104   index_ptr += 4;
12105   nr_slots = read_4_bytes (dbfd, index_ptr);
12106   index_ptr += 4;
12107
12108   if (version != 1 && version != 2)
12109     {
12110       error (_("Dwarf Error: unsupported DWP file version (%s)"
12111                " [in module %s]"),
12112              pulongest (version), dwp_file->name);
12113     }
12114   if (nr_slots != (nr_slots & -nr_slots))
12115     {
12116       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12117                " is not power of 2 [in module %s]"),
12118              pulongest (nr_slots), dwp_file->name);
12119     }
12120
12121   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12122   htab->version = version;
12123   htab->nr_columns = nr_columns;
12124   htab->nr_units = nr_units;
12125   htab->nr_slots = nr_slots;
12126   htab->hash_table = index_ptr;
12127   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12128
12129   /* Exit early if the table is empty.  */
12130   if (nr_slots == 0 || nr_units == 0
12131       || (version == 2 && nr_columns == 0))
12132     {
12133       /* All must be zero.  */
12134       if (nr_slots != 0 || nr_units != 0
12135           || (version == 2 && nr_columns != 0))
12136         {
12137           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12138                        " all zero [in modules %s]"),
12139                      dwp_file->name);
12140         }
12141       return htab;
12142     }
12143
12144   if (version == 1)
12145     {
12146       htab->section_pool.v1.indices =
12147         htab->unit_table + sizeof (uint32_t) * nr_slots;
12148       /* It's harder to decide whether the section is too small in v1.
12149          V1 is deprecated anyway so we punt.  */
12150     }
12151   else
12152     {
12153       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12154       int *ids = htab->section_pool.v2.section_ids;
12155       /* Reverse map for error checking.  */
12156       int ids_seen[DW_SECT_MAX + 1];
12157       int i;
12158
12159       if (nr_columns < 2)
12160         {
12161           error (_("Dwarf Error: bad DWP hash table, too few columns"
12162                    " in section table [in module %s]"),
12163                  dwp_file->name);
12164         }
12165       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12166         {
12167           error (_("Dwarf Error: bad DWP hash table, too many columns"
12168                    " in section table [in module %s]"),
12169                  dwp_file->name);
12170         }
12171       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12172       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12173       for (i = 0; i < nr_columns; ++i)
12174         {
12175           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12176
12177           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12178             {
12179               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12180                        " in section table [in module %s]"),
12181                      id, dwp_file->name);
12182             }
12183           if (ids_seen[id] != -1)
12184             {
12185               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12186                        " id %d in section table [in module %s]"),
12187                      id, dwp_file->name);
12188             }
12189           ids_seen[id] = i;
12190           ids[i] = id;
12191         }
12192       /* Must have exactly one info or types section.  */
12193       if (((ids_seen[DW_SECT_INFO] != -1)
12194            + (ids_seen[DW_SECT_TYPES] != -1))
12195           != 1)
12196         {
12197           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12198                    " DWO info/types section [in module %s]"),
12199                  dwp_file->name);
12200         }
12201       /* Must have an abbrev section.  */
12202       if (ids_seen[DW_SECT_ABBREV] == -1)
12203         {
12204           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12205                    " section [in module %s]"),
12206                  dwp_file->name);
12207         }
12208       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12209       htab->section_pool.v2.sizes =
12210         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12211                                          * nr_units * nr_columns);
12212       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12213                                           * nr_units * nr_columns))
12214           > index_end)
12215         {
12216           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12217                    " [in module %s]"),
12218                  dwp_file->name);
12219         }
12220     }
12221
12222   return htab;
12223 }
12224
12225 /* Update SECTIONS with the data from SECTP.
12226
12227    This function is like the other "locate" section routines that are
12228    passed to bfd_map_over_sections, but in this context the sections to
12229    read comes from the DWP V1 hash table, not the full ELF section table.
12230
12231    The result is non-zero for success, or zero if an error was found.  */
12232
12233 static int
12234 locate_v1_virtual_dwo_sections (asection *sectp,
12235                                 struct virtual_v1_dwo_sections *sections)
12236 {
12237   const struct dwop_section_names *names = &dwop_section_names;
12238
12239   if (section_is_p (sectp->name, &names->abbrev_dwo))
12240     {
12241       /* There can be only one.  */
12242       if (sections->abbrev.s.section != NULL)
12243         return 0;
12244       sections->abbrev.s.section = sectp;
12245       sections->abbrev.size = bfd_get_section_size (sectp);
12246     }
12247   else if (section_is_p (sectp->name, &names->info_dwo)
12248            || section_is_p (sectp->name, &names->types_dwo))
12249     {
12250       /* There can be only one.  */
12251       if (sections->info_or_types.s.section != NULL)
12252         return 0;
12253       sections->info_or_types.s.section = sectp;
12254       sections->info_or_types.size = bfd_get_section_size (sectp);
12255     }
12256   else if (section_is_p (sectp->name, &names->line_dwo))
12257     {
12258       /* There can be only one.  */
12259       if (sections->line.s.section != NULL)
12260         return 0;
12261       sections->line.s.section = sectp;
12262       sections->line.size = bfd_get_section_size (sectp);
12263     }
12264   else if (section_is_p (sectp->name, &names->loc_dwo))
12265     {
12266       /* There can be only one.  */
12267       if (sections->loc.s.section != NULL)
12268         return 0;
12269       sections->loc.s.section = sectp;
12270       sections->loc.size = bfd_get_section_size (sectp);
12271     }
12272   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12273     {
12274       /* There can be only one.  */
12275       if (sections->macinfo.s.section != NULL)
12276         return 0;
12277       sections->macinfo.s.section = sectp;
12278       sections->macinfo.size = bfd_get_section_size (sectp);
12279     }
12280   else if (section_is_p (sectp->name, &names->macro_dwo))
12281     {
12282       /* There can be only one.  */
12283       if (sections->macro.s.section != NULL)
12284         return 0;
12285       sections->macro.s.section = sectp;
12286       sections->macro.size = bfd_get_section_size (sectp);
12287     }
12288   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12289     {
12290       /* There can be only one.  */
12291       if (sections->str_offsets.s.section != NULL)
12292         return 0;
12293       sections->str_offsets.s.section = sectp;
12294       sections->str_offsets.size = bfd_get_section_size (sectp);
12295     }
12296   else
12297     {
12298       /* No other kind of section is valid.  */
12299       return 0;
12300     }
12301
12302   return 1;
12303 }
12304
12305 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12306    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12307    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12308    This is for DWP version 1 files.  */
12309
12310 static struct dwo_unit *
12311 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12312                            struct dwp_file *dwp_file,
12313                            uint32_t unit_index,
12314                            const char *comp_dir,
12315                            ULONGEST signature, int is_debug_types)
12316 {
12317   struct objfile *objfile = dwarf2_per_objfile->objfile;
12318   const struct dwp_hash_table *dwp_htab =
12319     is_debug_types ? dwp_file->tus : dwp_file->cus;
12320   bfd *dbfd = dwp_file->dbfd.get ();
12321   const char *kind = is_debug_types ? "TU" : "CU";
12322   struct dwo_file *dwo_file;
12323   struct dwo_unit *dwo_unit;
12324   struct virtual_v1_dwo_sections sections;
12325   void **dwo_file_slot;
12326   int i;
12327
12328   gdb_assert (dwp_file->version == 1);
12329
12330   if (dwarf_read_debug)
12331     {
12332       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12333                           kind,
12334                           pulongest (unit_index), hex_string (signature),
12335                           dwp_file->name);
12336     }
12337
12338   /* Fetch the sections of this DWO unit.
12339      Put a limit on the number of sections we look for so that bad data
12340      doesn't cause us to loop forever.  */
12341
12342 #define MAX_NR_V1_DWO_SECTIONS \
12343   (1 /* .debug_info or .debug_types */ \
12344    + 1 /* .debug_abbrev */ \
12345    + 1 /* .debug_line */ \
12346    + 1 /* .debug_loc */ \
12347    + 1 /* .debug_str_offsets */ \
12348    + 1 /* .debug_macro or .debug_macinfo */ \
12349    + 1 /* trailing zero */)
12350
12351   memset (&sections, 0, sizeof (sections));
12352
12353   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12354     {
12355       asection *sectp;
12356       uint32_t section_nr =
12357         read_4_bytes (dbfd,
12358                       dwp_htab->section_pool.v1.indices
12359                       + (unit_index + i) * sizeof (uint32_t));
12360
12361       if (section_nr == 0)
12362         break;
12363       if (section_nr >= dwp_file->num_sections)
12364         {
12365           error (_("Dwarf Error: bad DWP hash table, section number too large"
12366                    " [in module %s]"),
12367                  dwp_file->name);
12368         }
12369
12370       sectp = dwp_file->elf_sections[section_nr];
12371       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12372         {
12373           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12374                    " [in module %s]"),
12375                  dwp_file->name);
12376         }
12377     }
12378
12379   if (i < 2
12380       || dwarf2_section_empty_p (&sections.info_or_types)
12381       || dwarf2_section_empty_p (&sections.abbrev))
12382     {
12383       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12384                " [in module %s]"),
12385              dwp_file->name);
12386     }
12387   if (i == MAX_NR_V1_DWO_SECTIONS)
12388     {
12389       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12390                " [in module %s]"),
12391              dwp_file->name);
12392     }
12393
12394   /* It's easier for the rest of the code if we fake a struct dwo_file and
12395      have dwo_unit "live" in that.  At least for now.
12396
12397      The DWP file can be made up of a random collection of CUs and TUs.
12398      However, for each CU + set of TUs that came from the same original DWO
12399      file, we can combine them back into a virtual DWO file to save space
12400      (fewer struct dwo_file objects to allocate).  Remember that for really
12401      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12402
12403   std::string virtual_dwo_name =
12404     string_printf ("virtual-dwo/%d-%d-%d-%d",
12405                    get_section_id (&sections.abbrev),
12406                    get_section_id (&sections.line),
12407                    get_section_id (&sections.loc),
12408                    get_section_id (&sections.str_offsets));
12409   /* Can we use an existing virtual DWO file?  */
12410   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12411                                         virtual_dwo_name.c_str (),
12412                                         comp_dir);
12413   /* Create one if necessary.  */
12414   if (*dwo_file_slot == NULL)
12415     {
12416       if (dwarf_read_debug)
12417         {
12418           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12419                               virtual_dwo_name.c_str ());
12420         }
12421       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12422       dwo_file->dwo_name
12423         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12424                                         virtual_dwo_name.c_str (),
12425                                         virtual_dwo_name.size ());
12426       dwo_file->comp_dir = comp_dir;
12427       dwo_file->sections.abbrev = sections.abbrev;
12428       dwo_file->sections.line = sections.line;
12429       dwo_file->sections.loc = sections.loc;
12430       dwo_file->sections.macinfo = sections.macinfo;
12431       dwo_file->sections.macro = sections.macro;
12432       dwo_file->sections.str_offsets = sections.str_offsets;
12433       /* The "str" section is global to the entire DWP file.  */
12434       dwo_file->sections.str = dwp_file->sections.str;
12435       /* The info or types section is assigned below to dwo_unit,
12436          there's no need to record it in dwo_file.
12437          Also, we can't simply record type sections in dwo_file because
12438          we record a pointer into the vector in dwo_unit.  As we collect more
12439          types we'll grow the vector and eventually have to reallocate space
12440          for it, invalidating all copies of pointers into the previous
12441          contents.  */
12442       *dwo_file_slot = dwo_file;
12443     }
12444   else
12445     {
12446       if (dwarf_read_debug)
12447         {
12448           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12449                               virtual_dwo_name.c_str ());
12450         }
12451       dwo_file = (struct dwo_file *) *dwo_file_slot;
12452     }
12453
12454   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12455   dwo_unit->dwo_file = dwo_file;
12456   dwo_unit->signature = signature;
12457   dwo_unit->section =
12458     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12459   *dwo_unit->section = sections.info_or_types;
12460   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12461
12462   return dwo_unit;
12463 }
12464
12465 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12466    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12467    piece within that section used by a TU/CU, return a virtual section
12468    of just that piece.  */
12469
12470 static struct dwarf2_section_info
12471 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12472                        struct dwarf2_section_info *section,
12473                        bfd_size_type offset, bfd_size_type size)
12474 {
12475   struct dwarf2_section_info result;
12476   asection *sectp;
12477
12478   gdb_assert (section != NULL);
12479   gdb_assert (!section->is_virtual);
12480
12481   memset (&result, 0, sizeof (result));
12482   result.s.containing_section = section;
12483   result.is_virtual = 1;
12484
12485   if (size == 0)
12486     return result;
12487
12488   sectp = get_section_bfd_section (section);
12489
12490   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12491      bounds of the real section.  This is a pretty-rare event, so just
12492      flag an error (easier) instead of a warning and trying to cope.  */
12493   if (sectp == NULL
12494       || offset + size > bfd_get_section_size (sectp))
12495     {
12496       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12497                " in section %s [in module %s]"),
12498              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12499              objfile_name (dwarf2_per_objfile->objfile));
12500     }
12501
12502   result.virtual_offset = offset;
12503   result.size = size;
12504   return result;
12505 }
12506
12507 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12508    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12509    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12510    This is for DWP version 2 files.  */
12511
12512 static struct dwo_unit *
12513 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12514                            struct dwp_file *dwp_file,
12515                            uint32_t unit_index,
12516                            const char *comp_dir,
12517                            ULONGEST signature, int is_debug_types)
12518 {
12519   struct objfile *objfile = dwarf2_per_objfile->objfile;
12520   const struct dwp_hash_table *dwp_htab =
12521     is_debug_types ? dwp_file->tus : dwp_file->cus;
12522   bfd *dbfd = dwp_file->dbfd.get ();
12523   const char *kind = is_debug_types ? "TU" : "CU";
12524   struct dwo_file *dwo_file;
12525   struct dwo_unit *dwo_unit;
12526   struct virtual_v2_dwo_sections sections;
12527   void **dwo_file_slot;
12528   int i;
12529
12530   gdb_assert (dwp_file->version == 2);
12531
12532   if (dwarf_read_debug)
12533     {
12534       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12535                           kind,
12536                           pulongest (unit_index), hex_string (signature),
12537                           dwp_file->name);
12538     }
12539
12540   /* Fetch the section offsets of this DWO unit.  */
12541
12542   memset (&sections, 0, sizeof (sections));
12543
12544   for (i = 0; i < dwp_htab->nr_columns; ++i)
12545     {
12546       uint32_t offset = read_4_bytes (dbfd,
12547                                       dwp_htab->section_pool.v2.offsets
12548                                       + (((unit_index - 1) * dwp_htab->nr_columns
12549                                           + i)
12550                                          * sizeof (uint32_t)));
12551       uint32_t size = read_4_bytes (dbfd,
12552                                     dwp_htab->section_pool.v2.sizes
12553                                     + (((unit_index - 1) * dwp_htab->nr_columns
12554                                         + i)
12555                                        * sizeof (uint32_t)));
12556
12557       switch (dwp_htab->section_pool.v2.section_ids[i])
12558         {
12559         case DW_SECT_INFO:
12560         case DW_SECT_TYPES:
12561           sections.info_or_types_offset = offset;
12562           sections.info_or_types_size = size;
12563           break;
12564         case DW_SECT_ABBREV:
12565           sections.abbrev_offset = offset;
12566           sections.abbrev_size = size;
12567           break;
12568         case DW_SECT_LINE:
12569           sections.line_offset = offset;
12570           sections.line_size = size;
12571           break;
12572         case DW_SECT_LOC:
12573           sections.loc_offset = offset;
12574           sections.loc_size = size;
12575           break;
12576         case DW_SECT_STR_OFFSETS:
12577           sections.str_offsets_offset = offset;
12578           sections.str_offsets_size = size;
12579           break;
12580         case DW_SECT_MACINFO:
12581           sections.macinfo_offset = offset;
12582           sections.macinfo_size = size;
12583           break;
12584         case DW_SECT_MACRO:
12585           sections.macro_offset = offset;
12586           sections.macro_size = size;
12587           break;
12588         }
12589     }
12590
12591   /* It's easier for the rest of the code if we fake a struct dwo_file and
12592      have dwo_unit "live" in that.  At least for now.
12593
12594      The DWP file can be made up of a random collection of CUs and TUs.
12595      However, for each CU + set of TUs that came from the same original DWO
12596      file, we can combine them back into a virtual DWO file to save space
12597      (fewer struct dwo_file objects to allocate).  Remember that for really
12598      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12599
12600   std::string virtual_dwo_name =
12601     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12602                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12603                    (long) (sections.line_size ? sections.line_offset : 0),
12604                    (long) (sections.loc_size ? sections.loc_offset : 0),
12605                    (long) (sections.str_offsets_size
12606                            ? sections.str_offsets_offset : 0));
12607   /* Can we use an existing virtual DWO file?  */
12608   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12609                                         virtual_dwo_name.c_str (),
12610                                         comp_dir);
12611   /* Create one if necessary.  */
12612   if (*dwo_file_slot == NULL)
12613     {
12614       if (dwarf_read_debug)
12615         {
12616           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12617                               virtual_dwo_name.c_str ());
12618         }
12619       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12620       dwo_file->dwo_name
12621         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12622                                         virtual_dwo_name.c_str (),
12623                                         virtual_dwo_name.size ());
12624       dwo_file->comp_dir = comp_dir;
12625       dwo_file->sections.abbrev =
12626         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12627                                sections.abbrev_offset, sections.abbrev_size);
12628       dwo_file->sections.line =
12629         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12630                                sections.line_offset, sections.line_size);
12631       dwo_file->sections.loc =
12632         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12633                                sections.loc_offset, sections.loc_size);
12634       dwo_file->sections.macinfo =
12635         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12636                                sections.macinfo_offset, sections.macinfo_size);
12637       dwo_file->sections.macro =
12638         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12639                                sections.macro_offset, sections.macro_size);
12640       dwo_file->sections.str_offsets =
12641         create_dwp_v2_section (dwarf2_per_objfile,
12642                                &dwp_file->sections.str_offsets,
12643                                sections.str_offsets_offset,
12644                                sections.str_offsets_size);
12645       /* The "str" section is global to the entire DWP file.  */
12646       dwo_file->sections.str = dwp_file->sections.str;
12647       /* The info or types section is assigned below to dwo_unit,
12648          there's no need to record it in dwo_file.
12649          Also, we can't simply record type sections in dwo_file because
12650          we record a pointer into the vector in dwo_unit.  As we collect more
12651          types we'll grow the vector and eventually have to reallocate space
12652          for it, invalidating all copies of pointers into the previous
12653          contents.  */
12654       *dwo_file_slot = dwo_file;
12655     }
12656   else
12657     {
12658       if (dwarf_read_debug)
12659         {
12660           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12661                               virtual_dwo_name.c_str ());
12662         }
12663       dwo_file = (struct dwo_file *) *dwo_file_slot;
12664     }
12665
12666   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12667   dwo_unit->dwo_file = dwo_file;
12668   dwo_unit->signature = signature;
12669   dwo_unit->section =
12670     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12671   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12672                                               is_debug_types
12673                                               ? &dwp_file->sections.types
12674                                               : &dwp_file->sections.info,
12675                                               sections.info_or_types_offset,
12676                                               sections.info_or_types_size);
12677   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12678
12679   return dwo_unit;
12680 }
12681
12682 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12683    Returns NULL if the signature isn't found.  */
12684
12685 static struct dwo_unit *
12686 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12687                         struct dwp_file *dwp_file, const char *comp_dir,
12688                         ULONGEST signature, int is_debug_types)
12689 {
12690   const struct dwp_hash_table *dwp_htab =
12691     is_debug_types ? dwp_file->tus : dwp_file->cus;
12692   bfd *dbfd = dwp_file->dbfd.get ();
12693   uint32_t mask = dwp_htab->nr_slots - 1;
12694   uint32_t hash = signature & mask;
12695   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12696   unsigned int i;
12697   void **slot;
12698   struct dwo_unit find_dwo_cu;
12699
12700   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12701   find_dwo_cu.signature = signature;
12702   slot = htab_find_slot (is_debug_types
12703                          ? dwp_file->loaded_tus
12704                          : dwp_file->loaded_cus,
12705                          &find_dwo_cu, INSERT);
12706
12707   if (*slot != NULL)
12708     return (struct dwo_unit *) *slot;
12709
12710   /* Use a for loop so that we don't loop forever on bad debug info.  */
12711   for (i = 0; i < dwp_htab->nr_slots; ++i)
12712     {
12713       ULONGEST signature_in_table;
12714
12715       signature_in_table =
12716         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12717       if (signature_in_table == signature)
12718         {
12719           uint32_t unit_index =
12720             read_4_bytes (dbfd,
12721                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12722
12723           if (dwp_file->version == 1)
12724             {
12725               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12726                                                  dwp_file, unit_index,
12727                                                  comp_dir, signature,
12728                                                  is_debug_types);
12729             }
12730           else
12731             {
12732               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12733                                                  dwp_file, unit_index,
12734                                                  comp_dir, signature,
12735                                                  is_debug_types);
12736             }
12737           return (struct dwo_unit *) *slot;
12738         }
12739       if (signature_in_table == 0)
12740         return NULL;
12741       hash = (hash + hash2) & mask;
12742     }
12743
12744   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12745            " [in module %s]"),
12746          dwp_file->name);
12747 }
12748
12749 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12750    Open the file specified by FILE_NAME and hand it off to BFD for
12751    preliminary analysis.  Return a newly initialized bfd *, which
12752    includes a canonicalized copy of FILE_NAME.
12753    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12754    SEARCH_CWD is true if the current directory is to be searched.
12755    It will be searched before debug-file-directory.
12756    If successful, the file is added to the bfd include table of the
12757    objfile's bfd (see gdb_bfd_record_inclusion).
12758    If unable to find/open the file, return NULL.
12759    NOTE: This function is derived from symfile_bfd_open.  */
12760
12761 static gdb_bfd_ref_ptr
12762 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12763                     const char *file_name, int is_dwp, int search_cwd)
12764 {
12765   int desc;
12766   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12767      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12768      to debug_file_directory.  */
12769   const char *search_path;
12770   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12771
12772   gdb::unique_xmalloc_ptr<char> search_path_holder;
12773   if (search_cwd)
12774     {
12775       if (*debug_file_directory != '\0')
12776         {
12777           search_path_holder.reset (concat (".", dirname_separator_string,
12778                                             debug_file_directory,
12779                                             (char *) NULL));
12780           search_path = search_path_holder.get ();
12781         }
12782       else
12783         search_path = ".";
12784     }
12785   else
12786     search_path = debug_file_directory;
12787
12788   openp_flags flags = OPF_RETURN_REALPATH;
12789   if (is_dwp)
12790     flags |= OPF_SEARCH_IN_PATH;
12791
12792   gdb::unique_xmalloc_ptr<char> absolute_name;
12793   desc = openp (search_path, flags, file_name,
12794                 O_RDONLY | O_BINARY, &absolute_name);
12795   if (desc < 0)
12796     return NULL;
12797
12798   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12799                                          gnutarget, desc));
12800   if (sym_bfd == NULL)
12801     return NULL;
12802   bfd_set_cacheable (sym_bfd.get (), 1);
12803
12804   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12805     return NULL;
12806
12807   /* Success.  Record the bfd as having been included by the objfile's bfd.
12808      This is important because things like demangled_names_hash lives in the
12809      objfile's per_bfd space and may have references to things like symbol
12810      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12811   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12812
12813   return sym_bfd;
12814 }
12815
12816 /* Try to open DWO file FILE_NAME.
12817    COMP_DIR is the DW_AT_comp_dir attribute.
12818    The result is the bfd handle of the file.
12819    If there is a problem finding or opening the file, return NULL.
12820    Upon success, the canonicalized path of the file is stored in the bfd,
12821    same as symfile_bfd_open.  */
12822
12823 static gdb_bfd_ref_ptr
12824 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12825                const char *file_name, const char *comp_dir)
12826 {
12827   if (IS_ABSOLUTE_PATH (file_name))
12828     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12829                                0 /*is_dwp*/, 0 /*search_cwd*/);
12830
12831   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12832
12833   if (comp_dir != NULL)
12834     {
12835       char *path_to_try = concat (comp_dir, SLASH_STRING,
12836                                   file_name, (char *) NULL);
12837
12838       /* NOTE: If comp_dir is a relative path, this will also try the
12839          search path, which seems useful.  */
12840       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12841                                                 path_to_try,
12842                                                 0 /*is_dwp*/,
12843                                                 1 /*search_cwd*/));
12844       xfree (path_to_try);
12845       if (abfd != NULL)
12846         return abfd;
12847     }
12848
12849   /* That didn't work, try debug-file-directory, which, despite its name,
12850      is a list of paths.  */
12851
12852   if (*debug_file_directory == '\0')
12853     return NULL;
12854
12855   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12856                              0 /*is_dwp*/, 1 /*search_cwd*/);
12857 }
12858
12859 /* This function is mapped across the sections and remembers the offset and
12860    size of each of the DWO debugging sections we are interested in.  */
12861
12862 static void
12863 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12864 {
12865   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12866   const struct dwop_section_names *names = &dwop_section_names;
12867
12868   if (section_is_p (sectp->name, &names->abbrev_dwo))
12869     {
12870       dwo_sections->abbrev.s.section = sectp;
12871       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12872     }
12873   else if (section_is_p (sectp->name, &names->info_dwo))
12874     {
12875       dwo_sections->info.s.section = sectp;
12876       dwo_sections->info.size = bfd_get_section_size (sectp);
12877     }
12878   else if (section_is_p (sectp->name, &names->line_dwo))
12879     {
12880       dwo_sections->line.s.section = sectp;
12881       dwo_sections->line.size = bfd_get_section_size (sectp);
12882     }
12883   else if (section_is_p (sectp->name, &names->loc_dwo))
12884     {
12885       dwo_sections->loc.s.section = sectp;
12886       dwo_sections->loc.size = bfd_get_section_size (sectp);
12887     }
12888   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12889     {
12890       dwo_sections->macinfo.s.section = sectp;
12891       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12892     }
12893   else if (section_is_p (sectp->name, &names->macro_dwo))
12894     {
12895       dwo_sections->macro.s.section = sectp;
12896       dwo_sections->macro.size = bfd_get_section_size (sectp);
12897     }
12898   else if (section_is_p (sectp->name, &names->str_dwo))
12899     {
12900       dwo_sections->str.s.section = sectp;
12901       dwo_sections->str.size = bfd_get_section_size (sectp);
12902     }
12903   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12904     {
12905       dwo_sections->str_offsets.s.section = sectp;
12906       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12907     }
12908   else if (section_is_p (sectp->name, &names->types_dwo))
12909     {
12910       struct dwarf2_section_info type_section;
12911
12912       memset (&type_section, 0, sizeof (type_section));
12913       type_section.s.section = sectp;
12914       type_section.size = bfd_get_section_size (sectp);
12915       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12916                      &type_section);
12917     }
12918 }
12919
12920 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12921    by PER_CU.  This is for the non-DWP case.
12922    The result is NULL if DWO_NAME can't be found.  */
12923
12924 static struct dwo_file *
12925 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12926                         const char *dwo_name, const char *comp_dir)
12927 {
12928   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12929   struct objfile *objfile = dwarf2_per_objfile->objfile;
12930
12931   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12932   if (dbfd == NULL)
12933     {
12934       if (dwarf_read_debug)
12935         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12936       return NULL;
12937     }
12938
12939   /* We use a unique pointer here, despite the obstack allocation,
12940      because a dwo_file needs some cleanup if it is abandoned.  */
12941   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12942                                         struct dwo_file));
12943   dwo_file->dwo_name = dwo_name;
12944   dwo_file->comp_dir = comp_dir;
12945   dwo_file->dbfd = dbfd.release ();
12946
12947   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12948                          &dwo_file->sections);
12949
12950   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12951                          dwo_file->cus);
12952
12953   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12954                                  dwo_file->sections.types, dwo_file->tus);
12955
12956   if (dwarf_read_debug)
12957     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12958
12959   return dwo_file.release ();
12960 }
12961
12962 /* This function is mapped across the sections and remembers the offset and
12963    size of each of the DWP debugging sections common to version 1 and 2 that
12964    we are interested in.  */
12965
12966 static void
12967 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12968                                    void *dwp_file_ptr)
12969 {
12970   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12971   const struct dwop_section_names *names = &dwop_section_names;
12972   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12973
12974   /* Record the ELF section number for later lookup: this is what the
12975      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12976   gdb_assert (elf_section_nr < dwp_file->num_sections);
12977   dwp_file->elf_sections[elf_section_nr] = sectp;
12978
12979   /* Look for specific sections that we need.  */
12980   if (section_is_p (sectp->name, &names->str_dwo))
12981     {
12982       dwp_file->sections.str.s.section = sectp;
12983       dwp_file->sections.str.size = bfd_get_section_size (sectp);
12984     }
12985   else if (section_is_p (sectp->name, &names->cu_index))
12986     {
12987       dwp_file->sections.cu_index.s.section = sectp;
12988       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
12989     }
12990   else if (section_is_p (sectp->name, &names->tu_index))
12991     {
12992       dwp_file->sections.tu_index.s.section = sectp;
12993       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
12994     }
12995 }
12996
12997 /* This function is mapped across the sections and remembers the offset and
12998    size of each of the DWP version 2 debugging sections that we are interested
12999    in.  This is split into a separate function because we don't know if we
13000    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
13001
13002 static void
13003 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
13004 {
13005   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
13006   const struct dwop_section_names *names = &dwop_section_names;
13007   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
13008
13009   /* Record the ELF section number for later lookup: this is what the
13010      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
13011   gdb_assert (elf_section_nr < dwp_file->num_sections);
13012   dwp_file->elf_sections[elf_section_nr] = sectp;
13013
13014   /* Look for specific sections that we need.  */
13015   if (section_is_p (sectp->name, &names->abbrev_dwo))
13016     {
13017       dwp_file->sections.abbrev.s.section = sectp;
13018       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
13019     }
13020   else if (section_is_p (sectp->name, &names->info_dwo))
13021     {
13022       dwp_file->sections.info.s.section = sectp;
13023       dwp_file->sections.info.size = bfd_get_section_size (sectp);
13024     }
13025   else if (section_is_p (sectp->name, &names->line_dwo))
13026     {
13027       dwp_file->sections.line.s.section = sectp;
13028       dwp_file->sections.line.size = bfd_get_section_size (sectp);
13029     }
13030   else if (section_is_p (sectp->name, &names->loc_dwo))
13031     {
13032       dwp_file->sections.loc.s.section = sectp;
13033       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
13034     }
13035   else if (section_is_p (sectp->name, &names->macinfo_dwo))
13036     {
13037       dwp_file->sections.macinfo.s.section = sectp;
13038       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
13039     }
13040   else if (section_is_p (sectp->name, &names->macro_dwo))
13041     {
13042       dwp_file->sections.macro.s.section = sectp;
13043       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
13044     }
13045   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
13046     {
13047       dwp_file->sections.str_offsets.s.section = sectp;
13048       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
13049     }
13050   else if (section_is_p (sectp->name, &names->types_dwo))
13051     {
13052       dwp_file->sections.types.s.section = sectp;
13053       dwp_file->sections.types.size = bfd_get_section_size (sectp);
13054     }
13055 }
13056
13057 /* Hash function for dwp_file loaded CUs/TUs.  */
13058
13059 static hashval_t
13060 hash_dwp_loaded_cutus (const void *item)
13061 {
13062   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
13063
13064   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
13065   return dwo_unit->signature;
13066 }
13067
13068 /* Equality function for dwp_file loaded CUs/TUs.  */
13069
13070 static int
13071 eq_dwp_loaded_cutus (const void *a, const void *b)
13072 {
13073   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13074   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13075
13076   return dua->signature == dub->signature;
13077 }
13078
13079 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13080
13081 static htab_t
13082 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13083 {
13084   return htab_create_alloc_ex (3,
13085                                hash_dwp_loaded_cutus,
13086                                eq_dwp_loaded_cutus,
13087                                NULL,
13088                                &objfile->objfile_obstack,
13089                                hashtab_obstack_allocate,
13090                                dummy_obstack_deallocate);
13091 }
13092
13093 /* Try to open DWP file FILE_NAME.
13094    The result is the bfd handle of the file.
13095    If there is a problem finding or opening the file, return NULL.
13096    Upon success, the canonicalized path of the file is stored in the bfd,
13097    same as symfile_bfd_open.  */
13098
13099 static gdb_bfd_ref_ptr
13100 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13101                const char *file_name)
13102 {
13103   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13104                                             1 /*is_dwp*/,
13105                                             1 /*search_cwd*/));
13106   if (abfd != NULL)
13107     return abfd;
13108
13109   /* Work around upstream bug 15652.
13110      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13111      [Whether that's a "bug" is debatable, but it is getting in our way.]
13112      We have no real idea where the dwp file is, because gdb's realpath-ing
13113      of the executable's path may have discarded the needed info.
13114      [IWBN if the dwp file name was recorded in the executable, akin to
13115      .gnu_debuglink, but that doesn't exist yet.]
13116      Strip the directory from FILE_NAME and search again.  */
13117   if (*debug_file_directory != '\0')
13118     {
13119       /* Don't implicitly search the current directory here.
13120          If the user wants to search "." to handle this case,
13121          it must be added to debug-file-directory.  */
13122       return try_open_dwop_file (dwarf2_per_objfile,
13123                                  lbasename (file_name), 1 /*is_dwp*/,
13124                                  0 /*search_cwd*/);
13125     }
13126
13127   return NULL;
13128 }
13129
13130 /* Initialize the use of the DWP file for the current objfile.
13131    By convention the name of the DWP file is ${objfile}.dwp.
13132    The result is NULL if it can't be found.  */
13133
13134 static std::unique_ptr<struct dwp_file>
13135 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13136 {
13137   struct objfile *objfile = dwarf2_per_objfile->objfile;
13138
13139   /* Try to find first .dwp for the binary file before any symbolic links
13140      resolving.  */
13141
13142   /* If the objfile is a debug file, find the name of the real binary
13143      file and get the name of dwp file from there.  */
13144   std::string dwp_name;
13145   if (objfile->separate_debug_objfile_backlink != NULL)
13146     {
13147       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13148       const char *backlink_basename = lbasename (backlink->original_name);
13149
13150       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13151     }
13152   else
13153     dwp_name = objfile->original_name;
13154
13155   dwp_name += ".dwp";
13156
13157   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13158   if (dbfd == NULL
13159       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13160     {
13161       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13162       dwp_name = objfile_name (objfile);
13163       dwp_name += ".dwp";
13164       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13165     }
13166
13167   if (dbfd == NULL)
13168     {
13169       if (dwarf_read_debug)
13170         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13171       return std::unique_ptr<dwp_file> ();
13172     }
13173
13174   const char *name = bfd_get_filename (dbfd.get ());
13175   std::unique_ptr<struct dwp_file> dwp_file
13176     (new struct dwp_file (name, std::move (dbfd)));
13177
13178   /* +1: section 0 is unused */
13179   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13180   dwp_file->elf_sections =
13181     OBSTACK_CALLOC (&objfile->objfile_obstack,
13182                     dwp_file->num_sections, asection *);
13183
13184   bfd_map_over_sections (dwp_file->dbfd.get (),
13185                          dwarf2_locate_common_dwp_sections,
13186                          dwp_file.get ());
13187
13188   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13189                                          0);
13190
13191   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13192                                          1);
13193
13194   /* The DWP file version is stored in the hash table.  Oh well.  */
13195   if (dwp_file->cus && dwp_file->tus
13196       && dwp_file->cus->version != dwp_file->tus->version)
13197     {
13198       /* Technically speaking, we should try to limp along, but this is
13199          pretty bizarre.  We use pulongest here because that's the established
13200          portability solution (e.g, we cannot use %u for uint32_t).  */
13201       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13202                " TU version %s [in DWP file %s]"),
13203              pulongest (dwp_file->cus->version),
13204              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13205     }
13206
13207   if (dwp_file->cus)
13208     dwp_file->version = dwp_file->cus->version;
13209   else if (dwp_file->tus)
13210     dwp_file->version = dwp_file->tus->version;
13211   else
13212     dwp_file->version = 2;
13213
13214   if (dwp_file->version == 2)
13215     bfd_map_over_sections (dwp_file->dbfd.get (),
13216                            dwarf2_locate_v2_dwp_sections,
13217                            dwp_file.get ());
13218
13219   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13220   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13221
13222   if (dwarf_read_debug)
13223     {
13224       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13225       fprintf_unfiltered (gdb_stdlog,
13226                           "    %s CUs, %s TUs\n",
13227                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13228                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13229     }
13230
13231   return dwp_file;
13232 }
13233
13234 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13235
13236 static struct dwp_file *
13237 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13238 {
13239   if (! dwarf2_per_objfile->dwp_checked)
13240     {
13241       dwarf2_per_objfile->dwp_file
13242         = open_and_init_dwp_file (dwarf2_per_objfile);
13243       dwarf2_per_objfile->dwp_checked = 1;
13244     }
13245   return dwarf2_per_objfile->dwp_file.get ();
13246 }
13247
13248 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13249    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13250    or in the DWP file for the objfile, referenced by THIS_UNIT.
13251    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13252    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13253
13254    This is called, for example, when wanting to read a variable with a
13255    complex location.  Therefore we don't want to do file i/o for every call.
13256    Therefore we don't want to look for a DWO file on every call.
13257    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13258    then we check if we've already seen DWO_NAME, and only THEN do we check
13259    for a DWO file.
13260
13261    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13262    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13263
13264 static struct dwo_unit *
13265 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13266                  const char *dwo_name, const char *comp_dir,
13267                  ULONGEST signature, int is_debug_types)
13268 {
13269   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13270   struct objfile *objfile = dwarf2_per_objfile->objfile;
13271   const char *kind = is_debug_types ? "TU" : "CU";
13272   void **dwo_file_slot;
13273   struct dwo_file *dwo_file;
13274   struct dwp_file *dwp_file;
13275
13276   /* First see if there's a DWP file.
13277      If we have a DWP file but didn't find the DWO inside it, don't
13278      look for the original DWO file.  It makes gdb behave differently
13279      depending on whether one is debugging in the build tree.  */
13280
13281   dwp_file = get_dwp_file (dwarf2_per_objfile);
13282   if (dwp_file != NULL)
13283     {
13284       const struct dwp_hash_table *dwp_htab =
13285         is_debug_types ? dwp_file->tus : dwp_file->cus;
13286
13287       if (dwp_htab != NULL)
13288         {
13289           struct dwo_unit *dwo_cutu =
13290             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13291                                     signature, is_debug_types);
13292
13293           if (dwo_cutu != NULL)
13294             {
13295               if (dwarf_read_debug)
13296                 {
13297                   fprintf_unfiltered (gdb_stdlog,
13298                                       "Virtual DWO %s %s found: @%s\n",
13299                                       kind, hex_string (signature),
13300                                       host_address_to_string (dwo_cutu));
13301                 }
13302               return dwo_cutu;
13303             }
13304         }
13305     }
13306   else
13307     {
13308       /* No DWP file, look for the DWO file.  */
13309
13310       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13311                                             dwo_name, comp_dir);
13312       if (*dwo_file_slot == NULL)
13313         {
13314           /* Read in the file and build a table of the CUs/TUs it contains.  */
13315           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13316         }
13317       /* NOTE: This will be NULL if unable to open the file.  */
13318       dwo_file = (struct dwo_file *) *dwo_file_slot;
13319
13320       if (dwo_file != NULL)
13321         {
13322           struct dwo_unit *dwo_cutu = NULL;
13323
13324           if (is_debug_types && dwo_file->tus)
13325             {
13326               struct dwo_unit find_dwo_cutu;
13327
13328               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13329               find_dwo_cutu.signature = signature;
13330               dwo_cutu
13331                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13332             }
13333           else if (!is_debug_types && dwo_file->cus)
13334             {
13335               struct dwo_unit find_dwo_cutu;
13336
13337               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13338               find_dwo_cutu.signature = signature;
13339               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13340                                                        &find_dwo_cutu);
13341             }
13342
13343           if (dwo_cutu != NULL)
13344             {
13345               if (dwarf_read_debug)
13346                 {
13347                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13348                                       kind, dwo_name, hex_string (signature),
13349                                       host_address_to_string (dwo_cutu));
13350                 }
13351               return dwo_cutu;
13352             }
13353         }
13354     }
13355
13356   /* We didn't find it.  This could mean a dwo_id mismatch, or
13357      someone deleted the DWO/DWP file, or the search path isn't set up
13358      correctly to find the file.  */
13359
13360   if (dwarf_read_debug)
13361     {
13362       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13363                           kind, dwo_name, hex_string (signature));
13364     }
13365
13366   /* This is a warning and not a complaint because it can be caused by
13367      pilot error (e.g., user accidentally deleting the DWO).  */
13368   {
13369     /* Print the name of the DWP file if we looked there, helps the user
13370        better diagnose the problem.  */
13371     std::string dwp_text;
13372
13373     if (dwp_file != NULL)
13374       dwp_text = string_printf (" [in DWP file %s]",
13375                                 lbasename (dwp_file->name));
13376
13377     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13378                " [in module %s]"),
13379              kind, dwo_name, hex_string (signature),
13380              dwp_text.c_str (),
13381              this_unit->is_debug_types ? "TU" : "CU",
13382              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13383   }
13384   return NULL;
13385 }
13386
13387 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13388    See lookup_dwo_cutu_unit for details.  */
13389
13390 static struct dwo_unit *
13391 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13392                       const char *dwo_name, const char *comp_dir,
13393                       ULONGEST signature)
13394 {
13395   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13396 }
13397
13398 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13399    See lookup_dwo_cutu_unit for details.  */
13400
13401 static struct dwo_unit *
13402 lookup_dwo_type_unit (struct signatured_type *this_tu,
13403                       const char *dwo_name, const char *comp_dir)
13404 {
13405   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13406 }
13407
13408 /* Traversal function for queue_and_load_all_dwo_tus.  */
13409
13410 static int
13411 queue_and_load_dwo_tu (void **slot, void *info)
13412 {
13413   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13414   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13415   ULONGEST signature = dwo_unit->signature;
13416   struct signatured_type *sig_type =
13417     lookup_dwo_signatured_type (per_cu->cu, signature);
13418
13419   if (sig_type != NULL)
13420     {
13421       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13422
13423       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13424          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13425          while processing PER_CU.  */
13426       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13427         load_full_type_unit (sig_cu);
13428       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13429     }
13430
13431   return 1;
13432 }
13433
13434 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13435    The DWO may have the only definition of the type, though it may not be
13436    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13437    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13438
13439 static void
13440 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13441 {
13442   struct dwo_unit *dwo_unit;
13443   struct dwo_file *dwo_file;
13444
13445   gdb_assert (!per_cu->is_debug_types);
13446   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13447   gdb_assert (per_cu->cu != NULL);
13448
13449   dwo_unit = per_cu->cu->dwo_unit;
13450   gdb_assert (dwo_unit != NULL);
13451
13452   dwo_file = dwo_unit->dwo_file;
13453   if (dwo_file->tus != NULL)
13454     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13455 }
13456
13457 /* Free all resources associated with DWO_FILE.
13458    Close the DWO file and munmap the sections.  */
13459
13460 static void
13461 free_dwo_file (struct dwo_file *dwo_file)
13462 {
13463   /* Note: dbfd is NULL for virtual DWO files.  */
13464   gdb_bfd_unref (dwo_file->dbfd);
13465
13466   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13467 }
13468
13469 /* Traversal function for free_dwo_files.  */
13470
13471 static int
13472 free_dwo_file_from_slot (void **slot, void *info)
13473 {
13474   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13475
13476   free_dwo_file (dwo_file);
13477
13478   return 1;
13479 }
13480
13481 /* Free all resources associated with DWO_FILES.  */
13482
13483 static void
13484 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13485 {
13486   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13487 }
13488 \f
13489 /* Read in various DIEs.  */
13490
13491 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13492    Inherit only the children of the DW_AT_abstract_origin DIE not being
13493    already referenced by DW_AT_abstract_origin from the children of the
13494    current DIE.  */
13495
13496 static void
13497 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13498 {
13499   struct die_info *child_die;
13500   sect_offset *offsetp;
13501   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13502   struct die_info *origin_die;
13503   /* Iterator of the ORIGIN_DIE children.  */
13504   struct die_info *origin_child_die;
13505   struct attribute *attr;
13506   struct dwarf2_cu *origin_cu;
13507   struct pending **origin_previous_list_in_scope;
13508
13509   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13510   if (!attr)
13511     return;
13512
13513   /* Note that following die references may follow to a die in a
13514      different cu.  */
13515
13516   origin_cu = cu;
13517   origin_die = follow_die_ref (die, attr, &origin_cu);
13518
13519   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13520      symbols in.  */
13521   origin_previous_list_in_scope = origin_cu->list_in_scope;
13522   origin_cu->list_in_scope = cu->list_in_scope;
13523
13524   if (die->tag != origin_die->tag
13525       && !(die->tag == DW_TAG_inlined_subroutine
13526            && origin_die->tag == DW_TAG_subprogram))
13527     complaint (_("DIE %s and its abstract origin %s have different tags"),
13528                sect_offset_str (die->sect_off),
13529                sect_offset_str (origin_die->sect_off));
13530
13531   std::vector<sect_offset> offsets;
13532
13533   for (child_die = die->child;
13534        child_die && child_die->tag;
13535        child_die = sibling_die (child_die))
13536     {
13537       struct die_info *child_origin_die;
13538       struct dwarf2_cu *child_origin_cu;
13539
13540       /* We are trying to process concrete instance entries:
13541          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13542          it's not relevant to our analysis here. i.e. detecting DIEs that are
13543          present in the abstract instance but not referenced in the concrete
13544          one.  */
13545       if (child_die->tag == DW_TAG_call_site
13546           || child_die->tag == DW_TAG_GNU_call_site)
13547         continue;
13548
13549       /* For each CHILD_DIE, find the corresponding child of
13550          ORIGIN_DIE.  If there is more than one layer of
13551          DW_AT_abstract_origin, follow them all; there shouldn't be,
13552          but GCC versions at least through 4.4 generate this (GCC PR
13553          40573).  */
13554       child_origin_die = child_die;
13555       child_origin_cu = cu;
13556       while (1)
13557         {
13558           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13559                               child_origin_cu);
13560           if (attr == NULL)
13561             break;
13562           child_origin_die = follow_die_ref (child_origin_die, attr,
13563                                              &child_origin_cu);
13564         }
13565
13566       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13567          counterpart may exist.  */
13568       if (child_origin_die != child_die)
13569         {
13570           if (child_die->tag != child_origin_die->tag
13571               && !(child_die->tag == DW_TAG_inlined_subroutine
13572                    && child_origin_die->tag == DW_TAG_subprogram))
13573             complaint (_("Child DIE %s and its abstract origin %s have "
13574                          "different tags"),
13575                        sect_offset_str (child_die->sect_off),
13576                        sect_offset_str (child_origin_die->sect_off));
13577           if (child_origin_die->parent != origin_die)
13578             complaint (_("Child DIE %s and its abstract origin %s have "
13579                          "different parents"),
13580                        sect_offset_str (child_die->sect_off),
13581                        sect_offset_str (child_origin_die->sect_off));
13582           else
13583             offsets.push_back (child_origin_die->sect_off);
13584         }
13585     }
13586   std::sort (offsets.begin (), offsets.end ());
13587   sect_offset *offsets_end = offsets.data () + offsets.size ();
13588   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13589     if (offsetp[-1] == *offsetp)
13590       complaint (_("Multiple children of DIE %s refer "
13591                    "to DIE %s as their abstract origin"),
13592                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13593
13594   offsetp = offsets.data ();
13595   origin_child_die = origin_die->child;
13596   while (origin_child_die && origin_child_die->tag)
13597     {
13598       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13599       while (offsetp < offsets_end
13600              && *offsetp < origin_child_die->sect_off)
13601         offsetp++;
13602       if (offsetp >= offsets_end
13603           || *offsetp > origin_child_die->sect_off)
13604         {
13605           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13606              Check whether we're already processing ORIGIN_CHILD_DIE.
13607              This can happen with mutually referenced abstract_origins.
13608              PR 16581.  */
13609           if (!origin_child_die->in_process)
13610             process_die (origin_child_die, origin_cu);
13611         }
13612       origin_child_die = sibling_die (origin_child_die);
13613     }
13614   origin_cu->list_in_scope = origin_previous_list_in_scope;
13615 }
13616
13617 static void
13618 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13619 {
13620   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13621   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13622   struct context_stack *newobj;
13623   CORE_ADDR lowpc;
13624   CORE_ADDR highpc;
13625   struct die_info *child_die;
13626   struct attribute *attr, *call_line, *call_file;
13627   const char *name;
13628   CORE_ADDR baseaddr;
13629   struct block *block;
13630   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13631   std::vector<struct symbol *> template_args;
13632   struct template_symbol *templ_func = NULL;
13633
13634   if (inlined_func)
13635     {
13636       /* If we do not have call site information, we can't show the
13637          caller of this inlined function.  That's too confusing, so
13638          only use the scope for local variables.  */
13639       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13640       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13641       if (call_line == NULL || call_file == NULL)
13642         {
13643           read_lexical_block_scope (die, cu);
13644           return;
13645         }
13646     }
13647
13648   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13649
13650   name = dwarf2_name (die, cu);
13651
13652   /* Ignore functions with missing or empty names.  These are actually
13653      illegal according to the DWARF standard.  */
13654   if (name == NULL)
13655     {
13656       complaint (_("missing name for subprogram DIE at %s"),
13657                  sect_offset_str (die->sect_off));
13658       return;
13659     }
13660
13661   /* Ignore functions with missing or invalid low and high pc attributes.  */
13662   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13663       <= PC_BOUNDS_INVALID)
13664     {
13665       attr = dwarf2_attr (die, DW_AT_external, cu);
13666       if (!attr || !DW_UNSND (attr))
13667         complaint (_("cannot get low and high bounds "
13668                      "for subprogram DIE at %s"),
13669                    sect_offset_str (die->sect_off));
13670       return;
13671     }
13672
13673   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13674   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13675
13676   /* If we have any template arguments, then we must allocate a
13677      different sort of symbol.  */
13678   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13679     {
13680       if (child_die->tag == DW_TAG_template_type_param
13681           || child_die->tag == DW_TAG_template_value_param)
13682         {
13683           templ_func = allocate_template_symbol (objfile);
13684           templ_func->subclass = SYMBOL_TEMPLATE;
13685           break;
13686         }
13687     }
13688
13689   newobj = cu->builder->push_context (0, lowpc);
13690   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13691                              (struct symbol *) templ_func);
13692
13693   /* If there is a location expression for DW_AT_frame_base, record
13694      it.  */
13695   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13696   if (attr)
13697     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13698
13699   /* If there is a location for the static link, record it.  */
13700   newobj->static_link = NULL;
13701   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13702   if (attr)
13703     {
13704       newobj->static_link
13705         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13706       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13707     }
13708
13709   cu->list_in_scope = cu->builder->get_local_symbols ();
13710
13711   if (die->child != NULL)
13712     {
13713       child_die = die->child;
13714       while (child_die && child_die->tag)
13715         {
13716           if (child_die->tag == DW_TAG_template_type_param
13717               || child_die->tag == DW_TAG_template_value_param)
13718             {
13719               struct symbol *arg = new_symbol (child_die, NULL, cu);
13720
13721               if (arg != NULL)
13722                 template_args.push_back (arg);
13723             }
13724           else
13725             process_die (child_die, cu);
13726           child_die = sibling_die (child_die);
13727         }
13728     }
13729
13730   inherit_abstract_dies (die, cu);
13731
13732   /* If we have a DW_AT_specification, we might need to import using
13733      directives from the context of the specification DIE.  See the
13734      comment in determine_prefix.  */
13735   if (cu->language == language_cplus
13736       && dwarf2_attr (die, DW_AT_specification, cu))
13737     {
13738       struct dwarf2_cu *spec_cu = cu;
13739       struct die_info *spec_die = die_specification (die, &spec_cu);
13740
13741       while (spec_die)
13742         {
13743           child_die = spec_die->child;
13744           while (child_die && child_die->tag)
13745             {
13746               if (child_die->tag == DW_TAG_imported_module)
13747                 process_die (child_die, spec_cu);
13748               child_die = sibling_die (child_die);
13749             }
13750
13751           /* In some cases, GCC generates specification DIEs that
13752              themselves contain DW_AT_specification attributes.  */
13753           spec_die = die_specification (spec_die, &spec_cu);
13754         }
13755     }
13756
13757   struct context_stack cstk = cu->builder->pop_context ();
13758   /* Make a block for the local symbols within.  */
13759   block = cu->builder->finish_block (cstk.name, cstk.old_blocks,
13760                                      cstk.static_link, lowpc, highpc);
13761
13762   /* For C++, set the block's scope.  */
13763   if ((cu->language == language_cplus
13764        || cu->language == language_fortran
13765        || cu->language == language_d
13766        || cu->language == language_rust)
13767       && cu->processing_has_namespace_info)
13768     block_set_scope (block, determine_prefix (die, cu),
13769                      &objfile->objfile_obstack);
13770
13771   /* If we have address ranges, record them.  */
13772   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13773
13774   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13775
13776   /* Attach template arguments to function.  */
13777   if (!template_args.empty ())
13778     {
13779       gdb_assert (templ_func != NULL);
13780
13781       templ_func->n_template_arguments = template_args.size ();
13782       templ_func->template_arguments
13783         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13784                      templ_func->n_template_arguments);
13785       memcpy (templ_func->template_arguments,
13786               template_args.data (),
13787               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13788
13789       /* Make sure that the symtab is set on the new symbols.  Even
13790          though they don't appear in this symtab directly, other parts
13791          of gdb assume that symbols do, and this is reasonably
13792          true.  */
13793       for (struct symbol *sym : template_args)
13794         symbol_set_symtab (sym, symbol_symtab (templ_func));
13795     }
13796
13797   /* In C++, we can have functions nested inside functions (e.g., when
13798      a function declares a class that has methods).  This means that
13799      when we finish processing a function scope, we may need to go
13800      back to building a containing block's symbol lists.  */
13801   *cu->builder->get_local_symbols () = cstk.locals;
13802   cu->builder->set_local_using_directives (cstk.local_using_directives);
13803
13804   /* If we've finished processing a top-level function, subsequent
13805      symbols go in the file symbol list.  */
13806   if (cu->builder->outermost_context_p ())
13807     cu->list_in_scope = cu->builder->get_file_symbols ();
13808 }
13809
13810 /* Process all the DIES contained within a lexical block scope.  Start
13811    a new scope, process the dies, and then close the scope.  */
13812
13813 static void
13814 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13815 {
13816   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13817   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13818   CORE_ADDR lowpc, highpc;
13819   struct die_info *child_die;
13820   CORE_ADDR baseaddr;
13821
13822   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13823
13824   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13825   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13826      as multiple lexical blocks?  Handling children in a sane way would
13827      be nasty.  Might be easier to properly extend generic blocks to
13828      describe ranges.  */
13829   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13830     {
13831     case PC_BOUNDS_NOT_PRESENT:
13832       /* DW_TAG_lexical_block has no attributes, process its children as if
13833          there was no wrapping by that DW_TAG_lexical_block.
13834          GCC does no longer produces such DWARF since GCC r224161.  */
13835       for (child_die = die->child;
13836            child_die != NULL && child_die->tag;
13837            child_die = sibling_die (child_die))
13838         process_die (child_die, cu);
13839       return;
13840     case PC_BOUNDS_INVALID:
13841       return;
13842     }
13843   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13844   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13845
13846   cu->builder->push_context (0, lowpc);
13847   if (die->child != NULL)
13848     {
13849       child_die = die->child;
13850       while (child_die && child_die->tag)
13851         {
13852           process_die (child_die, cu);
13853           child_die = sibling_die (child_die);
13854         }
13855     }
13856   inherit_abstract_dies (die, cu);
13857   struct context_stack cstk = cu->builder->pop_context ();
13858
13859   if (*cu->builder->get_local_symbols () != NULL
13860       || (*cu->builder->get_local_using_directives ()) != NULL)
13861     {
13862       struct block *block
13863         = cu->builder->finish_block (0, cstk.old_blocks, NULL,
13864                                      cstk.start_addr, highpc);
13865
13866       /* Note that recording ranges after traversing children, as we
13867          do here, means that recording a parent's ranges entails
13868          walking across all its children's ranges as they appear in
13869          the address map, which is quadratic behavior.
13870
13871          It would be nicer to record the parent's ranges before
13872          traversing its children, simply overriding whatever you find
13873          there.  But since we don't even decide whether to create a
13874          block until after we've traversed its children, that's hard
13875          to do.  */
13876       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13877     }
13878   *cu->builder->get_local_symbols () = cstk.locals;
13879   cu->builder->set_local_using_directives (cstk.local_using_directives);
13880 }
13881
13882 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13883
13884 static void
13885 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13886 {
13887   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13888   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13889   CORE_ADDR pc, baseaddr;
13890   struct attribute *attr;
13891   struct call_site *call_site, call_site_local;
13892   void **slot;
13893   int nparams;
13894   struct die_info *child_die;
13895
13896   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13897
13898   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13899   if (attr == NULL)
13900     {
13901       /* This was a pre-DWARF-5 GNU extension alias
13902          for DW_AT_call_return_pc.  */
13903       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13904     }
13905   if (!attr)
13906     {
13907       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13908                    "DIE %s [in module %s]"),
13909                  sect_offset_str (die->sect_off), objfile_name (objfile));
13910       return;
13911     }
13912   pc = attr_value_as_address (attr) + baseaddr;
13913   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13914
13915   if (cu->call_site_htab == NULL)
13916     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13917                                                NULL, &objfile->objfile_obstack,
13918                                                hashtab_obstack_allocate, NULL);
13919   call_site_local.pc = pc;
13920   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13921   if (*slot != NULL)
13922     {
13923       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13924                    "DIE %s [in module %s]"),
13925                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13926                  objfile_name (objfile));
13927       return;
13928     }
13929
13930   /* Count parameters at the caller.  */
13931
13932   nparams = 0;
13933   for (child_die = die->child; child_die && child_die->tag;
13934        child_die = sibling_die (child_die))
13935     {
13936       if (child_die->tag != DW_TAG_call_site_parameter
13937           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13938         {
13939           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13940                        "DW_TAG_call_site child DIE %s [in module %s]"),
13941                      child_die->tag, sect_offset_str (child_die->sect_off),
13942                      objfile_name (objfile));
13943           continue;
13944         }
13945
13946       nparams++;
13947     }
13948
13949   call_site
13950     = ((struct call_site *)
13951        obstack_alloc (&objfile->objfile_obstack,
13952                       sizeof (*call_site)
13953                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13954   *slot = call_site;
13955   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13956   call_site->pc = pc;
13957
13958   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13959       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13960     {
13961       struct die_info *func_die;
13962
13963       /* Skip also over DW_TAG_inlined_subroutine.  */
13964       for (func_die = die->parent;
13965            func_die && func_die->tag != DW_TAG_subprogram
13966            && func_die->tag != DW_TAG_subroutine_type;
13967            func_die = func_die->parent);
13968
13969       /* DW_AT_call_all_calls is a superset
13970          of DW_AT_call_all_tail_calls.  */
13971       if (func_die
13972           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13973           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13974           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13975           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13976         {
13977           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13978              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13979              both the initial caller containing the real return address PC and
13980              the final callee containing the current PC of a chain of tail
13981              calls do not need to have the tail call list complete.  But any
13982              function candidate for a virtual tail call frame searched via
13983              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13984              determined unambiguously.  */
13985         }
13986       else
13987         {
13988           struct type *func_type = NULL;
13989
13990           if (func_die)
13991             func_type = get_die_type (func_die, cu);
13992           if (func_type != NULL)
13993             {
13994               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13995
13996               /* Enlist this call site to the function.  */
13997               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13998               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13999             }
14000           else
14001             complaint (_("Cannot find function owning DW_TAG_call_site "
14002                          "DIE %s [in module %s]"),
14003                        sect_offset_str (die->sect_off), objfile_name (objfile));
14004         }
14005     }
14006
14007   attr = dwarf2_attr (die, DW_AT_call_target, cu);
14008   if (attr == NULL)
14009     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
14010   if (attr == NULL)
14011     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
14012   if (attr == NULL)
14013     {
14014       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
14015       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
14016     }
14017   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
14018   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
14019     /* Keep NULL DWARF_BLOCK.  */;
14020   else if (attr_form_is_block (attr))
14021     {
14022       struct dwarf2_locexpr_baton *dlbaton;
14023
14024       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14025       dlbaton->data = DW_BLOCK (attr)->data;
14026       dlbaton->size = DW_BLOCK (attr)->size;
14027       dlbaton->per_cu = cu->per_cu;
14028
14029       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
14030     }
14031   else if (attr_form_is_ref (attr))
14032     {
14033       struct dwarf2_cu *target_cu = cu;
14034       struct die_info *target_die;
14035
14036       target_die = follow_die_ref (die, attr, &target_cu);
14037       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
14038       if (die_is_declaration (target_die, target_cu))
14039         {
14040           const char *target_physname;
14041
14042           /* Prefer the mangled name; otherwise compute the demangled one.  */
14043           target_physname = dw2_linkage_name (target_die, target_cu);
14044           if (target_physname == NULL)
14045             target_physname = dwarf2_physname (NULL, target_die, target_cu);
14046           if (target_physname == NULL)
14047             complaint (_("DW_AT_call_target target DIE has invalid "
14048                          "physname, for referencing DIE %s [in module %s]"),
14049                        sect_offset_str (die->sect_off), objfile_name (objfile));
14050           else
14051             SET_FIELD_PHYSNAME (call_site->target, target_physname);
14052         }
14053       else
14054         {
14055           CORE_ADDR lowpc;
14056
14057           /* DW_AT_entry_pc should be preferred.  */
14058           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
14059               <= PC_BOUNDS_INVALID)
14060             complaint (_("DW_AT_call_target target DIE has invalid "
14061                          "low pc, for referencing DIE %s [in module %s]"),
14062                        sect_offset_str (die->sect_off), objfile_name (objfile));
14063           else
14064             {
14065               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
14066               SET_FIELD_PHYSADDR (call_site->target, lowpc);
14067             }
14068         }
14069     }
14070   else
14071     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
14072                  "block nor reference, for DIE %s [in module %s]"),
14073                sect_offset_str (die->sect_off), objfile_name (objfile));
14074
14075   call_site->per_cu = cu->per_cu;
14076
14077   for (child_die = die->child;
14078        child_die && child_die->tag;
14079        child_die = sibling_die (child_die))
14080     {
14081       struct call_site_parameter *parameter;
14082       struct attribute *loc, *origin;
14083
14084       if (child_die->tag != DW_TAG_call_site_parameter
14085           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14086         {
14087           /* Already printed the complaint above.  */
14088           continue;
14089         }
14090
14091       gdb_assert (call_site->parameter_count < nparams);
14092       parameter = &call_site->parameter[call_site->parameter_count];
14093
14094       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14095          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14096          register is contained in DW_AT_call_value.  */
14097
14098       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14099       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14100       if (origin == NULL)
14101         {
14102           /* This was a pre-DWARF-5 GNU extension alias
14103              for DW_AT_call_parameter.  */
14104           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14105         }
14106       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14107         {
14108           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14109
14110           sect_offset sect_off
14111             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14112           if (!offset_in_cu_p (&cu->header, sect_off))
14113             {
14114               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14115                  binding can be done only inside one CU.  Such referenced DIE
14116                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14117               complaint (_("DW_AT_call_parameter offset is not in CU for "
14118                            "DW_TAG_call_site child DIE %s [in module %s]"),
14119                          sect_offset_str (child_die->sect_off),
14120                          objfile_name (objfile));
14121               continue;
14122             }
14123           parameter->u.param_cu_off
14124             = (cu_offset) (sect_off - cu->header.sect_off);
14125         }
14126       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14127         {
14128           complaint (_("No DW_FORM_block* DW_AT_location for "
14129                        "DW_TAG_call_site child DIE %s [in module %s]"),
14130                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14131           continue;
14132         }
14133       else
14134         {
14135           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14136             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14137           if (parameter->u.dwarf_reg != -1)
14138             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14139           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14140                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14141                                              &parameter->u.fb_offset))
14142             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14143           else
14144             {
14145               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14146                            "for DW_FORM_block* DW_AT_location is supported for "
14147                            "DW_TAG_call_site child DIE %s "
14148                            "[in module %s]"),
14149                          sect_offset_str (child_die->sect_off),
14150                          objfile_name (objfile));
14151               continue;
14152             }
14153         }
14154
14155       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14156       if (attr == NULL)
14157         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14158       if (!attr_form_is_block (attr))
14159         {
14160           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14161                        "DW_TAG_call_site child DIE %s [in module %s]"),
14162                      sect_offset_str (child_die->sect_off),
14163                      objfile_name (objfile));
14164           continue;
14165         }
14166       parameter->value = DW_BLOCK (attr)->data;
14167       parameter->value_size = DW_BLOCK (attr)->size;
14168
14169       /* Parameters are not pre-cleared by memset above.  */
14170       parameter->data_value = NULL;
14171       parameter->data_value_size = 0;
14172       call_site->parameter_count++;
14173
14174       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14175       if (attr == NULL)
14176         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14177       if (attr)
14178         {
14179           if (!attr_form_is_block (attr))
14180             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14181                          "DW_TAG_call_site child DIE %s [in module %s]"),
14182                        sect_offset_str (child_die->sect_off),
14183                        objfile_name (objfile));
14184           else
14185             {
14186               parameter->data_value = DW_BLOCK (attr)->data;
14187               parameter->data_value_size = DW_BLOCK (attr)->size;
14188             }
14189         }
14190     }
14191 }
14192
14193 /* Helper function for read_variable.  If DIE represents a virtual
14194    table, then return the type of the concrete object that is
14195    associated with the virtual table.  Otherwise, return NULL.  */
14196
14197 static struct type *
14198 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14199 {
14200   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14201   if (attr == NULL)
14202     return NULL;
14203
14204   /* Find the type DIE.  */
14205   struct die_info *type_die = NULL;
14206   struct dwarf2_cu *type_cu = cu;
14207
14208   if (attr_form_is_ref (attr))
14209     type_die = follow_die_ref (die, attr, &type_cu);
14210   if (type_die == NULL)
14211     return NULL;
14212
14213   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14214     return NULL;
14215   return die_containing_type (type_die, type_cu);
14216 }
14217
14218 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14219
14220 static void
14221 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14222 {
14223   struct rust_vtable_symbol *storage = NULL;
14224
14225   if (cu->language == language_rust)
14226     {
14227       struct type *containing_type = rust_containing_type (die, cu);
14228
14229       if (containing_type != NULL)
14230         {
14231           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14232
14233           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14234                                     struct rust_vtable_symbol);
14235           initialize_objfile_symbol (storage);
14236           storage->concrete_type = containing_type;
14237           storage->subclass = SYMBOL_RUST_VTABLE;
14238         }
14239     }
14240
14241   new_symbol (die, NULL, cu, storage);
14242 }
14243
14244 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14245    reading .debug_rnglists.
14246    Callback's type should be:
14247     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14248    Return true if the attributes are present and valid, otherwise,
14249    return false.  */
14250
14251 template <typename Callback>
14252 static bool
14253 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14254                          Callback &&callback)
14255 {
14256   struct dwarf2_per_objfile *dwarf2_per_objfile
14257     = cu->per_cu->dwarf2_per_objfile;
14258   struct objfile *objfile = dwarf2_per_objfile->objfile;
14259   bfd *obfd = objfile->obfd;
14260   /* Base address selection entry.  */
14261   CORE_ADDR base;
14262   int found_base;
14263   const gdb_byte *buffer;
14264   CORE_ADDR baseaddr;
14265   bool overflow = false;
14266
14267   found_base = cu->base_known;
14268   base = cu->base_address;
14269
14270   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14271   if (offset >= dwarf2_per_objfile->rnglists.size)
14272     {
14273       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14274                  offset);
14275       return false;
14276     }
14277   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14278
14279   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14280
14281   while (1)
14282     {
14283       /* Initialize it due to a false compiler warning.  */
14284       CORE_ADDR range_beginning = 0, range_end = 0;
14285       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14286                                  + dwarf2_per_objfile->rnglists.size);
14287       unsigned int bytes_read;
14288
14289       if (buffer == buf_end)
14290         {
14291           overflow = true;
14292           break;
14293         }
14294       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14295       switch (rlet)
14296         {
14297         case DW_RLE_end_of_list:
14298           break;
14299         case DW_RLE_base_address:
14300           if (buffer + cu->header.addr_size > buf_end)
14301             {
14302               overflow = true;
14303               break;
14304             }
14305           base = read_address (obfd, buffer, cu, &bytes_read);
14306           found_base = 1;
14307           buffer += bytes_read;
14308           break;
14309         case DW_RLE_start_length:
14310           if (buffer + cu->header.addr_size > buf_end)
14311             {
14312               overflow = true;
14313               break;
14314             }
14315           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14316           buffer += bytes_read;
14317           range_end = (range_beginning
14318                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14319           buffer += bytes_read;
14320           if (buffer > buf_end)
14321             {
14322               overflow = true;
14323               break;
14324             }
14325           break;
14326         case DW_RLE_offset_pair:
14327           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14328           buffer += bytes_read;
14329           if (buffer > buf_end)
14330             {
14331               overflow = true;
14332               break;
14333             }
14334           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14335           buffer += bytes_read;
14336           if (buffer > buf_end)
14337             {
14338               overflow = true;
14339               break;
14340             }
14341           break;
14342         case DW_RLE_start_end:
14343           if (buffer + 2 * cu->header.addr_size > buf_end)
14344             {
14345               overflow = true;
14346               break;
14347             }
14348           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14349           buffer += bytes_read;
14350           range_end = read_address (obfd, buffer, cu, &bytes_read);
14351           buffer += bytes_read;
14352           break;
14353         default:
14354           complaint (_("Invalid .debug_rnglists data (no base address)"));
14355           return false;
14356         }
14357       if (rlet == DW_RLE_end_of_list || overflow)
14358         break;
14359       if (rlet == DW_RLE_base_address)
14360         continue;
14361
14362       if (!found_base)
14363         {
14364           /* We have no valid base address for the ranges
14365              data.  */
14366           complaint (_("Invalid .debug_rnglists data (no base address)"));
14367           return false;
14368         }
14369
14370       if (range_beginning > range_end)
14371         {
14372           /* Inverted range entries are invalid.  */
14373           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14374           return false;
14375         }
14376
14377       /* Empty range entries have no effect.  */
14378       if (range_beginning == range_end)
14379         continue;
14380
14381       range_beginning += base;
14382       range_end += base;
14383
14384       /* A not-uncommon case of bad debug info.
14385          Don't pollute the addrmap with bad data.  */
14386       if (range_beginning + baseaddr == 0
14387           && !dwarf2_per_objfile->has_section_at_zero)
14388         {
14389           complaint (_(".debug_rnglists entry has start address of zero"
14390                        " [in module %s]"), objfile_name (objfile));
14391           continue;
14392         }
14393
14394       callback (range_beginning, range_end);
14395     }
14396
14397   if (overflow)
14398     {
14399       complaint (_("Offset %d is not terminated "
14400                    "for DW_AT_ranges attribute"),
14401                  offset);
14402       return false;
14403     }
14404
14405   return true;
14406 }
14407
14408 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14409    Callback's type should be:
14410     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14411    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14412
14413 template <typename Callback>
14414 static int
14415 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14416                        Callback &&callback)
14417 {
14418   struct dwarf2_per_objfile *dwarf2_per_objfile
14419       = cu->per_cu->dwarf2_per_objfile;
14420   struct objfile *objfile = dwarf2_per_objfile->objfile;
14421   struct comp_unit_head *cu_header = &cu->header;
14422   bfd *obfd = objfile->obfd;
14423   unsigned int addr_size = cu_header->addr_size;
14424   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14425   /* Base address selection entry.  */
14426   CORE_ADDR base;
14427   int found_base;
14428   unsigned int dummy;
14429   const gdb_byte *buffer;
14430   CORE_ADDR baseaddr;
14431
14432   if (cu_header->version >= 5)
14433     return dwarf2_rnglists_process (offset, cu, callback);
14434
14435   found_base = cu->base_known;
14436   base = cu->base_address;
14437
14438   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14439   if (offset >= dwarf2_per_objfile->ranges.size)
14440     {
14441       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14442                  offset);
14443       return 0;
14444     }
14445   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14446
14447   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14448
14449   while (1)
14450     {
14451       CORE_ADDR range_beginning, range_end;
14452
14453       range_beginning = read_address (obfd, buffer, cu, &dummy);
14454       buffer += addr_size;
14455       range_end = read_address (obfd, buffer, cu, &dummy);
14456       buffer += addr_size;
14457       offset += 2 * addr_size;
14458
14459       /* An end of list marker is a pair of zero addresses.  */
14460       if (range_beginning == 0 && range_end == 0)
14461         /* Found the end of list entry.  */
14462         break;
14463
14464       /* Each base address selection entry is a pair of 2 values.
14465          The first is the largest possible address, the second is
14466          the base address.  Check for a base address here.  */
14467       if ((range_beginning & mask) == mask)
14468         {
14469           /* If we found the largest possible address, then we already
14470              have the base address in range_end.  */
14471           base = range_end;
14472           found_base = 1;
14473           continue;
14474         }
14475
14476       if (!found_base)
14477         {
14478           /* We have no valid base address for the ranges
14479              data.  */
14480           complaint (_("Invalid .debug_ranges data (no base address)"));
14481           return 0;
14482         }
14483
14484       if (range_beginning > range_end)
14485         {
14486           /* Inverted range entries are invalid.  */
14487           complaint (_("Invalid .debug_ranges data (inverted range)"));
14488           return 0;
14489         }
14490
14491       /* Empty range entries have no effect.  */
14492       if (range_beginning == range_end)
14493         continue;
14494
14495       range_beginning += base;
14496       range_end += base;
14497
14498       /* A not-uncommon case of bad debug info.
14499          Don't pollute the addrmap with bad data.  */
14500       if (range_beginning + baseaddr == 0
14501           && !dwarf2_per_objfile->has_section_at_zero)
14502         {
14503           complaint (_(".debug_ranges entry has start address of zero"
14504                        " [in module %s]"), objfile_name (objfile));
14505           continue;
14506         }
14507
14508       callback (range_beginning, range_end);
14509     }
14510
14511   return 1;
14512 }
14513
14514 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14515    Return 1 if the attributes are present and valid, otherwise, return 0.
14516    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14517
14518 static int
14519 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14520                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14521                     struct partial_symtab *ranges_pst)
14522 {
14523   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14524   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14525   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14526                                        SECT_OFF_TEXT (objfile));
14527   int low_set = 0;
14528   CORE_ADDR low = 0;
14529   CORE_ADDR high = 0;
14530   int retval;
14531
14532   retval = dwarf2_ranges_process (offset, cu,
14533     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14534     {
14535       if (ranges_pst != NULL)
14536         {
14537           CORE_ADDR lowpc;
14538           CORE_ADDR highpc;
14539
14540           lowpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14541                                                range_beginning + baseaddr)
14542                    - baseaddr);
14543           highpc = (gdbarch_adjust_dwarf2_addr (gdbarch,
14544                                                 range_end + baseaddr)
14545                     - baseaddr);
14546           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14547                              ranges_pst);
14548         }
14549
14550       /* FIXME: This is recording everything as a low-high
14551          segment of consecutive addresses.  We should have a
14552          data structure for discontiguous block ranges
14553          instead.  */
14554       if (! low_set)
14555         {
14556           low = range_beginning;
14557           high = range_end;
14558           low_set = 1;
14559         }
14560       else
14561         {
14562           if (range_beginning < low)
14563             low = range_beginning;
14564           if (range_end > high)
14565             high = range_end;
14566         }
14567     });
14568   if (!retval)
14569     return 0;
14570
14571   if (! low_set)
14572     /* If the first entry is an end-of-list marker, the range
14573        describes an empty scope, i.e. no instructions.  */
14574     return 0;
14575
14576   if (low_return)
14577     *low_return = low;
14578   if (high_return)
14579     *high_return = high;
14580   return 1;
14581 }
14582
14583 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14584    definition for the return value.  *LOWPC and *HIGHPC are set iff
14585    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14586
14587 static enum pc_bounds_kind
14588 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14589                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14590                       struct partial_symtab *pst)
14591 {
14592   struct dwarf2_per_objfile *dwarf2_per_objfile
14593     = cu->per_cu->dwarf2_per_objfile;
14594   struct attribute *attr;
14595   struct attribute *attr_high;
14596   CORE_ADDR low = 0;
14597   CORE_ADDR high = 0;
14598   enum pc_bounds_kind ret;
14599
14600   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14601   if (attr_high)
14602     {
14603       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14604       if (attr)
14605         {
14606           low = attr_value_as_address (attr);
14607           high = attr_value_as_address (attr_high);
14608           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14609             high += low;
14610         }
14611       else
14612         /* Found high w/o low attribute.  */
14613         return PC_BOUNDS_INVALID;
14614
14615       /* Found consecutive range of addresses.  */
14616       ret = PC_BOUNDS_HIGH_LOW;
14617     }
14618   else
14619     {
14620       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14621       if (attr != NULL)
14622         {
14623           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14624              We take advantage of the fact that DW_AT_ranges does not appear
14625              in DW_TAG_compile_unit of DWO files.  */
14626           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14627           unsigned int ranges_offset = (DW_UNSND (attr)
14628                                         + (need_ranges_base
14629                                            ? cu->ranges_base
14630                                            : 0));
14631
14632           /* Value of the DW_AT_ranges attribute is the offset in the
14633              .debug_ranges section.  */
14634           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14635             return PC_BOUNDS_INVALID;
14636           /* Found discontinuous range of addresses.  */
14637           ret = PC_BOUNDS_RANGES;
14638         }
14639       else
14640         return PC_BOUNDS_NOT_PRESENT;
14641     }
14642
14643   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14644   if (high <= low)
14645     return PC_BOUNDS_INVALID;
14646
14647   /* When using the GNU linker, .gnu.linkonce. sections are used to
14648      eliminate duplicate copies of functions and vtables and such.
14649      The linker will arbitrarily choose one and discard the others.
14650      The AT_*_pc values for such functions refer to local labels in
14651      these sections.  If the section from that file was discarded, the
14652      labels are not in the output, so the relocs get a value of 0.
14653      If this is a discarded function, mark the pc bounds as invalid,
14654      so that GDB will ignore it.  */
14655   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14656     return PC_BOUNDS_INVALID;
14657
14658   *lowpc = low;
14659   if (highpc)
14660     *highpc = high;
14661   return ret;
14662 }
14663
14664 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14665    its low and high PC addresses.  Do nothing if these addresses could not
14666    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14667    and HIGHPC to the high address if greater than HIGHPC.  */
14668
14669 static void
14670 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14671                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14672                                  struct dwarf2_cu *cu)
14673 {
14674   CORE_ADDR low, high;
14675   struct die_info *child = die->child;
14676
14677   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14678     {
14679       *lowpc = std::min (*lowpc, low);
14680       *highpc = std::max (*highpc, high);
14681     }
14682
14683   /* If the language does not allow nested subprograms (either inside
14684      subprograms or lexical blocks), we're done.  */
14685   if (cu->language != language_ada)
14686     return;
14687
14688   /* Check all the children of the given DIE.  If it contains nested
14689      subprograms, then check their pc bounds.  Likewise, we need to
14690      check lexical blocks as well, as they may also contain subprogram
14691      definitions.  */
14692   while (child && child->tag)
14693     {
14694       if (child->tag == DW_TAG_subprogram
14695           || child->tag == DW_TAG_lexical_block)
14696         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14697       child = sibling_die (child);
14698     }
14699 }
14700
14701 /* Get the low and high pc's represented by the scope DIE, and store
14702    them in *LOWPC and *HIGHPC.  If the correct values can't be
14703    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14704
14705 static void
14706 get_scope_pc_bounds (struct die_info *die,
14707                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14708                      struct dwarf2_cu *cu)
14709 {
14710   CORE_ADDR best_low = (CORE_ADDR) -1;
14711   CORE_ADDR best_high = (CORE_ADDR) 0;
14712   CORE_ADDR current_low, current_high;
14713
14714   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14715       >= PC_BOUNDS_RANGES)
14716     {
14717       best_low = current_low;
14718       best_high = current_high;
14719     }
14720   else
14721     {
14722       struct die_info *child = die->child;
14723
14724       while (child && child->tag)
14725         {
14726           switch (child->tag) {
14727           case DW_TAG_subprogram:
14728             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14729             break;
14730           case DW_TAG_namespace:
14731           case DW_TAG_module:
14732             /* FIXME: carlton/2004-01-16: Should we do this for
14733                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14734                that current GCC's always emit the DIEs corresponding
14735                to definitions of methods of classes as children of a
14736                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14737                the DIEs giving the declarations, which could be
14738                anywhere).  But I don't see any reason why the
14739                standards says that they have to be there.  */
14740             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14741
14742             if (current_low != ((CORE_ADDR) -1))
14743               {
14744                 best_low = std::min (best_low, current_low);
14745                 best_high = std::max (best_high, current_high);
14746               }
14747             break;
14748           default:
14749             /* Ignore.  */
14750             break;
14751           }
14752
14753           child = sibling_die (child);
14754         }
14755     }
14756
14757   *lowpc = best_low;
14758   *highpc = best_high;
14759 }
14760
14761 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14762    in DIE.  */
14763
14764 static void
14765 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14766                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14767 {
14768   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14769   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14770   struct attribute *attr;
14771   struct attribute *attr_high;
14772
14773   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14774   if (attr_high)
14775     {
14776       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14777       if (attr)
14778         {
14779           CORE_ADDR low = attr_value_as_address (attr);
14780           CORE_ADDR high = attr_value_as_address (attr_high);
14781
14782           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14783             high += low;
14784
14785           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14786           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14787           cu->builder->record_block_range (block, low, high - 1);
14788         }
14789     }
14790
14791   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14792   if (attr)
14793     {
14794       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14795          We take advantage of the fact that DW_AT_ranges does not appear
14796          in DW_TAG_compile_unit of DWO files.  */
14797       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14798
14799       /* The value of the DW_AT_ranges attribute is the offset of the
14800          address range list in the .debug_ranges section.  */
14801       unsigned long offset = (DW_UNSND (attr)
14802                               + (need_ranges_base ? cu->ranges_base : 0));
14803
14804       dwarf2_ranges_process (offset, cu,
14805         [&] (CORE_ADDR start, CORE_ADDR end)
14806         {
14807           start += baseaddr;
14808           end += baseaddr;
14809           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14810           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14811           cu->builder->record_block_range (block, start, end - 1);
14812         });
14813     }
14814 }
14815
14816 /* Check whether the producer field indicates either of GCC < 4.6, or the
14817    Intel C/C++ compiler, and cache the result in CU.  */
14818
14819 static void
14820 check_producer (struct dwarf2_cu *cu)
14821 {
14822   int major, minor;
14823
14824   if (cu->producer == NULL)
14825     {
14826       /* For unknown compilers expect their behavior is DWARF version
14827          compliant.
14828
14829          GCC started to support .debug_types sections by -gdwarf-4 since
14830          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14831          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14832          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14833          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14834     }
14835   else if (producer_is_gcc (cu->producer, &major, &minor))
14836     {
14837       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14838       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14839     }
14840   else if (producer_is_icc (cu->producer, &major, &minor))
14841     cu->producer_is_icc_lt_14 = major < 14;
14842   else
14843     {
14844       /* For other non-GCC compilers, expect their behavior is DWARF version
14845          compliant.  */
14846     }
14847
14848   cu->checked_producer = 1;
14849 }
14850
14851 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14852    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14853    during 4.6.0 experimental.  */
14854
14855 static int
14856 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14857 {
14858   if (!cu->checked_producer)
14859     check_producer (cu);
14860
14861   return cu->producer_is_gxx_lt_4_6;
14862 }
14863
14864 /* Return the default accessibility type if it is not overriden by
14865    DW_AT_accessibility.  */
14866
14867 static enum dwarf_access_attribute
14868 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14869 {
14870   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14871     {
14872       /* The default DWARF 2 accessibility for members is public, the default
14873          accessibility for inheritance is private.  */
14874
14875       if (die->tag != DW_TAG_inheritance)
14876         return DW_ACCESS_public;
14877       else
14878         return DW_ACCESS_private;
14879     }
14880   else
14881     {
14882       /* DWARF 3+ defines the default accessibility a different way.  The same
14883          rules apply now for DW_TAG_inheritance as for the members and it only
14884          depends on the container kind.  */
14885
14886       if (die->parent->tag == DW_TAG_class_type)
14887         return DW_ACCESS_private;
14888       else
14889         return DW_ACCESS_public;
14890     }
14891 }
14892
14893 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14894    offset.  If the attribute was not found return 0, otherwise return
14895    1.  If it was found but could not properly be handled, set *OFFSET
14896    to 0.  */
14897
14898 static int
14899 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14900                              LONGEST *offset)
14901 {
14902   struct attribute *attr;
14903
14904   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14905   if (attr != NULL)
14906     {
14907       *offset = 0;
14908
14909       /* Note that we do not check for a section offset first here.
14910          This is because DW_AT_data_member_location is new in DWARF 4,
14911          so if we see it, we can assume that a constant form is really
14912          a constant and not a section offset.  */
14913       if (attr_form_is_constant (attr))
14914         *offset = dwarf2_get_attr_constant_value (attr, 0);
14915       else if (attr_form_is_section_offset (attr))
14916         dwarf2_complex_location_expr_complaint ();
14917       else if (attr_form_is_block (attr))
14918         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14919       else
14920         dwarf2_complex_location_expr_complaint ();
14921
14922       return 1;
14923     }
14924
14925   return 0;
14926 }
14927
14928 /* Add an aggregate field to the field list.  */
14929
14930 static void
14931 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14932                   struct dwarf2_cu *cu)
14933 {
14934   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14935   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14936   struct nextfield *new_field;
14937   struct attribute *attr;
14938   struct field *fp;
14939   const char *fieldname = "";
14940
14941   if (die->tag == DW_TAG_inheritance)
14942     {
14943       fip->baseclasses.emplace_back ();
14944       new_field = &fip->baseclasses.back ();
14945     }
14946   else
14947     {
14948       fip->fields.emplace_back ();
14949       new_field = &fip->fields.back ();
14950     }
14951
14952   fip->nfields++;
14953
14954   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14955   if (attr)
14956     new_field->accessibility = DW_UNSND (attr);
14957   else
14958     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14959   if (new_field->accessibility != DW_ACCESS_public)
14960     fip->non_public_fields = 1;
14961
14962   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14963   if (attr)
14964     new_field->virtuality = DW_UNSND (attr);
14965   else
14966     new_field->virtuality = DW_VIRTUALITY_none;
14967
14968   fp = &new_field->field;
14969
14970   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14971     {
14972       LONGEST offset;
14973
14974       /* Data member other than a C++ static data member.  */
14975
14976       /* Get type of field.  */
14977       fp->type = die_type (die, cu);
14978
14979       SET_FIELD_BITPOS (*fp, 0);
14980
14981       /* Get bit size of field (zero if none).  */
14982       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14983       if (attr)
14984         {
14985           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14986         }
14987       else
14988         {
14989           FIELD_BITSIZE (*fp) = 0;
14990         }
14991
14992       /* Get bit offset of field.  */
14993       if (handle_data_member_location (die, cu, &offset))
14994         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14995       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14996       if (attr)
14997         {
14998           if (gdbarch_bits_big_endian (gdbarch))
14999             {
15000               /* For big endian bits, the DW_AT_bit_offset gives the
15001                  additional bit offset from the MSB of the containing
15002                  anonymous object to the MSB of the field.  We don't
15003                  have to do anything special since we don't need to
15004                  know the size of the anonymous object.  */
15005               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
15006             }
15007           else
15008             {
15009               /* For little endian bits, compute the bit offset to the
15010                  MSB of the anonymous object, subtract off the number of
15011                  bits from the MSB of the field to the MSB of the
15012                  object, and then subtract off the number of bits of
15013                  the field itself.  The result is the bit offset of
15014                  the LSB of the field.  */
15015               int anonymous_size;
15016               int bit_offset = DW_UNSND (attr);
15017
15018               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15019               if (attr)
15020                 {
15021                   /* The size of the anonymous object containing
15022                      the bit field is explicit, so use the
15023                      indicated size (in bytes).  */
15024                   anonymous_size = DW_UNSND (attr);
15025                 }
15026               else
15027                 {
15028                   /* The size of the anonymous object containing
15029                      the bit field must be inferred from the type
15030                      attribute of the data member containing the
15031                      bit field.  */
15032                   anonymous_size = TYPE_LENGTH (fp->type);
15033                 }
15034               SET_FIELD_BITPOS (*fp,
15035                                 (FIELD_BITPOS (*fp)
15036                                  + anonymous_size * bits_per_byte
15037                                  - bit_offset - FIELD_BITSIZE (*fp)));
15038             }
15039         }
15040       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
15041       if (attr != NULL)
15042         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
15043                                 + dwarf2_get_attr_constant_value (attr, 0)));
15044
15045       /* Get name of field.  */
15046       fieldname = dwarf2_name (die, cu);
15047       if (fieldname == NULL)
15048         fieldname = "";
15049
15050       /* The name is already allocated along with this objfile, so we don't
15051          need to duplicate it for the type.  */
15052       fp->name = fieldname;
15053
15054       /* Change accessibility for artificial fields (e.g. virtual table
15055          pointer or virtual base class pointer) to private.  */
15056       if (dwarf2_attr (die, DW_AT_artificial, cu))
15057         {
15058           FIELD_ARTIFICIAL (*fp) = 1;
15059           new_field->accessibility = DW_ACCESS_private;
15060           fip->non_public_fields = 1;
15061         }
15062     }
15063   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
15064     {
15065       /* C++ static member.  */
15066
15067       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
15068          is a declaration, but all versions of G++ as of this writing
15069          (so through at least 3.2.1) incorrectly generate
15070          DW_TAG_variable tags.  */
15071
15072       const char *physname;
15073
15074       /* Get name of field.  */
15075       fieldname = dwarf2_name (die, cu);
15076       if (fieldname == NULL)
15077         return;
15078
15079       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15080       if (attr
15081           /* Only create a symbol if this is an external value.
15082              new_symbol checks this and puts the value in the global symbol
15083              table, which we want.  If it is not external, new_symbol
15084              will try to put the value in cu->list_in_scope which is wrong.  */
15085           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15086         {
15087           /* A static const member, not much different than an enum as far as
15088              we're concerned, except that we can support more types.  */
15089           new_symbol (die, NULL, cu);
15090         }
15091
15092       /* Get physical name.  */
15093       physname = dwarf2_physname (fieldname, die, cu);
15094
15095       /* The name is already allocated along with this objfile, so we don't
15096          need to duplicate it for the type.  */
15097       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15098       FIELD_TYPE (*fp) = die_type (die, cu);
15099       FIELD_NAME (*fp) = fieldname;
15100     }
15101   else if (die->tag == DW_TAG_inheritance)
15102     {
15103       LONGEST offset;
15104
15105       /* C++ base class field.  */
15106       if (handle_data_member_location (die, cu, &offset))
15107         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15108       FIELD_BITSIZE (*fp) = 0;
15109       FIELD_TYPE (*fp) = die_type (die, cu);
15110       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15111     }
15112   else if (die->tag == DW_TAG_variant_part)
15113     {
15114       /* process_structure_scope will treat this DIE as a union.  */
15115       process_structure_scope (die, cu);
15116
15117       /* The variant part is relative to the start of the enclosing
15118          structure.  */
15119       SET_FIELD_BITPOS (*fp, 0);
15120       fp->type = get_die_type (die, cu);
15121       fp->artificial = 1;
15122       fp->name = "<<variant>>";
15123     }
15124   else
15125     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15126 }
15127
15128 /* Can the type given by DIE define another type?  */
15129
15130 static bool
15131 type_can_define_types (const struct die_info *die)
15132 {
15133   switch (die->tag)
15134     {
15135     case DW_TAG_typedef:
15136     case DW_TAG_class_type:
15137     case DW_TAG_structure_type:
15138     case DW_TAG_union_type:
15139     case DW_TAG_enumeration_type:
15140       return true;
15141
15142     default:
15143       return false;
15144     }
15145 }
15146
15147 /* Add a type definition defined in the scope of the FIP's class.  */
15148
15149 static void
15150 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15151                       struct dwarf2_cu *cu)
15152 {
15153   struct decl_field fp;
15154   memset (&fp, 0, sizeof (fp));
15155
15156   gdb_assert (type_can_define_types (die));
15157
15158   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15159   fp.name = dwarf2_name (die, cu);
15160   fp.type = read_type_die (die, cu);
15161
15162   /* Save accessibility.  */
15163   enum dwarf_access_attribute accessibility;
15164   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15165   if (attr != NULL)
15166     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15167   else
15168     accessibility = dwarf2_default_access_attribute (die, cu);
15169   switch (accessibility)
15170     {
15171     case DW_ACCESS_public:
15172       /* The assumed value if neither private nor protected.  */
15173       break;
15174     case DW_ACCESS_private:
15175       fp.is_private = 1;
15176       break;
15177     case DW_ACCESS_protected:
15178       fp.is_protected = 1;
15179       break;
15180     default:
15181       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15182     }
15183
15184   if (die->tag == DW_TAG_typedef)
15185     fip->typedef_field_list.push_back (fp);
15186   else
15187     fip->nested_types_list.push_back (fp);
15188 }
15189
15190 /* Create the vector of fields, and attach it to the type.  */
15191
15192 static void
15193 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15194                               struct dwarf2_cu *cu)
15195 {
15196   int nfields = fip->nfields;
15197
15198   /* Record the field count, allocate space for the array of fields,
15199      and create blank accessibility bitfields if necessary.  */
15200   TYPE_NFIELDS (type) = nfields;
15201   TYPE_FIELDS (type) = (struct field *)
15202     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15203
15204   if (fip->non_public_fields && cu->language != language_ada)
15205     {
15206       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15207
15208       TYPE_FIELD_PRIVATE_BITS (type) =
15209         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15210       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15211
15212       TYPE_FIELD_PROTECTED_BITS (type) =
15213         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15214       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15215
15216       TYPE_FIELD_IGNORE_BITS (type) =
15217         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15218       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15219     }
15220
15221   /* If the type has baseclasses, allocate and clear a bit vector for
15222      TYPE_FIELD_VIRTUAL_BITS.  */
15223   if (!fip->baseclasses.empty () && cu->language != language_ada)
15224     {
15225       int num_bytes = B_BYTES (fip->baseclasses.size ());
15226       unsigned char *pointer;
15227
15228       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15229       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15230       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15231       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15232       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15233     }
15234
15235   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15236     {
15237       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15238
15239       for (int index = 0; index < nfields; ++index)
15240         {
15241           struct nextfield &field = fip->fields[index];
15242
15243           if (field.variant.is_discriminant)
15244             di->discriminant_index = index;
15245           else if (field.variant.default_branch)
15246             di->default_index = index;
15247           else
15248             di->discriminants[index] = field.variant.discriminant_value;
15249         }
15250     }
15251
15252   /* Copy the saved-up fields into the field vector.  */
15253   for (int i = 0; i < nfields; ++i)
15254     {
15255       struct nextfield &field
15256         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15257            : fip->fields[i - fip->baseclasses.size ()]);
15258
15259       TYPE_FIELD (type, i) = field.field;
15260       switch (field.accessibility)
15261         {
15262         case DW_ACCESS_private:
15263           if (cu->language != language_ada)
15264             SET_TYPE_FIELD_PRIVATE (type, i);
15265           break;
15266
15267         case DW_ACCESS_protected:
15268           if (cu->language != language_ada)
15269             SET_TYPE_FIELD_PROTECTED (type, i);
15270           break;
15271
15272         case DW_ACCESS_public:
15273           break;
15274
15275         default:
15276           /* Unknown accessibility.  Complain and treat it as public.  */
15277           {
15278             complaint (_("unsupported accessibility %d"),
15279                        field.accessibility);
15280           }
15281           break;
15282         }
15283       if (i < fip->baseclasses.size ())
15284         {
15285           switch (field.virtuality)
15286             {
15287             case DW_VIRTUALITY_virtual:
15288             case DW_VIRTUALITY_pure_virtual:
15289               if (cu->language == language_ada)
15290                 error (_("unexpected virtuality in component of Ada type"));
15291               SET_TYPE_FIELD_VIRTUAL (type, i);
15292               break;
15293             }
15294         }
15295     }
15296 }
15297
15298 /* Return true if this member function is a constructor, false
15299    otherwise.  */
15300
15301 static int
15302 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15303 {
15304   const char *fieldname;
15305   const char *type_name;
15306   int len;
15307
15308   if (die->parent == NULL)
15309     return 0;
15310
15311   if (die->parent->tag != DW_TAG_structure_type
15312       && die->parent->tag != DW_TAG_union_type
15313       && die->parent->tag != DW_TAG_class_type)
15314     return 0;
15315
15316   fieldname = dwarf2_name (die, cu);
15317   type_name = dwarf2_name (die->parent, cu);
15318   if (fieldname == NULL || type_name == NULL)
15319     return 0;
15320
15321   len = strlen (fieldname);
15322   return (strncmp (fieldname, type_name, len) == 0
15323           && (type_name[len] == '\0' || type_name[len] == '<'));
15324 }
15325
15326 /* Add a member function to the proper fieldlist.  */
15327
15328 static void
15329 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15330                       struct type *type, struct dwarf2_cu *cu)
15331 {
15332   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15333   struct attribute *attr;
15334   int i;
15335   struct fnfieldlist *flp = nullptr;
15336   struct fn_field *fnp;
15337   const char *fieldname;
15338   struct type *this_type;
15339   enum dwarf_access_attribute accessibility;
15340
15341   if (cu->language == language_ada)
15342     error (_("unexpected member function in Ada type"));
15343
15344   /* Get name of member function.  */
15345   fieldname = dwarf2_name (die, cu);
15346   if (fieldname == NULL)
15347     return;
15348
15349   /* Look up member function name in fieldlist.  */
15350   for (i = 0; i < fip->fnfieldlists.size (); i++)
15351     {
15352       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15353         {
15354           flp = &fip->fnfieldlists[i];
15355           break;
15356         }
15357     }
15358
15359   /* Create a new fnfieldlist if necessary.  */
15360   if (flp == nullptr)
15361     {
15362       fip->fnfieldlists.emplace_back ();
15363       flp = &fip->fnfieldlists.back ();
15364       flp->name = fieldname;
15365       i = fip->fnfieldlists.size () - 1;
15366     }
15367
15368   /* Create a new member function field and add it to the vector of
15369      fnfieldlists.  */
15370   flp->fnfields.emplace_back ();
15371   fnp = &flp->fnfields.back ();
15372
15373   /* Delay processing of the physname until later.  */
15374   if (cu->language == language_cplus)
15375     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15376                         die, cu);
15377   else
15378     {
15379       const char *physname = dwarf2_physname (fieldname, die, cu);
15380       fnp->physname = physname ? physname : "";
15381     }
15382
15383   fnp->type = alloc_type (objfile);
15384   this_type = read_type_die (die, cu);
15385   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15386     {
15387       int nparams = TYPE_NFIELDS (this_type);
15388
15389       /* TYPE is the domain of this method, and THIS_TYPE is the type
15390            of the method itself (TYPE_CODE_METHOD).  */
15391       smash_to_method_type (fnp->type, type,
15392                             TYPE_TARGET_TYPE (this_type),
15393                             TYPE_FIELDS (this_type),
15394                             TYPE_NFIELDS (this_type),
15395                             TYPE_VARARGS (this_type));
15396
15397       /* Handle static member functions.
15398          Dwarf2 has no clean way to discern C++ static and non-static
15399          member functions.  G++ helps GDB by marking the first
15400          parameter for non-static member functions (which is the this
15401          pointer) as artificial.  We obtain this information from
15402          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15403       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15404         fnp->voffset = VOFFSET_STATIC;
15405     }
15406   else
15407     complaint (_("member function type missing for '%s'"),
15408                dwarf2_full_name (fieldname, die, cu));
15409
15410   /* Get fcontext from DW_AT_containing_type if present.  */
15411   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15412     fnp->fcontext = die_containing_type (die, cu);
15413
15414   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15415      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15416
15417   /* Get accessibility.  */
15418   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15419   if (attr)
15420     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15421   else
15422     accessibility = dwarf2_default_access_attribute (die, cu);
15423   switch (accessibility)
15424     {
15425     case DW_ACCESS_private:
15426       fnp->is_private = 1;
15427       break;
15428     case DW_ACCESS_protected:
15429       fnp->is_protected = 1;
15430       break;
15431     }
15432
15433   /* Check for artificial methods.  */
15434   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15435   if (attr && DW_UNSND (attr) != 0)
15436     fnp->is_artificial = 1;
15437
15438   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15439
15440   /* Get index in virtual function table if it is a virtual member
15441      function.  For older versions of GCC, this is an offset in the
15442      appropriate virtual table, as specified by DW_AT_containing_type.
15443      For everyone else, it is an expression to be evaluated relative
15444      to the object address.  */
15445
15446   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15447   if (attr)
15448     {
15449       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15450         {
15451           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15452             {
15453               /* Old-style GCC.  */
15454               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15455             }
15456           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15457                    || (DW_BLOCK (attr)->size > 1
15458                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15459                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15460             {
15461               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15462               if ((fnp->voffset % cu->header.addr_size) != 0)
15463                 dwarf2_complex_location_expr_complaint ();
15464               else
15465                 fnp->voffset /= cu->header.addr_size;
15466               fnp->voffset += 2;
15467             }
15468           else
15469             dwarf2_complex_location_expr_complaint ();
15470
15471           if (!fnp->fcontext)
15472             {
15473               /* If there is no `this' field and no DW_AT_containing_type,
15474                  we cannot actually find a base class context for the
15475                  vtable!  */
15476               if (TYPE_NFIELDS (this_type) == 0
15477                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15478                 {
15479                   complaint (_("cannot determine context for virtual member "
15480                                "function \"%s\" (offset %s)"),
15481                              fieldname, sect_offset_str (die->sect_off));
15482                 }
15483               else
15484                 {
15485                   fnp->fcontext
15486                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15487                 }
15488             }
15489         }
15490       else if (attr_form_is_section_offset (attr))
15491         {
15492           dwarf2_complex_location_expr_complaint ();
15493         }
15494       else
15495         {
15496           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15497                                                  fieldname);
15498         }
15499     }
15500   else
15501     {
15502       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15503       if (attr && DW_UNSND (attr))
15504         {
15505           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15506           complaint (_("Member function \"%s\" (offset %s) is virtual "
15507                        "but the vtable offset is not specified"),
15508                      fieldname, sect_offset_str (die->sect_off));
15509           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15510           TYPE_CPLUS_DYNAMIC (type) = 1;
15511         }
15512     }
15513 }
15514
15515 /* Create the vector of member function fields, and attach it to the type.  */
15516
15517 static void
15518 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15519                                  struct dwarf2_cu *cu)
15520 {
15521   if (cu->language == language_ada)
15522     error (_("unexpected member functions in Ada type"));
15523
15524   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15525   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15526     TYPE_ALLOC (type,
15527                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15528
15529   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15530     {
15531       struct fnfieldlist &nf = fip->fnfieldlists[i];
15532       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15533
15534       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15535       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15536       fn_flp->fn_fields = (struct fn_field *)
15537         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15538
15539       for (int k = 0; k < nf.fnfields.size (); ++k)
15540         fn_flp->fn_fields[k] = nf.fnfields[k];
15541     }
15542
15543   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15544 }
15545
15546 /* Returns non-zero if NAME is the name of a vtable member in CU's
15547    language, zero otherwise.  */
15548 static int
15549 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15550 {
15551   static const char vptr[] = "_vptr";
15552
15553   /* Look for the C++ form of the vtable.  */
15554   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15555     return 1;
15556
15557   return 0;
15558 }
15559
15560 /* GCC outputs unnamed structures that are really pointers to member
15561    functions, with the ABI-specified layout.  If TYPE describes
15562    such a structure, smash it into a member function type.
15563
15564    GCC shouldn't do this; it should just output pointer to member DIEs.
15565    This is GCC PR debug/28767.  */
15566
15567 static void
15568 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15569 {
15570   struct type *pfn_type, *self_type, *new_type;
15571
15572   /* Check for a structure with no name and two children.  */
15573   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15574     return;
15575
15576   /* Check for __pfn and __delta members.  */
15577   if (TYPE_FIELD_NAME (type, 0) == NULL
15578       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15579       || TYPE_FIELD_NAME (type, 1) == NULL
15580       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15581     return;
15582
15583   /* Find the type of the method.  */
15584   pfn_type = TYPE_FIELD_TYPE (type, 0);
15585   if (pfn_type == NULL
15586       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15587       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15588     return;
15589
15590   /* Look for the "this" argument.  */
15591   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15592   if (TYPE_NFIELDS (pfn_type) == 0
15593       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15594       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15595     return;
15596
15597   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15598   new_type = alloc_type (objfile);
15599   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15600                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15601                         TYPE_VARARGS (pfn_type));
15602   smash_to_methodptr_type (type, new_type);
15603 }
15604
15605 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15606    appropriate error checking and issuing complaints if there is a
15607    problem.  */
15608
15609 static ULONGEST
15610 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15611 {
15612   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15613
15614   if (attr == nullptr)
15615     return 0;
15616
15617   if (!attr_form_is_constant (attr))
15618     {
15619       complaint (_("DW_AT_alignment must have constant form"
15620                    " - DIE at %s [in module %s]"),
15621                  sect_offset_str (die->sect_off),
15622                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15623       return 0;
15624     }
15625
15626   ULONGEST align;
15627   if (attr->form == DW_FORM_sdata)
15628     {
15629       LONGEST val = DW_SND (attr);
15630       if (val < 0)
15631         {
15632           complaint (_("DW_AT_alignment value must not be negative"
15633                        " - DIE at %s [in module %s]"),
15634                      sect_offset_str (die->sect_off),
15635                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15636           return 0;
15637         }
15638       align = val;
15639     }
15640   else
15641     align = DW_UNSND (attr);
15642
15643   if (align == 0)
15644     {
15645       complaint (_("DW_AT_alignment value must not be zero"
15646                    " - DIE at %s [in module %s]"),
15647                  sect_offset_str (die->sect_off),
15648                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15649       return 0;
15650     }
15651   if ((align & (align - 1)) != 0)
15652     {
15653       complaint (_("DW_AT_alignment value must be a power of 2"
15654                    " - DIE at %s [in module %s]"),
15655                  sect_offset_str (die->sect_off),
15656                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15657       return 0;
15658     }
15659
15660   return align;
15661 }
15662
15663 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15664    the alignment for TYPE.  */
15665
15666 static void
15667 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15668                      struct type *type)
15669 {
15670   if (!set_type_align (type, get_alignment (cu, die)))
15671     complaint (_("DW_AT_alignment value too large"
15672                  " - DIE at %s [in module %s]"),
15673                sect_offset_str (die->sect_off),
15674                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15675 }
15676
15677 /* Called when we find the DIE that starts a structure or union scope
15678    (definition) to create a type for the structure or union.  Fill in
15679    the type's name and general properties; the members will not be
15680    processed until process_structure_scope.  A symbol table entry for
15681    the type will also not be done until process_structure_scope (assuming
15682    the type has a name).
15683
15684    NOTE: we need to call these functions regardless of whether or not the
15685    DIE has a DW_AT_name attribute, since it might be an anonymous
15686    structure or union.  This gets the type entered into our set of
15687    user defined types.  */
15688
15689 static struct type *
15690 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15691 {
15692   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15693   struct type *type;
15694   struct attribute *attr;
15695   const char *name;
15696
15697   /* If the definition of this type lives in .debug_types, read that type.
15698      Don't follow DW_AT_specification though, that will take us back up
15699      the chain and we want to go down.  */
15700   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15701   if (attr)
15702     {
15703       type = get_DW_AT_signature_type (die, attr, cu);
15704
15705       /* The type's CU may not be the same as CU.
15706          Ensure TYPE is recorded with CU in die_type_hash.  */
15707       return set_die_type (die, type, cu);
15708     }
15709
15710   type = alloc_type (objfile);
15711   INIT_CPLUS_SPECIFIC (type);
15712
15713   name = dwarf2_name (die, cu);
15714   if (name != NULL)
15715     {
15716       if (cu->language == language_cplus
15717           || cu->language == language_d
15718           || cu->language == language_rust)
15719         {
15720           const char *full_name = dwarf2_full_name (name, die, cu);
15721
15722           /* dwarf2_full_name might have already finished building the DIE's
15723              type.  If so, there is no need to continue.  */
15724           if (get_die_type (die, cu) != NULL)
15725             return get_die_type (die, cu);
15726
15727           TYPE_NAME (type) = full_name;
15728         }
15729       else
15730         {
15731           /* The name is already allocated along with this objfile, so
15732              we don't need to duplicate it for the type.  */
15733           TYPE_NAME (type) = name;
15734         }
15735     }
15736
15737   if (die->tag == DW_TAG_structure_type)
15738     {
15739       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15740     }
15741   else if (die->tag == DW_TAG_union_type)
15742     {
15743       TYPE_CODE (type) = TYPE_CODE_UNION;
15744     }
15745   else if (die->tag == DW_TAG_variant_part)
15746     {
15747       TYPE_CODE (type) = TYPE_CODE_UNION;
15748       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15749     }
15750   else
15751     {
15752       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15753     }
15754
15755   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15756     TYPE_DECLARED_CLASS (type) = 1;
15757
15758   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15759   if (attr)
15760     {
15761       if (attr_form_is_constant (attr))
15762         TYPE_LENGTH (type) = DW_UNSND (attr);
15763       else
15764         {
15765           /* For the moment, dynamic type sizes are not supported
15766              by GDB's struct type.  The actual size is determined
15767              on-demand when resolving the type of a given object,
15768              so set the type's length to zero for now.  Otherwise,
15769              we record an expression as the length, and that expression
15770              could lead to a very large value, which could eventually
15771              lead to us trying to allocate that much memory when creating
15772              a value of that type.  */
15773           TYPE_LENGTH (type) = 0;
15774         }
15775     }
15776   else
15777     {
15778       TYPE_LENGTH (type) = 0;
15779     }
15780
15781   maybe_set_alignment (cu, die, type);
15782
15783   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15784     {
15785       /* ICC<14 does not output the required DW_AT_declaration on
15786          incomplete types, but gives them a size of zero.  */
15787       TYPE_STUB (type) = 1;
15788     }
15789   else
15790     TYPE_STUB_SUPPORTED (type) = 1;
15791
15792   if (die_is_declaration (die, cu))
15793     TYPE_STUB (type) = 1;
15794   else if (attr == NULL && die->child == NULL
15795            && producer_is_realview (cu->producer))
15796     /* RealView does not output the required DW_AT_declaration
15797        on incomplete types.  */
15798     TYPE_STUB (type) = 1;
15799
15800   /* We need to add the type field to the die immediately so we don't
15801      infinitely recurse when dealing with pointers to the structure
15802      type within the structure itself.  */
15803   set_die_type (die, type, cu);
15804
15805   /* set_die_type should be already done.  */
15806   set_descriptive_type (type, die, cu);
15807
15808   return type;
15809 }
15810
15811 /* A helper for process_structure_scope that handles a single member
15812    DIE.  */
15813
15814 static void
15815 handle_struct_member_die (struct die_info *child_die, struct type *type,
15816                           struct field_info *fi,
15817                           std::vector<struct symbol *> *template_args,
15818                           struct dwarf2_cu *cu)
15819 {
15820   if (child_die->tag == DW_TAG_member
15821       || child_die->tag == DW_TAG_variable
15822       || child_die->tag == DW_TAG_variant_part)
15823     {
15824       /* NOTE: carlton/2002-11-05: A C++ static data member
15825          should be a DW_TAG_member that is a declaration, but
15826          all versions of G++ as of this writing (so through at
15827          least 3.2.1) incorrectly generate DW_TAG_variable
15828          tags for them instead.  */
15829       dwarf2_add_field (fi, child_die, cu);
15830     }
15831   else if (child_die->tag == DW_TAG_subprogram)
15832     {
15833       /* Rust doesn't have member functions in the C++ sense.
15834          However, it does emit ordinary functions as children
15835          of a struct DIE.  */
15836       if (cu->language == language_rust)
15837         read_func_scope (child_die, cu);
15838       else
15839         {
15840           /* C++ member function.  */
15841           dwarf2_add_member_fn (fi, child_die, type, cu);
15842         }
15843     }
15844   else if (child_die->tag == DW_TAG_inheritance)
15845     {
15846       /* C++ base class field.  */
15847       dwarf2_add_field (fi, child_die, cu);
15848     }
15849   else if (type_can_define_types (child_die))
15850     dwarf2_add_type_defn (fi, child_die, cu);
15851   else if (child_die->tag == DW_TAG_template_type_param
15852            || child_die->tag == DW_TAG_template_value_param)
15853     {
15854       struct symbol *arg = new_symbol (child_die, NULL, cu);
15855
15856       if (arg != NULL)
15857         template_args->push_back (arg);
15858     }
15859   else if (child_die->tag == DW_TAG_variant)
15860     {
15861       /* In a variant we want to get the discriminant and also add a
15862          field for our sole member child.  */
15863       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15864
15865       for (struct die_info *variant_child = child_die->child;
15866            variant_child != NULL;
15867            variant_child = sibling_die (variant_child))
15868         {
15869           if (variant_child->tag == DW_TAG_member)
15870             {
15871               handle_struct_member_die (variant_child, type, fi,
15872                                         template_args, cu);
15873               /* Only handle the one.  */
15874               break;
15875             }
15876         }
15877
15878       /* We don't handle this but we might as well report it if we see
15879          it.  */
15880       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15881           complaint (_("DW_AT_discr_list is not supported yet"
15882                        " - DIE at %s [in module %s]"),
15883                      sect_offset_str (child_die->sect_off),
15884                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15885
15886       /* The first field was just added, so we can stash the
15887          discriminant there.  */
15888       gdb_assert (!fi->fields.empty ());
15889       if (discr == NULL)
15890         fi->fields.back ().variant.default_branch = true;
15891       else
15892         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15893     }
15894 }
15895
15896 /* Finish creating a structure or union type, including filling in
15897    its members and creating a symbol for it.  */
15898
15899 static void
15900 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15901 {
15902   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15903   struct die_info *child_die;
15904   struct type *type;
15905
15906   type = get_die_type (die, cu);
15907   if (type == NULL)
15908     type = read_structure_type (die, cu);
15909
15910   /* When reading a DW_TAG_variant_part, we need to notice when we
15911      read the discriminant member, so we can record it later in the
15912      discriminant_info.  */
15913   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15914   sect_offset discr_offset;
15915   bool has_template_parameters = false;
15916
15917   if (is_variant_part)
15918     {
15919       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15920       if (discr == NULL)
15921         {
15922           /* Maybe it's a univariant form, an extension we support.
15923              In this case arrange not to check the offset.  */
15924           is_variant_part = false;
15925         }
15926       else if (attr_form_is_ref (discr))
15927         {
15928           struct dwarf2_cu *target_cu = cu;
15929           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15930
15931           discr_offset = target_die->sect_off;
15932         }
15933       else
15934         {
15935           complaint (_("DW_AT_discr does not have DIE reference form"
15936                        " - DIE at %s [in module %s]"),
15937                      sect_offset_str (die->sect_off),
15938                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15939           is_variant_part = false;
15940         }
15941     }
15942
15943   if (die->child != NULL && ! die_is_declaration (die, cu))
15944     {
15945       struct field_info fi;
15946       std::vector<struct symbol *> template_args;
15947
15948       child_die = die->child;
15949
15950       while (child_die && child_die->tag)
15951         {
15952           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15953
15954           if (is_variant_part && discr_offset == child_die->sect_off)
15955             fi.fields.back ().variant.is_discriminant = true;
15956
15957           child_die = sibling_die (child_die);
15958         }
15959
15960       /* Attach template arguments to type.  */
15961       if (!template_args.empty ())
15962         {
15963           has_template_parameters = true;
15964           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15965           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15966           TYPE_TEMPLATE_ARGUMENTS (type)
15967             = XOBNEWVEC (&objfile->objfile_obstack,
15968                          struct symbol *,
15969                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15970           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15971                   template_args.data (),
15972                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15973                    * sizeof (struct symbol *)));
15974         }
15975
15976       /* Attach fields and member functions to the type.  */
15977       if (fi.nfields)
15978         dwarf2_attach_fields_to_type (&fi, type, cu);
15979       if (!fi.fnfieldlists.empty ())
15980         {
15981           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15982
15983           /* Get the type which refers to the base class (possibly this
15984              class itself) which contains the vtable pointer for the current
15985              class from the DW_AT_containing_type attribute.  This use of
15986              DW_AT_containing_type is a GNU extension.  */
15987
15988           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15989             {
15990               struct type *t = die_containing_type (die, cu);
15991
15992               set_type_vptr_basetype (type, t);
15993               if (type == t)
15994                 {
15995                   int i;
15996
15997                   /* Our own class provides vtbl ptr.  */
15998                   for (i = TYPE_NFIELDS (t) - 1;
15999                        i >= TYPE_N_BASECLASSES (t);
16000                        --i)
16001                     {
16002                       const char *fieldname = TYPE_FIELD_NAME (t, i);
16003
16004                       if (is_vtable_name (fieldname, cu))
16005                         {
16006                           set_type_vptr_fieldno (type, i);
16007                           break;
16008                         }
16009                     }
16010
16011                   /* Complain if virtual function table field not found.  */
16012                   if (i < TYPE_N_BASECLASSES (t))
16013                     complaint (_("virtual function table pointer "
16014                                  "not found when defining class '%s'"),
16015                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
16016                 }
16017               else
16018                 {
16019                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
16020                 }
16021             }
16022           else if (cu->producer
16023                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
16024             {
16025               /* The IBM XLC compiler does not provide direct indication
16026                  of the containing type, but the vtable pointer is
16027                  always named __vfp.  */
16028
16029               int i;
16030
16031               for (i = TYPE_NFIELDS (type) - 1;
16032                    i >= TYPE_N_BASECLASSES (type);
16033                    --i)
16034                 {
16035                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
16036                     {
16037                       set_type_vptr_fieldno (type, i);
16038                       set_type_vptr_basetype (type, type);
16039                       break;
16040                     }
16041                 }
16042             }
16043         }
16044
16045       /* Copy fi.typedef_field_list linked list elements content into the
16046          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
16047       if (!fi.typedef_field_list.empty ())
16048         {
16049           int count = fi.typedef_field_list.size ();
16050
16051           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16052           TYPE_TYPEDEF_FIELD_ARRAY (type)
16053             = ((struct decl_field *)
16054                TYPE_ALLOC (type,
16055                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
16056           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
16057
16058           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
16059             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
16060         }
16061
16062       /* Copy fi.nested_types_list linked list elements content into the
16063          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
16064       if (!fi.nested_types_list.empty () && cu->language != language_ada)
16065         {
16066           int count = fi.nested_types_list.size ();
16067
16068           ALLOCATE_CPLUS_STRUCT_TYPE (type);
16069           TYPE_NESTED_TYPES_ARRAY (type)
16070             = ((struct decl_field *)
16071                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
16072           TYPE_NESTED_TYPES_COUNT (type) = count;
16073
16074           for (int i = 0; i < fi.nested_types_list.size (); ++i)
16075             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
16076         }
16077     }
16078
16079   quirk_gcc_member_function_pointer (type, objfile);
16080   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
16081     cu->rust_unions.push_back (type);
16082
16083   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16084      snapshots) has been known to create a die giving a declaration
16085      for a class that has, as a child, a die giving a definition for a
16086      nested class.  So we have to process our children even if the
16087      current die is a declaration.  Normally, of course, a declaration
16088      won't have any children at all.  */
16089
16090   child_die = die->child;
16091
16092   while (child_die != NULL && child_die->tag)
16093     {
16094       if (child_die->tag == DW_TAG_member
16095           || child_die->tag == DW_TAG_variable
16096           || child_die->tag == DW_TAG_inheritance
16097           || child_die->tag == DW_TAG_template_value_param
16098           || child_die->tag == DW_TAG_template_type_param)
16099         {
16100           /* Do nothing.  */
16101         }
16102       else
16103         process_die (child_die, cu);
16104
16105       child_die = sibling_die (child_die);
16106     }
16107
16108   /* Do not consider external references.  According to the DWARF standard,
16109      these DIEs are identified by the fact that they have no byte_size
16110      attribute, and a declaration attribute.  */
16111   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16112       || !die_is_declaration (die, cu))
16113     {
16114       struct symbol *sym = new_symbol (die, type, cu);
16115
16116       if (has_template_parameters)
16117         {
16118           /* Make sure that the symtab is set on the new symbols.
16119              Even though they don't appear in this symtab directly,
16120              other parts of gdb assume that symbols do, and this is
16121              reasonably true.  */
16122           for (int i = 0; i < TYPE_N_TEMPLATE_ARGUMENTS (type); ++i)
16123             symbol_set_symtab (TYPE_TEMPLATE_ARGUMENT (type, i),
16124                                symbol_symtab (sym));
16125         }
16126     }
16127 }
16128
16129 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16130    update TYPE using some information only available in DIE's children.  */
16131
16132 static void
16133 update_enumeration_type_from_children (struct die_info *die,
16134                                        struct type *type,
16135                                        struct dwarf2_cu *cu)
16136 {
16137   struct die_info *child_die;
16138   int unsigned_enum = 1;
16139   int flag_enum = 1;
16140   ULONGEST mask = 0;
16141
16142   auto_obstack obstack;
16143
16144   for (child_die = die->child;
16145        child_die != NULL && child_die->tag;
16146        child_die = sibling_die (child_die))
16147     {
16148       struct attribute *attr;
16149       LONGEST value;
16150       const gdb_byte *bytes;
16151       struct dwarf2_locexpr_baton *baton;
16152       const char *name;
16153
16154       if (child_die->tag != DW_TAG_enumerator)
16155         continue;
16156
16157       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16158       if (attr == NULL)
16159         continue;
16160
16161       name = dwarf2_name (child_die, cu);
16162       if (name == NULL)
16163         name = "<anonymous enumerator>";
16164
16165       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16166                                &value, &bytes, &baton);
16167       if (value < 0)
16168         {
16169           unsigned_enum = 0;
16170           flag_enum = 0;
16171         }
16172       else if ((mask & value) != 0)
16173         flag_enum = 0;
16174       else
16175         mask |= value;
16176
16177       /* If we already know that the enum type is neither unsigned, nor
16178          a flag type, no need to look at the rest of the enumerates.  */
16179       if (!unsigned_enum && !flag_enum)
16180         break;
16181     }
16182
16183   if (unsigned_enum)
16184     TYPE_UNSIGNED (type) = 1;
16185   if (flag_enum)
16186     TYPE_FLAG_ENUM (type) = 1;
16187 }
16188
16189 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16190    complete the type's fields yet, or create any symbols.  */
16191
16192 static struct type *
16193 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16194 {
16195   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16196   struct type *type;
16197   struct attribute *attr;
16198   const char *name;
16199
16200   /* If the definition of this type lives in .debug_types, read that type.
16201      Don't follow DW_AT_specification though, that will take us back up
16202      the chain and we want to go down.  */
16203   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16204   if (attr)
16205     {
16206       type = get_DW_AT_signature_type (die, attr, cu);
16207
16208       /* The type's CU may not be the same as CU.
16209          Ensure TYPE is recorded with CU in die_type_hash.  */
16210       return set_die_type (die, type, cu);
16211     }
16212
16213   type = alloc_type (objfile);
16214
16215   TYPE_CODE (type) = TYPE_CODE_ENUM;
16216   name = dwarf2_full_name (NULL, die, cu);
16217   if (name != NULL)
16218     TYPE_NAME (type) = name;
16219
16220   attr = dwarf2_attr (die, DW_AT_type, cu);
16221   if (attr != NULL)
16222     {
16223       struct type *underlying_type = die_type (die, cu);
16224
16225       TYPE_TARGET_TYPE (type) = underlying_type;
16226     }
16227
16228   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16229   if (attr)
16230     {
16231       TYPE_LENGTH (type) = DW_UNSND (attr);
16232     }
16233   else
16234     {
16235       TYPE_LENGTH (type) = 0;
16236     }
16237
16238   maybe_set_alignment (cu, die, type);
16239
16240   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16241      declared as private in the package spec, and then defined only
16242      inside the package body.  Such types are known as Taft Amendment
16243      Types.  When another package uses such a type, an incomplete DIE
16244      may be generated by the compiler.  */
16245   if (die_is_declaration (die, cu))
16246     TYPE_STUB (type) = 1;
16247
16248   /* Finish the creation of this type by using the enum's children.
16249      We must call this even when the underlying type has been provided
16250      so that we can determine if we're looking at a "flag" enum.  */
16251   update_enumeration_type_from_children (die, type, cu);
16252
16253   /* If this type has an underlying type that is not a stub, then we
16254      may use its attributes.  We always use the "unsigned" attribute
16255      in this situation, because ordinarily we guess whether the type
16256      is unsigned -- but the guess can be wrong and the underlying type
16257      can tell us the reality.  However, we defer to a local size
16258      attribute if one exists, because this lets the compiler override
16259      the underlying type if needed.  */
16260   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16261     {
16262       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16263       if (TYPE_LENGTH (type) == 0)
16264         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16265       if (TYPE_RAW_ALIGN (type) == 0
16266           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16267         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16268     }
16269
16270   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16271
16272   return set_die_type (die, type, cu);
16273 }
16274
16275 /* Given a pointer to a die which begins an enumeration, process all
16276    the dies that define the members of the enumeration, and create the
16277    symbol for the enumeration type.
16278
16279    NOTE: We reverse the order of the element list.  */
16280
16281 static void
16282 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16283 {
16284   struct type *this_type;
16285
16286   this_type = get_die_type (die, cu);
16287   if (this_type == NULL)
16288     this_type = read_enumeration_type (die, cu);
16289
16290   if (die->child != NULL)
16291     {
16292       struct die_info *child_die;
16293       struct symbol *sym;
16294       struct field *fields = NULL;
16295       int num_fields = 0;
16296       const char *name;
16297
16298       child_die = die->child;
16299       while (child_die && child_die->tag)
16300         {
16301           if (child_die->tag != DW_TAG_enumerator)
16302             {
16303               process_die (child_die, cu);
16304             }
16305           else
16306             {
16307               name = dwarf2_name (child_die, cu);
16308               if (name)
16309                 {
16310                   sym = new_symbol (child_die, this_type, cu);
16311
16312                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16313                     {
16314                       fields = (struct field *)
16315                         xrealloc (fields,
16316                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16317                                   * sizeof (struct field));
16318                     }
16319
16320                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16321                   FIELD_TYPE (fields[num_fields]) = NULL;
16322                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16323                   FIELD_BITSIZE (fields[num_fields]) = 0;
16324
16325                   num_fields++;
16326                 }
16327             }
16328
16329           child_die = sibling_die (child_die);
16330         }
16331
16332       if (num_fields)
16333         {
16334           TYPE_NFIELDS (this_type) = num_fields;
16335           TYPE_FIELDS (this_type) = (struct field *)
16336             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16337           memcpy (TYPE_FIELDS (this_type), fields,
16338                   sizeof (struct field) * num_fields);
16339           xfree (fields);
16340         }
16341     }
16342
16343   /* If we are reading an enum from a .debug_types unit, and the enum
16344      is a declaration, and the enum is not the signatured type in the
16345      unit, then we do not want to add a symbol for it.  Adding a
16346      symbol would in some cases obscure the true definition of the
16347      enum, giving users an incomplete type when the definition is
16348      actually available.  Note that we do not want to do this for all
16349      enums which are just declarations, because C++0x allows forward
16350      enum declarations.  */
16351   if (cu->per_cu->is_debug_types
16352       && die_is_declaration (die, cu))
16353     {
16354       struct signatured_type *sig_type;
16355
16356       sig_type = (struct signatured_type *) cu->per_cu;
16357       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16358       if (sig_type->type_offset_in_section != die->sect_off)
16359         return;
16360     }
16361
16362   new_symbol (die, this_type, cu);
16363 }
16364
16365 /* Extract all information from a DW_TAG_array_type DIE and put it in
16366    the DIE's type field.  For now, this only handles one dimensional
16367    arrays.  */
16368
16369 static struct type *
16370 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16371 {
16372   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16373   struct die_info *child_die;
16374   struct type *type;
16375   struct type *element_type, *range_type, *index_type;
16376   struct attribute *attr;
16377   const char *name;
16378   struct dynamic_prop *byte_stride_prop = NULL;
16379   unsigned int bit_stride = 0;
16380
16381   element_type = die_type (die, cu);
16382
16383   /* The die_type call above may have already set the type for this DIE.  */
16384   type = get_die_type (die, cu);
16385   if (type)
16386     return type;
16387
16388   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16389   if (attr != NULL)
16390     {
16391       int stride_ok;
16392
16393       byte_stride_prop
16394         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16395       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16396       if (!stride_ok)
16397         {
16398           complaint (_("unable to read array DW_AT_byte_stride "
16399                        " - DIE at %s [in module %s]"),
16400                      sect_offset_str (die->sect_off),
16401                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16402           /* Ignore this attribute.  We will likely not be able to print
16403              arrays of this type correctly, but there is little we can do
16404              to help if we cannot read the attribute's value.  */
16405           byte_stride_prop = NULL;
16406         }
16407     }
16408
16409   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16410   if (attr != NULL)
16411     bit_stride = DW_UNSND (attr);
16412
16413   /* Irix 6.2 native cc creates array types without children for
16414      arrays with unspecified length.  */
16415   if (die->child == NULL)
16416     {
16417       index_type = objfile_type (objfile)->builtin_int;
16418       range_type = create_static_range_type (NULL, index_type, 0, -1);
16419       type = create_array_type_with_stride (NULL, element_type, range_type,
16420                                             byte_stride_prop, bit_stride);
16421       return set_die_type (die, type, cu);
16422     }
16423
16424   std::vector<struct type *> range_types;
16425   child_die = die->child;
16426   while (child_die && child_die->tag)
16427     {
16428       if (child_die->tag == DW_TAG_subrange_type)
16429         {
16430           struct type *child_type = read_type_die (child_die, cu);
16431
16432           if (child_type != NULL)
16433             {
16434               /* The range type was succesfully read.  Save it for the
16435                  array type creation.  */
16436               range_types.push_back (child_type);
16437             }
16438         }
16439       child_die = sibling_die (child_die);
16440     }
16441
16442   /* Dwarf2 dimensions are output from left to right, create the
16443      necessary array types in backwards order.  */
16444
16445   type = element_type;
16446
16447   if (read_array_order (die, cu) == DW_ORD_col_major)
16448     {
16449       int i = 0;
16450
16451       while (i < range_types.size ())
16452         type = create_array_type_with_stride (NULL, type, range_types[i++],
16453                                               byte_stride_prop, bit_stride);
16454     }
16455   else
16456     {
16457       size_t ndim = range_types.size ();
16458       while (ndim-- > 0)
16459         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16460                                               byte_stride_prop, bit_stride);
16461     }
16462
16463   /* Understand Dwarf2 support for vector types (like they occur on
16464      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16465      array type.  This is not part of the Dwarf2/3 standard yet, but a
16466      custom vendor extension.  The main difference between a regular
16467      array and the vector variant is that vectors are passed by value
16468      to functions.  */
16469   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16470   if (attr)
16471     make_vector_type (type);
16472
16473   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16474      implementation may choose to implement triple vectors using this
16475      attribute.  */
16476   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16477   if (attr)
16478     {
16479       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16480         TYPE_LENGTH (type) = DW_UNSND (attr);
16481       else
16482         complaint (_("DW_AT_byte_size for array type smaller "
16483                      "than the total size of elements"));
16484     }
16485
16486   name = dwarf2_name (die, cu);
16487   if (name)
16488     TYPE_NAME (type) = name;
16489
16490   maybe_set_alignment (cu, die, type);
16491
16492   /* Install the type in the die.  */
16493   set_die_type (die, type, cu);
16494
16495   /* set_die_type should be already done.  */
16496   set_descriptive_type (type, die, cu);
16497
16498   return type;
16499 }
16500
16501 static enum dwarf_array_dim_ordering
16502 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16503 {
16504   struct attribute *attr;
16505
16506   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16507
16508   if (attr)
16509     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16510
16511   /* GNU F77 is a special case, as at 08/2004 array type info is the
16512      opposite order to the dwarf2 specification, but data is still
16513      laid out as per normal fortran.
16514
16515      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16516      version checking.  */
16517
16518   if (cu->language == language_fortran
16519       && cu->producer && strstr (cu->producer, "GNU F77"))
16520     {
16521       return DW_ORD_row_major;
16522     }
16523
16524   switch (cu->language_defn->la_array_ordering)
16525     {
16526     case array_column_major:
16527       return DW_ORD_col_major;
16528     case array_row_major:
16529     default:
16530       return DW_ORD_row_major;
16531     };
16532 }
16533
16534 /* Extract all information from a DW_TAG_set_type DIE and put it in
16535    the DIE's type field.  */
16536
16537 static struct type *
16538 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16539 {
16540   struct type *domain_type, *set_type;
16541   struct attribute *attr;
16542
16543   domain_type = die_type (die, cu);
16544
16545   /* The die_type call above may have already set the type for this DIE.  */
16546   set_type = get_die_type (die, cu);
16547   if (set_type)
16548     return set_type;
16549
16550   set_type = create_set_type (NULL, domain_type);
16551
16552   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16553   if (attr)
16554     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16555
16556   maybe_set_alignment (cu, die, set_type);
16557
16558   return set_die_type (die, set_type, cu);
16559 }
16560
16561 /* A helper for read_common_block that creates a locexpr baton.
16562    SYM is the symbol which we are marking as computed.
16563    COMMON_DIE is the DIE for the common block.
16564    COMMON_LOC is the location expression attribute for the common
16565    block itself.
16566    MEMBER_LOC is the location expression attribute for the particular
16567    member of the common block that we are processing.
16568    CU is the CU from which the above come.  */
16569
16570 static void
16571 mark_common_block_symbol_computed (struct symbol *sym,
16572                                    struct die_info *common_die,
16573                                    struct attribute *common_loc,
16574                                    struct attribute *member_loc,
16575                                    struct dwarf2_cu *cu)
16576 {
16577   struct dwarf2_per_objfile *dwarf2_per_objfile
16578     = cu->per_cu->dwarf2_per_objfile;
16579   struct objfile *objfile = dwarf2_per_objfile->objfile;
16580   struct dwarf2_locexpr_baton *baton;
16581   gdb_byte *ptr;
16582   unsigned int cu_off;
16583   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16584   LONGEST offset = 0;
16585
16586   gdb_assert (common_loc && member_loc);
16587   gdb_assert (attr_form_is_block (common_loc));
16588   gdb_assert (attr_form_is_block (member_loc)
16589               || attr_form_is_constant (member_loc));
16590
16591   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16592   baton->per_cu = cu->per_cu;
16593   gdb_assert (baton->per_cu);
16594
16595   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16596
16597   if (attr_form_is_constant (member_loc))
16598     {
16599       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16600       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16601     }
16602   else
16603     baton->size += DW_BLOCK (member_loc)->size;
16604
16605   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16606   baton->data = ptr;
16607
16608   *ptr++ = DW_OP_call4;
16609   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16610   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16611   ptr += 4;
16612
16613   if (attr_form_is_constant (member_loc))
16614     {
16615       *ptr++ = DW_OP_addr;
16616       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16617       ptr += cu->header.addr_size;
16618     }
16619   else
16620     {
16621       /* We have to copy the data here, because DW_OP_call4 will only
16622          use a DW_AT_location attribute.  */
16623       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16624       ptr += DW_BLOCK (member_loc)->size;
16625     }
16626
16627   *ptr++ = DW_OP_plus;
16628   gdb_assert (ptr - baton->data == baton->size);
16629
16630   SYMBOL_LOCATION_BATON (sym) = baton;
16631   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16632 }
16633
16634 /* Create appropriate locally-scoped variables for all the
16635    DW_TAG_common_block entries.  Also create a struct common_block
16636    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16637    is used to sepate the common blocks name namespace from regular
16638    variable names.  */
16639
16640 static void
16641 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16642 {
16643   struct attribute *attr;
16644
16645   attr = dwarf2_attr (die, DW_AT_location, cu);
16646   if (attr)
16647     {
16648       /* Support the .debug_loc offsets.  */
16649       if (attr_form_is_block (attr))
16650         {
16651           /* Ok.  */
16652         }
16653       else if (attr_form_is_section_offset (attr))
16654         {
16655           dwarf2_complex_location_expr_complaint ();
16656           attr = NULL;
16657         }
16658       else
16659         {
16660           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16661                                                  "common block member");
16662           attr = NULL;
16663         }
16664     }
16665
16666   if (die->child != NULL)
16667     {
16668       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16669       struct die_info *child_die;
16670       size_t n_entries = 0, size;
16671       struct common_block *common_block;
16672       struct symbol *sym;
16673
16674       for (child_die = die->child;
16675            child_die && child_die->tag;
16676            child_die = sibling_die (child_die))
16677         ++n_entries;
16678
16679       size = (sizeof (struct common_block)
16680               + (n_entries - 1) * sizeof (struct symbol *));
16681       common_block
16682         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16683                                                  size);
16684       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16685       common_block->n_entries = 0;
16686
16687       for (child_die = die->child;
16688            child_die && child_die->tag;
16689            child_die = sibling_die (child_die))
16690         {
16691           /* Create the symbol in the DW_TAG_common_block block in the current
16692              symbol scope.  */
16693           sym = new_symbol (child_die, NULL, cu);
16694           if (sym != NULL)
16695             {
16696               struct attribute *member_loc;
16697
16698               common_block->contents[common_block->n_entries++] = sym;
16699
16700               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16701                                         cu);
16702               if (member_loc)
16703                 {
16704                   /* GDB has handled this for a long time, but it is
16705                      not specified by DWARF.  It seems to have been
16706                      emitted by gfortran at least as recently as:
16707                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16708                   complaint (_("Variable in common block has "
16709                                "DW_AT_data_member_location "
16710                                "- DIE at %s [in module %s]"),
16711                                sect_offset_str (child_die->sect_off),
16712                              objfile_name (objfile));
16713
16714                   if (attr_form_is_section_offset (member_loc))
16715                     dwarf2_complex_location_expr_complaint ();
16716                   else if (attr_form_is_constant (member_loc)
16717                            || attr_form_is_block (member_loc))
16718                     {
16719                       if (attr)
16720                         mark_common_block_symbol_computed (sym, die, attr,
16721                                                            member_loc, cu);
16722                     }
16723                   else
16724                     dwarf2_complex_location_expr_complaint ();
16725                 }
16726             }
16727         }
16728
16729       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16730       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16731     }
16732 }
16733
16734 /* Create a type for a C++ namespace.  */
16735
16736 static struct type *
16737 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16738 {
16739   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16740   const char *previous_prefix, *name;
16741   int is_anonymous;
16742   struct type *type;
16743
16744   /* For extensions, reuse the type of the original namespace.  */
16745   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16746     {
16747       struct die_info *ext_die;
16748       struct dwarf2_cu *ext_cu = cu;
16749
16750       ext_die = dwarf2_extension (die, &ext_cu);
16751       type = read_type_die (ext_die, ext_cu);
16752
16753       /* EXT_CU may not be the same as CU.
16754          Ensure TYPE is recorded with CU in die_type_hash.  */
16755       return set_die_type (die, type, cu);
16756     }
16757
16758   name = namespace_name (die, &is_anonymous, cu);
16759
16760   /* Now build the name of the current namespace.  */
16761
16762   previous_prefix = determine_prefix (die, cu);
16763   if (previous_prefix[0] != '\0')
16764     name = typename_concat (&objfile->objfile_obstack,
16765                             previous_prefix, name, 0, cu);
16766
16767   /* Create the type.  */
16768   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16769
16770   return set_die_type (die, type, cu);
16771 }
16772
16773 /* Read a namespace scope.  */
16774
16775 static void
16776 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16777 {
16778   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16779   int is_anonymous;
16780
16781   /* Add a symbol associated to this if we haven't seen the namespace
16782      before.  Also, add a using directive if it's an anonymous
16783      namespace.  */
16784
16785   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16786     {
16787       struct type *type;
16788
16789       type = read_type_die (die, cu);
16790       new_symbol (die, type, cu);
16791
16792       namespace_name (die, &is_anonymous, cu);
16793       if (is_anonymous)
16794         {
16795           const char *previous_prefix = determine_prefix (die, cu);
16796
16797           std::vector<const char *> excludes;
16798           add_using_directive (using_directives (cu),
16799                                previous_prefix, TYPE_NAME (type), NULL,
16800                                NULL, excludes, 0, &objfile->objfile_obstack);
16801         }
16802     }
16803
16804   if (die->child != NULL)
16805     {
16806       struct die_info *child_die = die->child;
16807
16808       while (child_die && child_die->tag)
16809         {
16810           process_die (child_die, cu);
16811           child_die = sibling_die (child_die);
16812         }
16813     }
16814 }
16815
16816 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16817    imported module.  Still we need that type as local Fortran "use ... only"
16818    declaration imports depend on the created type in determine_prefix.  */
16819
16820 static struct type *
16821 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16822 {
16823   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16824   const char *module_name;
16825   struct type *type;
16826
16827   module_name = dwarf2_name (die, cu);
16828   if (!module_name)
16829     complaint (_("DW_TAG_module has no name, offset %s"),
16830                sect_offset_str (die->sect_off));
16831   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16832
16833   return set_die_type (die, type, cu);
16834 }
16835
16836 /* Read a Fortran module.  */
16837
16838 static void
16839 read_module (struct die_info *die, struct dwarf2_cu *cu)
16840 {
16841   struct die_info *child_die = die->child;
16842   struct type *type;
16843
16844   type = read_type_die (die, cu);
16845   new_symbol (die, type, cu);
16846
16847   while (child_die && child_die->tag)
16848     {
16849       process_die (child_die, cu);
16850       child_die = sibling_die (child_die);
16851     }
16852 }
16853
16854 /* Return the name of the namespace represented by DIE.  Set
16855    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16856    namespace.  */
16857
16858 static const char *
16859 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16860 {
16861   struct die_info *current_die;
16862   const char *name = NULL;
16863
16864   /* Loop through the extensions until we find a name.  */
16865
16866   for (current_die = die;
16867        current_die != NULL;
16868        current_die = dwarf2_extension (die, &cu))
16869     {
16870       /* We don't use dwarf2_name here so that we can detect the absence
16871          of a name -> anonymous namespace.  */
16872       name = dwarf2_string_attr (die, DW_AT_name, cu);
16873
16874       if (name != NULL)
16875         break;
16876     }
16877
16878   /* Is it an anonymous namespace?  */
16879
16880   *is_anonymous = (name == NULL);
16881   if (*is_anonymous)
16882     name = CP_ANONYMOUS_NAMESPACE_STR;
16883
16884   return name;
16885 }
16886
16887 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16888    the user defined type vector.  */
16889
16890 static struct type *
16891 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16892 {
16893   struct gdbarch *gdbarch
16894     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16895   struct comp_unit_head *cu_header = &cu->header;
16896   struct type *type;
16897   struct attribute *attr_byte_size;
16898   struct attribute *attr_address_class;
16899   int byte_size, addr_class;
16900   struct type *target_type;
16901
16902   target_type = die_type (die, cu);
16903
16904   /* The die_type call above may have already set the type for this DIE.  */
16905   type = get_die_type (die, cu);
16906   if (type)
16907     return type;
16908
16909   type = lookup_pointer_type (target_type);
16910
16911   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16912   if (attr_byte_size)
16913     byte_size = DW_UNSND (attr_byte_size);
16914   else
16915     byte_size = cu_header->addr_size;
16916
16917   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16918   if (attr_address_class)
16919     addr_class = DW_UNSND (attr_address_class);
16920   else
16921     addr_class = DW_ADDR_none;
16922
16923   ULONGEST alignment = get_alignment (cu, die);
16924
16925   /* If the pointer size, alignment, or address class is different
16926      than the default, create a type variant marked as such and set
16927      the length accordingly.  */
16928   if (TYPE_LENGTH (type) != byte_size
16929       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16930           && alignment != TYPE_RAW_ALIGN (type))
16931       || addr_class != DW_ADDR_none)
16932     {
16933       if (gdbarch_address_class_type_flags_p (gdbarch))
16934         {
16935           int type_flags;
16936
16937           type_flags = gdbarch_address_class_type_flags
16938                          (gdbarch, byte_size, addr_class);
16939           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16940                       == 0);
16941           type = make_type_with_address_space (type, type_flags);
16942         }
16943       else if (TYPE_LENGTH (type) != byte_size)
16944         {
16945           complaint (_("invalid pointer size %d"), byte_size);
16946         }
16947       else if (TYPE_RAW_ALIGN (type) != alignment)
16948         {
16949           complaint (_("Invalid DW_AT_alignment"
16950                        " - DIE at %s [in module %s]"),
16951                      sect_offset_str (die->sect_off),
16952                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16953         }
16954       else
16955         {
16956           /* Should we also complain about unhandled address classes?  */
16957         }
16958     }
16959
16960   TYPE_LENGTH (type) = byte_size;
16961   set_type_align (type, alignment);
16962   return set_die_type (die, type, cu);
16963 }
16964
16965 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16966    the user defined type vector.  */
16967
16968 static struct type *
16969 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16970 {
16971   struct type *type;
16972   struct type *to_type;
16973   struct type *domain;
16974
16975   to_type = die_type (die, cu);
16976   domain = die_containing_type (die, cu);
16977
16978   /* The calls above may have already set the type for this DIE.  */
16979   type = get_die_type (die, cu);
16980   if (type)
16981     return type;
16982
16983   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16984     type = lookup_methodptr_type (to_type);
16985   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16986     {
16987       struct type *new_type
16988         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16989
16990       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16991                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16992                             TYPE_VARARGS (to_type));
16993       type = lookup_methodptr_type (new_type);
16994     }
16995   else
16996     type = lookup_memberptr_type (to_type, domain);
16997
16998   return set_die_type (die, type, cu);
16999 }
17000
17001 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
17002    the user defined type vector.  */
17003
17004 static struct type *
17005 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
17006                           enum type_code refcode)
17007 {
17008   struct comp_unit_head *cu_header = &cu->header;
17009   struct type *type, *target_type;
17010   struct attribute *attr;
17011
17012   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
17013
17014   target_type = die_type (die, cu);
17015
17016   /* The die_type call above may have already set the type for this DIE.  */
17017   type = get_die_type (die, cu);
17018   if (type)
17019     return type;
17020
17021   type = lookup_reference_type (target_type, refcode);
17022   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17023   if (attr)
17024     {
17025       TYPE_LENGTH (type) = DW_UNSND (attr);
17026     }
17027   else
17028     {
17029       TYPE_LENGTH (type) = cu_header->addr_size;
17030     }
17031   maybe_set_alignment (cu, die, type);
17032   return set_die_type (die, type, cu);
17033 }
17034
17035 /* Add the given cv-qualifiers to the element type of the array.  GCC
17036    outputs DWARF type qualifiers that apply to an array, not the
17037    element type.  But GDB relies on the array element type to carry
17038    the cv-qualifiers.  This mimics section 6.7.3 of the C99
17039    specification.  */
17040
17041 static struct type *
17042 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
17043                    struct type *base_type, int cnst, int voltl)
17044 {
17045   struct type *el_type, *inner_array;
17046
17047   base_type = copy_type (base_type);
17048   inner_array = base_type;
17049
17050   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
17051     {
17052       TYPE_TARGET_TYPE (inner_array) =
17053         copy_type (TYPE_TARGET_TYPE (inner_array));
17054       inner_array = TYPE_TARGET_TYPE (inner_array);
17055     }
17056
17057   el_type = TYPE_TARGET_TYPE (inner_array);
17058   cnst |= TYPE_CONST (el_type);
17059   voltl |= TYPE_VOLATILE (el_type);
17060   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
17061
17062   return set_die_type (die, base_type, cu);
17063 }
17064
17065 static struct type *
17066 read_tag_const_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   /* In case the const qualifier is applied to an array type, the element type
17078      is so qualified, not the array type (section 6.7.3 of C99).  */
17079   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17080     return add_array_cv_type (die, cu, base_type, 1, 0);
17081
17082   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
17083   return set_die_type (die, cv_type, cu);
17084 }
17085
17086 static struct type *
17087 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
17088 {
17089   struct type *base_type, *cv_type;
17090
17091   base_type = die_type (die, cu);
17092
17093   /* The die_type call above may have already set the type for this DIE.  */
17094   cv_type = get_die_type (die, cu);
17095   if (cv_type)
17096     return cv_type;
17097
17098   /* In case the volatile qualifier is applied to an array type, the
17099      element type is so qualified, not the array type (section 6.7.3
17100      of C99).  */
17101   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17102     return add_array_cv_type (die, cu, base_type, 0, 1);
17103
17104   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17105   return set_die_type (die, cv_type, cu);
17106 }
17107
17108 /* Handle DW_TAG_restrict_type.  */
17109
17110 static struct type *
17111 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17112 {
17113   struct type *base_type, *cv_type;
17114
17115   base_type = die_type (die, cu);
17116
17117   /* The die_type call above may have already set the type for this DIE.  */
17118   cv_type = get_die_type (die, cu);
17119   if (cv_type)
17120     return cv_type;
17121
17122   cv_type = make_restrict_type (base_type);
17123   return set_die_type (die, cv_type, cu);
17124 }
17125
17126 /* Handle DW_TAG_atomic_type.  */
17127
17128 static struct type *
17129 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17130 {
17131   struct type *base_type, *cv_type;
17132
17133   base_type = die_type (die, cu);
17134
17135   /* The die_type call above may have already set the type for this DIE.  */
17136   cv_type = get_die_type (die, cu);
17137   if (cv_type)
17138     return cv_type;
17139
17140   cv_type = make_atomic_type (base_type);
17141   return set_die_type (die, cv_type, cu);
17142 }
17143
17144 /* Extract all information from a DW_TAG_string_type DIE and add to
17145    the user defined type vector.  It isn't really a user defined type,
17146    but it behaves like one, with other DIE's using an AT_user_def_type
17147    attribute to reference it.  */
17148
17149 static struct type *
17150 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17151 {
17152   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17153   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17154   struct type *type, *range_type, *index_type, *char_type;
17155   struct attribute *attr;
17156   unsigned int length;
17157
17158   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17159   if (attr)
17160     {
17161       length = DW_UNSND (attr);
17162     }
17163   else
17164     {
17165       /* Check for the DW_AT_byte_size attribute.  */
17166       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17167       if (attr)
17168         {
17169           length = DW_UNSND (attr);
17170         }
17171       else
17172         {
17173           length = 1;
17174         }
17175     }
17176
17177   index_type = objfile_type (objfile)->builtin_int;
17178   range_type = create_static_range_type (NULL, index_type, 1, length);
17179   char_type = language_string_char_type (cu->language_defn, gdbarch);
17180   type = create_string_type (NULL, char_type, range_type);
17181
17182   return set_die_type (die, type, cu);
17183 }
17184
17185 /* Assuming that DIE corresponds to a function, returns nonzero
17186    if the function is prototyped.  */
17187
17188 static int
17189 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17190 {
17191   struct attribute *attr;
17192
17193   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17194   if (attr && (DW_UNSND (attr) != 0))
17195     return 1;
17196
17197   /* The DWARF standard implies that the DW_AT_prototyped attribute
17198      is only meaninful for C, but the concept also extends to other
17199      languages that allow unprototyped functions (Eg: Objective C).
17200      For all other languages, assume that functions are always
17201      prototyped.  */
17202   if (cu->language != language_c
17203       && cu->language != language_objc
17204       && cu->language != language_opencl)
17205     return 1;
17206
17207   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17208      prototyped and unprototyped functions; default to prototyped,
17209      since that is more common in modern code (and RealView warns
17210      about unprototyped functions).  */
17211   if (producer_is_realview (cu->producer))
17212     return 1;
17213
17214   return 0;
17215 }
17216
17217 /* Handle DIES due to C code like:
17218
17219    struct foo
17220    {
17221    int (*funcp)(int a, long l);
17222    int b;
17223    };
17224
17225    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17226
17227 static struct type *
17228 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17229 {
17230   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17231   struct type *type;            /* Type that this function returns.  */
17232   struct type *ftype;           /* Function that returns above type.  */
17233   struct attribute *attr;
17234
17235   type = die_type (die, cu);
17236
17237   /* The die_type call above may have already set the type for this DIE.  */
17238   ftype = get_die_type (die, cu);
17239   if (ftype)
17240     return ftype;
17241
17242   ftype = lookup_function_type (type);
17243
17244   if (prototyped_function_p (die, cu))
17245     TYPE_PROTOTYPED (ftype) = 1;
17246
17247   /* Store the calling convention in the type if it's available in
17248      the subroutine die.  Otherwise set the calling convention to
17249      the default value DW_CC_normal.  */
17250   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17251   if (attr)
17252     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17253   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17254     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17255   else
17256     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17257
17258   /* Record whether the function returns normally to its caller or not
17259      if the DWARF producer set that information.  */
17260   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17261   if (attr && (DW_UNSND (attr) != 0))
17262     TYPE_NO_RETURN (ftype) = 1;
17263
17264   /* We need to add the subroutine type to the die immediately so
17265      we don't infinitely recurse when dealing with parameters
17266      declared as the same subroutine type.  */
17267   set_die_type (die, ftype, cu);
17268
17269   if (die->child != NULL)
17270     {
17271       struct type *void_type = objfile_type (objfile)->builtin_void;
17272       struct die_info *child_die;
17273       int nparams, iparams;
17274
17275       /* Count the number of parameters.
17276          FIXME: GDB currently ignores vararg functions, but knows about
17277          vararg member functions.  */
17278       nparams = 0;
17279       child_die = die->child;
17280       while (child_die && child_die->tag)
17281         {
17282           if (child_die->tag == DW_TAG_formal_parameter)
17283             nparams++;
17284           else if (child_die->tag == DW_TAG_unspecified_parameters)
17285             TYPE_VARARGS (ftype) = 1;
17286           child_die = sibling_die (child_die);
17287         }
17288
17289       /* Allocate storage for parameters and fill them in.  */
17290       TYPE_NFIELDS (ftype) = nparams;
17291       TYPE_FIELDS (ftype) = (struct field *)
17292         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17293
17294       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17295          even if we error out during the parameters reading below.  */
17296       for (iparams = 0; iparams < nparams; iparams++)
17297         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17298
17299       iparams = 0;
17300       child_die = die->child;
17301       while (child_die && child_die->tag)
17302         {
17303           if (child_die->tag == DW_TAG_formal_parameter)
17304             {
17305               struct type *arg_type;
17306
17307               /* DWARF version 2 has no clean way to discern C++
17308                  static and non-static member functions.  G++ helps
17309                  GDB by marking the first parameter for non-static
17310                  member functions (which is the this pointer) as
17311                  artificial.  We pass this information to
17312                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17313
17314                  DWARF version 3 added DW_AT_object_pointer, which GCC
17315                  4.5 does not yet generate.  */
17316               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17317               if (attr)
17318                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17319               else
17320                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17321               arg_type = die_type (child_die, cu);
17322
17323               /* RealView does not mark THIS as const, which the testsuite
17324                  expects.  GCC marks THIS as const in method definitions,
17325                  but not in the class specifications (GCC PR 43053).  */
17326               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17327                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17328                 {
17329                   int is_this = 0;
17330                   struct dwarf2_cu *arg_cu = cu;
17331                   const char *name = dwarf2_name (child_die, cu);
17332
17333                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17334                   if (attr)
17335                     {
17336                       /* If the compiler emits this, use it.  */
17337                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17338                         is_this = 1;
17339                     }
17340                   else if (name && strcmp (name, "this") == 0)
17341                     /* Function definitions will have the argument names.  */
17342                     is_this = 1;
17343                   else if (name == NULL && iparams == 0)
17344                     /* Declarations may not have the names, so like
17345                        elsewhere in GDB, assume an artificial first
17346                        argument is "this".  */
17347                     is_this = 1;
17348
17349                   if (is_this)
17350                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17351                                              arg_type, 0);
17352                 }
17353
17354               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17355               iparams++;
17356             }
17357           child_die = sibling_die (child_die);
17358         }
17359     }
17360
17361   return ftype;
17362 }
17363
17364 static struct type *
17365 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17366 {
17367   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17368   const char *name = NULL;
17369   struct type *this_type, *target_type;
17370
17371   name = dwarf2_full_name (NULL, die, cu);
17372   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17373   TYPE_TARGET_STUB (this_type) = 1;
17374   set_die_type (die, this_type, cu);
17375   target_type = die_type (die, cu);
17376   if (target_type != this_type)
17377     TYPE_TARGET_TYPE (this_type) = target_type;
17378   else
17379     {
17380       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17381          spec and cause infinite loops in GDB.  */
17382       complaint (_("Self-referential DW_TAG_typedef "
17383                    "- DIE at %s [in module %s]"),
17384                  sect_offset_str (die->sect_off), objfile_name (objfile));
17385       TYPE_TARGET_TYPE (this_type) = NULL;
17386     }
17387   return this_type;
17388 }
17389
17390 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17391    (which may be different from NAME) to the architecture back-end to allow
17392    it to guess the correct format if necessary.  */
17393
17394 static struct type *
17395 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17396                         const char *name_hint)
17397 {
17398   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17399   const struct floatformat **format;
17400   struct type *type;
17401
17402   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17403   if (format)
17404     type = init_float_type (objfile, bits, name, format);
17405   else
17406     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17407
17408   return type;
17409 }
17410
17411 /* Find a representation of a given base type and install
17412    it in the TYPE field of the die.  */
17413
17414 static struct type *
17415 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17416 {
17417   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17418   struct type *type;
17419   struct attribute *attr;
17420   int encoding = 0, bits = 0;
17421   const char *name;
17422
17423   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17424   if (attr)
17425     {
17426       encoding = DW_UNSND (attr);
17427     }
17428   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17429   if (attr)
17430     {
17431       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17432     }
17433   name = dwarf2_name (die, cu);
17434   if (!name)
17435     {
17436       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17437     }
17438
17439   switch (encoding)
17440     {
17441       case DW_ATE_address:
17442         /* Turn DW_ATE_address into a void * pointer.  */
17443         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17444         type = init_pointer_type (objfile, bits, name, type);
17445         break;
17446       case DW_ATE_boolean:
17447         type = init_boolean_type (objfile, bits, 1, name);
17448         break;
17449       case DW_ATE_complex_float:
17450         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17451         type = init_complex_type (objfile, name, type);
17452         break;
17453       case DW_ATE_decimal_float:
17454         type = init_decfloat_type (objfile, bits, name);
17455         break;
17456       case DW_ATE_float:
17457         type = dwarf2_init_float_type (objfile, bits, name, name);
17458         break;
17459       case DW_ATE_signed:
17460         type = init_integer_type (objfile, bits, 0, name);
17461         break;
17462       case DW_ATE_unsigned:
17463         if (cu->language == language_fortran
17464             && name
17465             && startswith (name, "character("))
17466           type = init_character_type (objfile, bits, 1, name);
17467         else
17468           type = init_integer_type (objfile, bits, 1, name);
17469         break;
17470       case DW_ATE_signed_char:
17471         if (cu->language == language_ada || cu->language == language_m2
17472             || cu->language == language_pascal
17473             || cu->language == language_fortran)
17474           type = init_character_type (objfile, bits, 0, name);
17475         else
17476           type = init_integer_type (objfile, bits, 0, name);
17477         break;
17478       case DW_ATE_unsigned_char:
17479         if (cu->language == language_ada || cu->language == language_m2
17480             || cu->language == language_pascal
17481             || cu->language == language_fortran
17482             || cu->language == language_rust)
17483           type = init_character_type (objfile, bits, 1, name);
17484         else
17485           type = init_integer_type (objfile, bits, 1, name);
17486         break;
17487       case DW_ATE_UTF:
17488         {
17489           gdbarch *arch = get_objfile_arch (objfile);
17490
17491           if (bits == 16)
17492             type = builtin_type (arch)->builtin_char16;
17493           else if (bits == 32)
17494             type = builtin_type (arch)->builtin_char32;
17495           else
17496             {
17497               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17498                          bits);
17499               type = init_integer_type (objfile, bits, 1, name);
17500             }
17501           return set_die_type (die, type, cu);
17502         }
17503         break;
17504
17505       default:
17506         complaint (_("unsupported DW_AT_encoding: '%s'"),
17507                    dwarf_type_encoding_name (encoding));
17508         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17509         break;
17510     }
17511
17512   if (name && strcmp (name, "char") == 0)
17513     TYPE_NOSIGN (type) = 1;
17514
17515   maybe_set_alignment (cu, die, type);
17516
17517   return set_die_type (die, type, cu);
17518 }
17519
17520 /* Parse dwarf attribute if it's a block, reference or constant and put the
17521    resulting value of the attribute into struct bound_prop.
17522    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17523
17524 static int
17525 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17526                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17527 {
17528   struct dwarf2_property_baton *baton;
17529   struct obstack *obstack
17530     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17531
17532   if (attr == NULL || prop == NULL)
17533     return 0;
17534
17535   if (attr_form_is_block (attr))
17536     {
17537       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17538       baton->referenced_type = NULL;
17539       baton->locexpr.per_cu = cu->per_cu;
17540       baton->locexpr.size = DW_BLOCK (attr)->size;
17541       baton->locexpr.data = DW_BLOCK (attr)->data;
17542       prop->data.baton = baton;
17543       prop->kind = PROP_LOCEXPR;
17544       gdb_assert (prop->data.baton != NULL);
17545     }
17546   else if (attr_form_is_ref (attr))
17547     {
17548       struct dwarf2_cu *target_cu = cu;
17549       struct die_info *target_die;
17550       struct attribute *target_attr;
17551
17552       target_die = follow_die_ref (die, attr, &target_cu);
17553       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17554       if (target_attr == NULL)
17555         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17556                                    target_cu);
17557       if (target_attr == NULL)
17558         return 0;
17559
17560       switch (target_attr->name)
17561         {
17562           case DW_AT_location:
17563             if (attr_form_is_section_offset (target_attr))
17564               {
17565                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17566                 baton->referenced_type = die_type (target_die, target_cu);
17567                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17568                 prop->data.baton = baton;
17569                 prop->kind = PROP_LOCLIST;
17570                 gdb_assert (prop->data.baton != NULL);
17571               }
17572             else if (attr_form_is_block (target_attr))
17573               {
17574                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17575                 baton->referenced_type = die_type (target_die, target_cu);
17576                 baton->locexpr.per_cu = cu->per_cu;
17577                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17578                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17579                 prop->data.baton = baton;
17580                 prop->kind = PROP_LOCEXPR;
17581                 gdb_assert (prop->data.baton != NULL);
17582               }
17583             else
17584               {
17585                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17586                                                        "dynamic property");
17587                 return 0;
17588               }
17589             break;
17590           case DW_AT_data_member_location:
17591             {
17592               LONGEST offset;
17593
17594               if (!handle_data_member_location (target_die, target_cu,
17595                                                 &offset))
17596                 return 0;
17597
17598               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17599               baton->referenced_type = read_type_die (target_die->parent,
17600                                                       target_cu);
17601               baton->offset_info.offset = offset;
17602               baton->offset_info.type = die_type (target_die, target_cu);
17603               prop->data.baton = baton;
17604               prop->kind = PROP_ADDR_OFFSET;
17605               break;
17606             }
17607         }
17608     }
17609   else if (attr_form_is_constant (attr))
17610     {
17611       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17612       prop->kind = PROP_CONST;
17613     }
17614   else
17615     {
17616       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17617                                              dwarf2_name (die, cu));
17618       return 0;
17619     }
17620
17621   return 1;
17622 }
17623
17624 /* Read the given DW_AT_subrange DIE.  */
17625
17626 static struct type *
17627 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17628 {
17629   struct type *base_type, *orig_base_type;
17630   struct type *range_type;
17631   struct attribute *attr;
17632   struct dynamic_prop low, high;
17633   int low_default_is_valid;
17634   int high_bound_is_count = 0;
17635   const char *name;
17636   LONGEST negative_mask;
17637
17638   orig_base_type = die_type (die, cu);
17639   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17640      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17641      creating the range type, but we use the result of check_typedef
17642      when examining properties of the type.  */
17643   base_type = check_typedef (orig_base_type);
17644
17645   /* The die_type call above may have already set the type for this DIE.  */
17646   range_type = get_die_type (die, cu);
17647   if (range_type)
17648     return range_type;
17649
17650   low.kind = PROP_CONST;
17651   high.kind = PROP_CONST;
17652   high.data.const_val = 0;
17653
17654   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17655      omitting DW_AT_lower_bound.  */
17656   switch (cu->language)
17657     {
17658     case language_c:
17659     case language_cplus:
17660       low.data.const_val = 0;
17661       low_default_is_valid = 1;
17662       break;
17663     case language_fortran:
17664       low.data.const_val = 1;
17665       low_default_is_valid = 1;
17666       break;
17667     case language_d:
17668     case language_objc:
17669     case language_rust:
17670       low.data.const_val = 0;
17671       low_default_is_valid = (cu->header.version >= 4);
17672       break;
17673     case language_ada:
17674     case language_m2:
17675     case language_pascal:
17676       low.data.const_val = 1;
17677       low_default_is_valid = (cu->header.version >= 4);
17678       break;
17679     default:
17680       low.data.const_val = 0;
17681       low_default_is_valid = 0;
17682       break;
17683     }
17684
17685   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17686   if (attr)
17687     attr_to_dynamic_prop (attr, die, cu, &low);
17688   else if (!low_default_is_valid)
17689     complaint (_("Missing DW_AT_lower_bound "
17690                                       "- DIE at %s [in module %s]"),
17691                sect_offset_str (die->sect_off),
17692                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17693
17694   struct attribute *attr_ub, *attr_count;
17695   attr = attr_ub = dwarf2_attr (die, DW_AT_upper_bound, cu);
17696   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17697     {
17698       attr = attr_count = dwarf2_attr (die, DW_AT_count, cu);
17699       if (attr_to_dynamic_prop (attr, die, cu, &high))
17700         {
17701           /* If bounds are constant do the final calculation here.  */
17702           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17703             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17704           else
17705             high_bound_is_count = 1;
17706         }
17707       else
17708         {
17709           if (attr_ub != NULL)
17710             complaint (_("Unresolved DW_AT_upper_bound "
17711                          "- DIE at %s [in module %s]"),
17712                        sect_offset_str (die->sect_off),
17713                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17714           if (attr_count != NULL)
17715             complaint (_("Unresolved DW_AT_count "
17716                          "- DIE at %s [in module %s]"),
17717                        sect_offset_str (die->sect_off),
17718                        objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17719         }
17720         
17721     }
17722
17723   /* Dwarf-2 specifications explicitly allows to create subrange types
17724      without specifying a base type.
17725      In that case, the base type must be set to the type of
17726      the lower bound, upper bound or count, in that order, if any of these
17727      three attributes references an object that has a type.
17728      If no base type is found, the Dwarf-2 specifications say that
17729      a signed integer type of size equal to the size of an address should
17730      be used.
17731      For the following C code: `extern char gdb_int [];'
17732      GCC produces an empty range DIE.
17733      FIXME: muller/2010-05-28: Possible references to object for low bound,
17734      high bound or count are not yet handled by this code.  */
17735   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17736     {
17737       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17738       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17739       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17740       struct type *int_type = objfile_type (objfile)->builtin_int;
17741
17742       /* Test "int", "long int", and "long long int" objfile types,
17743          and select the first one having a size above or equal to the
17744          architecture address size.  */
17745       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17746         base_type = int_type;
17747       else
17748         {
17749           int_type = objfile_type (objfile)->builtin_long;
17750           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17751             base_type = int_type;
17752           else
17753             {
17754               int_type = objfile_type (objfile)->builtin_long_long;
17755               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17756                 base_type = int_type;
17757             }
17758         }
17759     }
17760
17761   /* Normally, the DWARF producers are expected to use a signed
17762      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17763      But this is unfortunately not always the case, as witnessed
17764      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17765      is used instead.  To work around that ambiguity, we treat
17766      the bounds as signed, and thus sign-extend their values, when
17767      the base type is signed.  */
17768   negative_mask =
17769     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17770   if (low.kind == PROP_CONST
17771       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17772     low.data.const_val |= negative_mask;
17773   if (high.kind == PROP_CONST
17774       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17775     high.data.const_val |= negative_mask;
17776
17777   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17778
17779   if (high_bound_is_count)
17780     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17781
17782   /* Ada expects an empty array on no boundary attributes.  */
17783   if (attr == NULL && cu->language != language_ada)
17784     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17785
17786   name = dwarf2_name (die, cu);
17787   if (name)
17788     TYPE_NAME (range_type) = name;
17789
17790   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17791   if (attr)
17792     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17793
17794   maybe_set_alignment (cu, die, range_type);
17795
17796   set_die_type (die, range_type, cu);
17797
17798   /* set_die_type should be already done.  */
17799   set_descriptive_type (range_type, die, cu);
17800
17801   return range_type;
17802 }
17803
17804 static struct type *
17805 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17806 {
17807   struct type *type;
17808
17809   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17810                     NULL);
17811   TYPE_NAME (type) = dwarf2_name (die, cu);
17812
17813   /* In Ada, an unspecified type is typically used when the description
17814      of the type is defered to a different unit.  When encountering
17815      such a type, we treat it as a stub, and try to resolve it later on,
17816      when needed.  */
17817   if (cu->language == language_ada)
17818     TYPE_STUB (type) = 1;
17819
17820   return set_die_type (die, type, cu);
17821 }
17822
17823 /* Read a single die and all its descendents.  Set the die's sibling
17824    field to NULL; set other fields in the die correctly, and set all
17825    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17826    location of the info_ptr after reading all of those dies.  PARENT
17827    is the parent of the die in question.  */
17828
17829 static struct die_info *
17830 read_die_and_children (const struct die_reader_specs *reader,
17831                        const gdb_byte *info_ptr,
17832                        const gdb_byte **new_info_ptr,
17833                        struct die_info *parent)
17834 {
17835   struct die_info *die;
17836   const gdb_byte *cur_ptr;
17837   int has_children;
17838
17839   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17840   if (die == NULL)
17841     {
17842       *new_info_ptr = cur_ptr;
17843       return NULL;
17844     }
17845   store_in_ref_table (die, reader->cu);
17846
17847   if (has_children)
17848     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17849   else
17850     {
17851       die->child = NULL;
17852       *new_info_ptr = cur_ptr;
17853     }
17854
17855   die->sibling = NULL;
17856   die->parent = parent;
17857   return die;
17858 }
17859
17860 /* Read a die, all of its descendents, and all of its siblings; set
17861    all of the fields of all of the dies correctly.  Arguments are as
17862    in read_die_and_children.  */
17863
17864 static struct die_info *
17865 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17866                          const gdb_byte *info_ptr,
17867                          const gdb_byte **new_info_ptr,
17868                          struct die_info *parent)
17869 {
17870   struct die_info *first_die, *last_sibling;
17871   const gdb_byte *cur_ptr;
17872
17873   cur_ptr = info_ptr;
17874   first_die = last_sibling = NULL;
17875
17876   while (1)
17877     {
17878       struct die_info *die
17879         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17880
17881       if (die == NULL)
17882         {
17883           *new_info_ptr = cur_ptr;
17884           return first_die;
17885         }
17886
17887       if (!first_die)
17888         first_die = die;
17889       else
17890         last_sibling->sibling = die;
17891
17892       last_sibling = die;
17893     }
17894 }
17895
17896 /* Read a die, all of its descendents, and all of its siblings; set
17897    all of the fields of all of the dies correctly.  Arguments are as
17898    in read_die_and_children.
17899    This the main entry point for reading a DIE and all its children.  */
17900
17901 static struct die_info *
17902 read_die_and_siblings (const struct die_reader_specs *reader,
17903                        const gdb_byte *info_ptr,
17904                        const gdb_byte **new_info_ptr,
17905                        struct die_info *parent)
17906 {
17907   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17908                                                   new_info_ptr, parent);
17909
17910   if (dwarf_die_debug)
17911     {
17912       fprintf_unfiltered (gdb_stdlog,
17913                           "Read die from %s@0x%x of %s:\n",
17914                           get_section_name (reader->die_section),
17915                           (unsigned) (info_ptr - reader->die_section->buffer),
17916                           bfd_get_filename (reader->abfd));
17917       dump_die (die, dwarf_die_debug);
17918     }
17919
17920   return die;
17921 }
17922
17923 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17924    attributes.
17925    The caller is responsible for filling in the extra attributes
17926    and updating (*DIEP)->num_attrs.
17927    Set DIEP to point to a newly allocated die with its information,
17928    except for its child, sibling, and parent fields.
17929    Set HAS_CHILDREN to tell whether the die has children or not.  */
17930
17931 static const gdb_byte *
17932 read_full_die_1 (const struct die_reader_specs *reader,
17933                  struct die_info **diep, const gdb_byte *info_ptr,
17934                  int *has_children, int num_extra_attrs)
17935 {
17936   unsigned int abbrev_number, bytes_read, i;
17937   struct abbrev_info *abbrev;
17938   struct die_info *die;
17939   struct dwarf2_cu *cu = reader->cu;
17940   bfd *abfd = reader->abfd;
17941
17942   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17943   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17944   info_ptr += bytes_read;
17945   if (!abbrev_number)
17946     {
17947       *diep = NULL;
17948       *has_children = 0;
17949       return info_ptr;
17950     }
17951
17952   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17953   if (!abbrev)
17954     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17955            abbrev_number,
17956            bfd_get_filename (abfd));
17957
17958   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17959   die->sect_off = sect_off;
17960   die->tag = abbrev->tag;
17961   die->abbrev = abbrev_number;
17962
17963   /* Make the result usable.
17964      The caller needs to update num_attrs after adding the extra
17965      attributes.  */
17966   die->num_attrs = abbrev->num_attrs;
17967
17968   for (i = 0; i < abbrev->num_attrs; ++i)
17969     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17970                                info_ptr);
17971
17972   *diep = die;
17973   *has_children = abbrev->has_children;
17974   return info_ptr;
17975 }
17976
17977 /* Read a die and all its attributes.
17978    Set DIEP to point to a newly allocated die with its information,
17979    except for its child, sibling, and parent fields.
17980    Set HAS_CHILDREN to tell whether the die has children or not.  */
17981
17982 static const gdb_byte *
17983 read_full_die (const struct die_reader_specs *reader,
17984                struct die_info **diep, const gdb_byte *info_ptr,
17985                int *has_children)
17986 {
17987   const gdb_byte *result;
17988
17989   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17990
17991   if (dwarf_die_debug)
17992     {
17993       fprintf_unfiltered (gdb_stdlog,
17994                           "Read die from %s@0x%x of %s:\n",
17995                           get_section_name (reader->die_section),
17996                           (unsigned) (info_ptr - reader->die_section->buffer),
17997                           bfd_get_filename (reader->abfd));
17998       dump_die (*diep, dwarf_die_debug);
17999     }
18000
18001   return result;
18002 }
18003 \f
18004 /* Abbreviation tables.
18005
18006    In DWARF version 2, the description of the debugging information is
18007    stored in a separate .debug_abbrev section.  Before we read any
18008    dies from a section we read in all abbreviations and install them
18009    in a hash table.  */
18010
18011 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
18012
18013 struct abbrev_info *
18014 abbrev_table::alloc_abbrev ()
18015 {
18016   struct abbrev_info *abbrev;
18017
18018   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
18019   memset (abbrev, 0, sizeof (struct abbrev_info));
18020
18021   return abbrev;
18022 }
18023
18024 /* Add an abbreviation to the table.  */
18025
18026 void
18027 abbrev_table::add_abbrev (unsigned int abbrev_number,
18028                           struct abbrev_info *abbrev)
18029 {
18030   unsigned int hash_number;
18031
18032   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18033   abbrev->next = m_abbrevs[hash_number];
18034   m_abbrevs[hash_number] = abbrev;
18035 }
18036
18037 /* Look up an abbrev in the table.
18038    Returns NULL if the abbrev is not found.  */
18039
18040 struct abbrev_info *
18041 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
18042 {
18043   unsigned int hash_number;
18044   struct abbrev_info *abbrev;
18045
18046   hash_number = abbrev_number % ABBREV_HASH_SIZE;
18047   abbrev = m_abbrevs[hash_number];
18048
18049   while (abbrev)
18050     {
18051       if (abbrev->number == abbrev_number)
18052         return abbrev;
18053       abbrev = abbrev->next;
18054     }
18055   return NULL;
18056 }
18057
18058 /* Read in an abbrev table.  */
18059
18060 static abbrev_table_up
18061 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
18062                          struct dwarf2_section_info *section,
18063                          sect_offset sect_off)
18064 {
18065   struct objfile *objfile = dwarf2_per_objfile->objfile;
18066   bfd *abfd = get_section_bfd_owner (section);
18067   const gdb_byte *abbrev_ptr;
18068   struct abbrev_info *cur_abbrev;
18069   unsigned int abbrev_number, bytes_read, abbrev_name;
18070   unsigned int abbrev_form;
18071   struct attr_abbrev *cur_attrs;
18072   unsigned int allocated_attrs;
18073
18074   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
18075
18076   dwarf2_read_section (objfile, section);
18077   abbrev_ptr = section->buffer + to_underlying (sect_off);
18078   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18079   abbrev_ptr += bytes_read;
18080
18081   allocated_attrs = ATTR_ALLOC_CHUNK;
18082   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
18083
18084   /* Loop until we reach an abbrev number of 0.  */
18085   while (abbrev_number)
18086     {
18087       cur_abbrev = abbrev_table->alloc_abbrev ();
18088
18089       /* read in abbrev header */
18090       cur_abbrev->number = abbrev_number;
18091       cur_abbrev->tag
18092         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18093       abbrev_ptr += bytes_read;
18094       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
18095       abbrev_ptr += 1;
18096
18097       /* now read in declarations */
18098       for (;;)
18099         {
18100           LONGEST implicit_const;
18101
18102           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18103           abbrev_ptr += bytes_read;
18104           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18105           abbrev_ptr += bytes_read;
18106           if (abbrev_form == DW_FORM_implicit_const)
18107             {
18108               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
18109                                                    &bytes_read);
18110               abbrev_ptr += bytes_read;
18111             }
18112           else
18113             {
18114               /* Initialize it due to a false compiler warning.  */
18115               implicit_const = -1;
18116             }
18117
18118           if (abbrev_name == 0)
18119             break;
18120
18121           if (cur_abbrev->num_attrs == allocated_attrs)
18122             {
18123               allocated_attrs += ATTR_ALLOC_CHUNK;
18124               cur_attrs
18125                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18126             }
18127
18128           cur_attrs[cur_abbrev->num_attrs].name
18129             = (enum dwarf_attribute) abbrev_name;
18130           cur_attrs[cur_abbrev->num_attrs].form
18131             = (enum dwarf_form) abbrev_form;
18132           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18133           ++cur_abbrev->num_attrs;
18134         }
18135
18136       cur_abbrev->attrs =
18137         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18138                    cur_abbrev->num_attrs);
18139       memcpy (cur_abbrev->attrs, cur_attrs,
18140               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18141
18142       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18143
18144       /* Get next abbreviation.
18145          Under Irix6 the abbreviations for a compilation unit are not
18146          always properly terminated with an abbrev number of 0.
18147          Exit loop if we encounter an abbreviation which we have
18148          already read (which means we are about to read the abbreviations
18149          for the next compile unit) or if the end of the abbreviation
18150          table is reached.  */
18151       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18152         break;
18153       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18154       abbrev_ptr += bytes_read;
18155       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18156         break;
18157     }
18158
18159   xfree (cur_attrs);
18160   return abbrev_table;
18161 }
18162
18163 /* Returns nonzero if TAG represents a type that we might generate a partial
18164    symbol for.  */
18165
18166 static int
18167 is_type_tag_for_partial (int tag)
18168 {
18169   switch (tag)
18170     {
18171 #if 0
18172     /* Some types that would be reasonable to generate partial symbols for,
18173        that we don't at present.  */
18174     case DW_TAG_array_type:
18175     case DW_TAG_file_type:
18176     case DW_TAG_ptr_to_member_type:
18177     case DW_TAG_set_type:
18178     case DW_TAG_string_type:
18179     case DW_TAG_subroutine_type:
18180 #endif
18181     case DW_TAG_base_type:
18182     case DW_TAG_class_type:
18183     case DW_TAG_interface_type:
18184     case DW_TAG_enumeration_type:
18185     case DW_TAG_structure_type:
18186     case DW_TAG_subrange_type:
18187     case DW_TAG_typedef:
18188     case DW_TAG_union_type:
18189       return 1;
18190     default:
18191       return 0;
18192     }
18193 }
18194
18195 /* Load all DIEs that are interesting for partial symbols into memory.  */
18196
18197 static struct partial_die_info *
18198 load_partial_dies (const struct die_reader_specs *reader,
18199                    const gdb_byte *info_ptr, int building_psymtab)
18200 {
18201   struct dwarf2_cu *cu = reader->cu;
18202   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18203   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18204   unsigned int bytes_read;
18205   unsigned int load_all = 0;
18206   int nesting_level = 1;
18207
18208   parent_die = NULL;
18209   last_die = NULL;
18210
18211   gdb_assert (cu->per_cu != NULL);
18212   if (cu->per_cu->load_all_dies)
18213     load_all = 1;
18214
18215   cu->partial_dies
18216     = htab_create_alloc_ex (cu->header.length / 12,
18217                             partial_die_hash,
18218                             partial_die_eq,
18219                             NULL,
18220                             &cu->comp_unit_obstack,
18221                             hashtab_obstack_allocate,
18222                             dummy_obstack_deallocate);
18223
18224   while (1)
18225     {
18226       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18227
18228       /* A NULL abbrev means the end of a series of children.  */
18229       if (abbrev == NULL)
18230         {
18231           if (--nesting_level == 0)
18232             return first_die;
18233
18234           info_ptr += bytes_read;
18235           last_die = parent_die;
18236           parent_die = parent_die->die_parent;
18237           continue;
18238         }
18239
18240       /* Check for template arguments.  We never save these; if
18241          they're seen, we just mark the parent, and go on our way.  */
18242       if (parent_die != NULL
18243           && cu->language == language_cplus
18244           && (abbrev->tag == DW_TAG_template_type_param
18245               || abbrev->tag == DW_TAG_template_value_param))
18246         {
18247           parent_die->has_template_arguments = 1;
18248
18249           if (!load_all)
18250             {
18251               /* We don't need a partial DIE for the template argument.  */
18252               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18253               continue;
18254             }
18255         }
18256
18257       /* We only recurse into c++ subprograms looking for template arguments.
18258          Skip their other children.  */
18259       if (!load_all
18260           && cu->language == language_cplus
18261           && parent_die != NULL
18262           && parent_die->tag == DW_TAG_subprogram)
18263         {
18264           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18265           continue;
18266         }
18267
18268       /* Check whether this DIE is interesting enough to save.  Normally
18269          we would not be interested in members here, but there may be
18270          later variables referencing them via DW_AT_specification (for
18271          static members).  */
18272       if (!load_all
18273           && !is_type_tag_for_partial (abbrev->tag)
18274           && abbrev->tag != DW_TAG_constant
18275           && abbrev->tag != DW_TAG_enumerator
18276           && abbrev->tag != DW_TAG_subprogram
18277           && abbrev->tag != DW_TAG_inlined_subroutine
18278           && abbrev->tag != DW_TAG_lexical_block
18279           && abbrev->tag != DW_TAG_variable
18280           && abbrev->tag != DW_TAG_namespace
18281           && abbrev->tag != DW_TAG_module
18282           && abbrev->tag != DW_TAG_member
18283           && abbrev->tag != DW_TAG_imported_unit
18284           && abbrev->tag != DW_TAG_imported_declaration)
18285         {
18286           /* Otherwise we skip to the next sibling, if any.  */
18287           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18288           continue;
18289         }
18290
18291       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18292                                    abbrev);
18293
18294       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18295
18296       /* This two-pass algorithm for processing partial symbols has a
18297          high cost in cache pressure.  Thus, handle some simple cases
18298          here which cover the majority of C partial symbols.  DIEs
18299          which neither have specification tags in them, nor could have
18300          specification tags elsewhere pointing at them, can simply be
18301          processed and discarded.
18302
18303          This segment is also optional; scan_partial_symbols and
18304          add_partial_symbol will handle these DIEs if we chain
18305          them in normally.  When compilers which do not emit large
18306          quantities of duplicate debug information are more common,
18307          this code can probably be removed.  */
18308
18309       /* Any complete simple types at the top level (pretty much all
18310          of them, for a language without namespaces), can be processed
18311          directly.  */
18312       if (parent_die == NULL
18313           && pdi.has_specification == 0
18314           && pdi.is_declaration == 0
18315           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18316               || pdi.tag == DW_TAG_base_type
18317               || pdi.tag == DW_TAG_subrange_type))
18318         {
18319           if (building_psymtab && pdi.name != NULL)
18320             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18321                                  VAR_DOMAIN, LOC_TYPEDEF, -1,
18322                                  &objfile->static_psymbols,
18323                                  0, cu->language, objfile);
18324           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18325           continue;
18326         }
18327
18328       /* The exception for DW_TAG_typedef with has_children above is
18329          a workaround of GCC PR debug/47510.  In the case of this complaint
18330          type_name_or_error will error on such types later.
18331
18332          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18333          it could not find the child DIEs referenced later, this is checked
18334          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18335
18336       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18337         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18338                      "- DIE at %s [in module %s]"),
18339                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18340
18341       /* If we're at the second level, and we're an enumerator, and
18342          our parent has no specification (meaning possibly lives in a
18343          namespace elsewhere), then we can add the partial symbol now
18344          instead of queueing it.  */
18345       if (pdi.tag == DW_TAG_enumerator
18346           && parent_die != NULL
18347           && parent_die->die_parent == NULL
18348           && parent_die->tag == DW_TAG_enumeration_type
18349           && parent_die->has_specification == 0)
18350         {
18351           if (pdi.name == NULL)
18352             complaint (_("malformed enumerator DIE ignored"));
18353           else if (building_psymtab)
18354             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18355                                  VAR_DOMAIN, LOC_CONST, -1,
18356                                  cu->language == language_cplus
18357                                  ? &objfile->global_psymbols
18358                                  : &objfile->static_psymbols,
18359                                  0, cu->language, objfile);
18360
18361           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18362           continue;
18363         }
18364
18365       struct partial_die_info *part_die
18366         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18367
18368       /* We'll save this DIE so link it in.  */
18369       part_die->die_parent = parent_die;
18370       part_die->die_sibling = NULL;
18371       part_die->die_child = NULL;
18372
18373       if (last_die && last_die == parent_die)
18374         last_die->die_child = part_die;
18375       else if (last_die)
18376         last_die->die_sibling = part_die;
18377
18378       last_die = part_die;
18379
18380       if (first_die == NULL)
18381         first_die = part_die;
18382
18383       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18384          find interesting need to be in the hash table, because we
18385          also have the parent/sibling/child chains; only those that we
18386          might refer to by offset later during partial symbol reading.
18387
18388          For now this means things that might have be the target of a
18389          DW_AT_specification, DW_AT_abstract_origin, or
18390          DW_AT_extension.  DW_AT_extension will refer only to
18391          namespaces; DW_AT_abstract_origin refers to functions (and
18392          many things under the function DIE, but we do not recurse
18393          into function DIEs during partial symbol reading) and
18394          possibly variables as well; DW_AT_specification refers to
18395          declarations.  Declarations ought to have the DW_AT_declaration
18396          flag.  It happens that GCC forgets to put it in sometimes, but
18397          only for functions, not for types.
18398
18399          Adding more things than necessary to the hash table is harmless
18400          except for the performance cost.  Adding too few will result in
18401          wasted time in find_partial_die, when we reread the compilation
18402          unit with load_all_dies set.  */
18403
18404       if (load_all
18405           || abbrev->tag == DW_TAG_constant
18406           || abbrev->tag == DW_TAG_subprogram
18407           || abbrev->tag == DW_TAG_variable
18408           || abbrev->tag == DW_TAG_namespace
18409           || part_die->is_declaration)
18410         {
18411           void **slot;
18412
18413           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18414                                            to_underlying (part_die->sect_off),
18415                                            INSERT);
18416           *slot = part_die;
18417         }
18418
18419       /* For some DIEs we want to follow their children (if any).  For C
18420          we have no reason to follow the children of structures; for other
18421          languages we have to, so that we can get at method physnames
18422          to infer fully qualified class names, for DW_AT_specification,
18423          and for C++ template arguments.  For C++, we also look one level
18424          inside functions to find template arguments (if the name of the
18425          function does not already contain the template arguments).
18426
18427          For Ada, we need to scan the children of subprograms and lexical
18428          blocks as well because Ada allows the definition of nested
18429          entities that could be interesting for the debugger, such as
18430          nested subprograms for instance.  */
18431       if (last_die->has_children
18432           && (load_all
18433               || last_die->tag == DW_TAG_namespace
18434               || last_die->tag == DW_TAG_module
18435               || last_die->tag == DW_TAG_enumeration_type
18436               || (cu->language == language_cplus
18437                   && last_die->tag == DW_TAG_subprogram
18438                   && (last_die->name == NULL
18439                       || strchr (last_die->name, '<') == NULL))
18440               || (cu->language != language_c
18441                   && (last_die->tag == DW_TAG_class_type
18442                       || last_die->tag == DW_TAG_interface_type
18443                       || last_die->tag == DW_TAG_structure_type
18444                       || last_die->tag == DW_TAG_union_type))
18445               || (cu->language == language_ada
18446                   && (last_die->tag == DW_TAG_subprogram
18447                       || last_die->tag == DW_TAG_lexical_block))))
18448         {
18449           nesting_level++;
18450           parent_die = last_die;
18451           continue;
18452         }
18453
18454       /* Otherwise we skip to the next sibling, if any.  */
18455       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18456
18457       /* Back to the top, do it again.  */
18458     }
18459 }
18460
18461 partial_die_info::partial_die_info (sect_offset sect_off_,
18462                                     struct abbrev_info *abbrev)
18463   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18464 {
18465 }
18466
18467 /* Read a minimal amount of information into the minimal die structure.
18468    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18469
18470 const gdb_byte *
18471 partial_die_info::read (const struct die_reader_specs *reader,
18472                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18473 {
18474   struct dwarf2_cu *cu = reader->cu;
18475   struct dwarf2_per_objfile *dwarf2_per_objfile
18476     = cu->per_cu->dwarf2_per_objfile;
18477   unsigned int i;
18478   int has_low_pc_attr = 0;
18479   int has_high_pc_attr = 0;
18480   int high_pc_relative = 0;
18481
18482   for (i = 0; i < abbrev.num_attrs; ++i)
18483     {
18484       struct attribute attr;
18485
18486       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18487
18488       /* Store the data if it is of an attribute we want to keep in a
18489          partial symbol table.  */
18490       switch (attr.name)
18491         {
18492         case DW_AT_name:
18493           switch (tag)
18494             {
18495             case DW_TAG_compile_unit:
18496             case DW_TAG_partial_unit:
18497             case DW_TAG_type_unit:
18498               /* Compilation units have a DW_AT_name that is a filename, not
18499                  a source language identifier.  */
18500             case DW_TAG_enumeration_type:
18501             case DW_TAG_enumerator:
18502               /* These tags always have simple identifiers already; no need
18503                  to canonicalize them.  */
18504               name = DW_STRING (&attr);
18505               break;
18506             default:
18507               {
18508                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18509
18510                 name
18511                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18512                                               &objfile->per_bfd->storage_obstack);
18513               }
18514               break;
18515             }
18516           break;
18517         case DW_AT_linkage_name:
18518         case DW_AT_MIPS_linkage_name:
18519           /* Note that both forms of linkage name might appear.  We
18520              assume they will be the same, and we only store the last
18521              one we see.  */
18522           if (cu->language == language_ada)
18523             name = DW_STRING (&attr);
18524           linkage_name = DW_STRING (&attr);
18525           break;
18526         case DW_AT_low_pc:
18527           has_low_pc_attr = 1;
18528           lowpc = attr_value_as_address (&attr);
18529           break;
18530         case DW_AT_high_pc:
18531           has_high_pc_attr = 1;
18532           highpc = attr_value_as_address (&attr);
18533           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18534                 high_pc_relative = 1;
18535           break;
18536         case DW_AT_location:
18537           /* Support the .debug_loc offsets.  */
18538           if (attr_form_is_block (&attr))
18539             {
18540                d.locdesc = DW_BLOCK (&attr);
18541             }
18542           else if (attr_form_is_section_offset (&attr))
18543             {
18544               dwarf2_complex_location_expr_complaint ();
18545             }
18546           else
18547             {
18548               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18549                                                      "partial symbol information");
18550             }
18551           break;
18552         case DW_AT_external:
18553           is_external = DW_UNSND (&attr);
18554           break;
18555         case DW_AT_declaration:
18556           is_declaration = DW_UNSND (&attr);
18557           break;
18558         case DW_AT_type:
18559           has_type = 1;
18560           break;
18561         case DW_AT_abstract_origin:
18562         case DW_AT_specification:
18563         case DW_AT_extension:
18564           has_specification = 1;
18565           spec_offset = dwarf2_get_ref_die_offset (&attr);
18566           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18567                                    || cu->per_cu->is_dwz);
18568           break;
18569         case DW_AT_sibling:
18570           /* Ignore absolute siblings, they might point outside of
18571              the current compile unit.  */
18572           if (attr.form == DW_FORM_ref_addr)
18573             complaint (_("ignoring absolute DW_AT_sibling"));
18574           else
18575             {
18576               const gdb_byte *buffer = reader->buffer;
18577               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18578               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18579
18580               if (sibling_ptr < info_ptr)
18581                 complaint (_("DW_AT_sibling points backwards"));
18582               else if (sibling_ptr > reader->buffer_end)
18583                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18584               else
18585                 sibling = sibling_ptr;
18586             }
18587           break;
18588         case DW_AT_byte_size:
18589           has_byte_size = 1;
18590           break;
18591         case DW_AT_const_value:
18592           has_const_value = 1;
18593           break;
18594         case DW_AT_calling_convention:
18595           /* DWARF doesn't provide a way to identify a program's source-level
18596              entry point.  DW_AT_calling_convention attributes are only meant
18597              to describe functions' calling conventions.
18598
18599              However, because it's a necessary piece of information in
18600              Fortran, and before DWARF 4 DW_CC_program was the only
18601              piece of debugging information whose definition refers to
18602              a 'main program' at all, several compilers marked Fortran
18603              main programs with DW_CC_program --- even when those
18604              functions use the standard calling conventions.
18605
18606              Although DWARF now specifies a way to provide this
18607              information, we support this practice for backward
18608              compatibility.  */
18609           if (DW_UNSND (&attr) == DW_CC_program
18610               && cu->language == language_fortran)
18611             main_subprogram = 1;
18612           break;
18613         case DW_AT_inline:
18614           if (DW_UNSND (&attr) == DW_INL_inlined
18615               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18616             may_be_inlined = 1;
18617           break;
18618
18619         case DW_AT_import:
18620           if (tag == DW_TAG_imported_unit)
18621             {
18622               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18623               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18624                                   || cu->per_cu->is_dwz);
18625             }
18626           break;
18627
18628         case DW_AT_main_subprogram:
18629           main_subprogram = DW_UNSND (&attr);
18630           break;
18631
18632         default:
18633           break;
18634         }
18635     }
18636
18637   if (high_pc_relative)
18638     highpc += lowpc;
18639
18640   if (has_low_pc_attr && has_high_pc_attr)
18641     {
18642       /* When using the GNU linker, .gnu.linkonce. sections are used to
18643          eliminate duplicate copies of functions and vtables and such.
18644          The linker will arbitrarily choose one and discard the others.
18645          The AT_*_pc values for such functions refer to local labels in
18646          these sections.  If the section from that file was discarded, the
18647          labels are not in the output, so the relocs get a value of 0.
18648          If this is a discarded function, mark the pc bounds as invalid,
18649          so that GDB will ignore it.  */
18650       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18651         {
18652           struct objfile *objfile = dwarf2_per_objfile->objfile;
18653           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18654
18655           complaint (_("DW_AT_low_pc %s is zero "
18656                        "for DIE at %s [in module %s]"),
18657                      paddress (gdbarch, lowpc),
18658                      sect_offset_str (sect_off),
18659                      objfile_name (objfile));
18660         }
18661       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18662       else if (lowpc >= highpc)
18663         {
18664           struct objfile *objfile = dwarf2_per_objfile->objfile;
18665           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18666
18667           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18668                        "for DIE at %s [in module %s]"),
18669                      paddress (gdbarch, lowpc),
18670                      paddress (gdbarch, highpc),
18671                      sect_offset_str (sect_off),
18672                      objfile_name (objfile));
18673         }
18674       else
18675         has_pc_info = 1;
18676     }
18677
18678   return info_ptr;
18679 }
18680
18681 /* Find a cached partial DIE at OFFSET in CU.  */
18682
18683 struct partial_die_info *
18684 dwarf2_cu::find_partial_die (sect_offset sect_off)
18685 {
18686   struct partial_die_info *lookup_die = NULL;
18687   struct partial_die_info part_die (sect_off);
18688
18689   lookup_die = ((struct partial_die_info *)
18690                 htab_find_with_hash (partial_dies, &part_die,
18691                                      to_underlying (sect_off)));
18692
18693   return lookup_die;
18694 }
18695
18696 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18697    except in the case of .debug_types DIEs which do not reference
18698    outside their CU (they do however referencing other types via
18699    DW_FORM_ref_sig8).  */
18700
18701 static struct partial_die_info *
18702 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18703 {
18704   struct dwarf2_per_objfile *dwarf2_per_objfile
18705     = cu->per_cu->dwarf2_per_objfile;
18706   struct objfile *objfile = dwarf2_per_objfile->objfile;
18707   struct dwarf2_per_cu_data *per_cu = NULL;
18708   struct partial_die_info *pd = NULL;
18709
18710   if (offset_in_dwz == cu->per_cu->is_dwz
18711       && offset_in_cu_p (&cu->header, sect_off))
18712     {
18713       pd = cu->find_partial_die (sect_off);
18714       if (pd != NULL)
18715         return pd;
18716       /* We missed recording what we needed.
18717          Load all dies and try again.  */
18718       per_cu = cu->per_cu;
18719     }
18720   else
18721     {
18722       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18723       if (cu->per_cu->is_debug_types)
18724         {
18725           error (_("Dwarf Error: Type Unit at offset %s contains"
18726                    " external reference to offset %s [in module %s].\n"),
18727                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18728                  bfd_get_filename (objfile->obfd));
18729         }
18730       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18731                                                  dwarf2_per_objfile);
18732
18733       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18734         load_partial_comp_unit (per_cu);
18735
18736       per_cu->cu->last_used = 0;
18737       pd = per_cu->cu->find_partial_die (sect_off);
18738     }
18739
18740   /* If we didn't find it, and not all dies have been loaded,
18741      load them all and try again.  */
18742
18743   if (pd == NULL && per_cu->load_all_dies == 0)
18744     {
18745       per_cu->load_all_dies = 1;
18746
18747       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18748          THIS_CU->cu may already be in use.  So we can't just free it and
18749          replace its DIEs with the ones we read in.  Instead, we leave those
18750          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18751          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18752          set.  */
18753       load_partial_comp_unit (per_cu);
18754
18755       pd = per_cu->cu->find_partial_die (sect_off);
18756     }
18757
18758   if (pd == NULL)
18759     internal_error (__FILE__, __LINE__,
18760                     _("could not find partial DIE %s "
18761                       "in cache [from module %s]\n"),
18762                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18763   return pd;
18764 }
18765
18766 /* See if we can figure out if the class lives in a namespace.  We do
18767    this by looking for a member function; its demangled name will
18768    contain namespace info, if there is any.  */
18769
18770 static void
18771 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18772                                   struct dwarf2_cu *cu)
18773 {
18774   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18775      what template types look like, because the demangler
18776      frequently doesn't give the same name as the debug info.  We
18777      could fix this by only using the demangled name to get the
18778      prefix (but see comment in read_structure_type).  */
18779
18780   struct partial_die_info *real_pdi;
18781   struct partial_die_info *child_pdi;
18782
18783   /* If this DIE (this DIE's specification, if any) has a parent, then
18784      we should not do this.  We'll prepend the parent's fully qualified
18785      name when we create the partial symbol.  */
18786
18787   real_pdi = struct_pdi;
18788   while (real_pdi->has_specification)
18789     real_pdi = find_partial_die (real_pdi->spec_offset,
18790                                  real_pdi->spec_is_dwz, cu);
18791
18792   if (real_pdi->die_parent != NULL)
18793     return;
18794
18795   for (child_pdi = struct_pdi->die_child;
18796        child_pdi != NULL;
18797        child_pdi = child_pdi->die_sibling)
18798     {
18799       if (child_pdi->tag == DW_TAG_subprogram
18800           && child_pdi->linkage_name != NULL)
18801         {
18802           char *actual_class_name
18803             = language_class_name_from_physname (cu->language_defn,
18804                                                  child_pdi->linkage_name);
18805           if (actual_class_name != NULL)
18806             {
18807               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18808               struct_pdi->name
18809                 = ((const char *)
18810                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18811                                   actual_class_name,
18812                                   strlen (actual_class_name)));
18813               xfree (actual_class_name);
18814             }
18815           break;
18816         }
18817     }
18818 }
18819
18820 void
18821 partial_die_info::fixup (struct dwarf2_cu *cu)
18822 {
18823   /* Once we've fixed up a die, there's no point in doing so again.
18824      This also avoids a memory leak if we were to call
18825      guess_partial_die_structure_name multiple times.  */
18826   if (fixup_called)
18827     return;
18828
18829   /* If we found a reference attribute and the DIE has no name, try
18830      to find a name in the referred to DIE.  */
18831
18832   if (name == NULL && has_specification)
18833     {
18834       struct partial_die_info *spec_die;
18835
18836       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18837
18838       spec_die->fixup (cu);
18839
18840       if (spec_die->name)
18841         {
18842           name = spec_die->name;
18843
18844           /* Copy DW_AT_external attribute if it is set.  */
18845           if (spec_die->is_external)
18846             is_external = spec_die->is_external;
18847         }
18848     }
18849
18850   /* Set default names for some unnamed DIEs.  */
18851
18852   if (name == NULL && tag == DW_TAG_namespace)
18853     name = CP_ANONYMOUS_NAMESPACE_STR;
18854
18855   /* If there is no parent die to provide a namespace, and there are
18856      children, see if we can determine the namespace from their linkage
18857      name.  */
18858   if (cu->language == language_cplus
18859       && !VEC_empty (dwarf2_section_info_def,
18860                      cu->per_cu->dwarf2_per_objfile->types)
18861       && die_parent == NULL
18862       && has_children
18863       && (tag == DW_TAG_class_type
18864           || tag == DW_TAG_structure_type
18865           || tag == DW_TAG_union_type))
18866     guess_partial_die_structure_name (this, cu);
18867
18868   /* GCC might emit a nameless struct or union that has a linkage
18869      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18870   if (name == NULL
18871       && (tag == DW_TAG_class_type
18872           || tag == DW_TAG_interface_type
18873           || tag == DW_TAG_structure_type
18874           || tag == DW_TAG_union_type)
18875       && linkage_name != NULL)
18876     {
18877       char *demangled;
18878
18879       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18880       if (demangled)
18881         {
18882           const char *base;
18883
18884           /* Strip any leading namespaces/classes, keep only the base name.
18885              DW_AT_name for named DIEs does not contain the prefixes.  */
18886           base = strrchr (demangled, ':');
18887           if (base && base > demangled && base[-1] == ':')
18888             base++;
18889           else
18890             base = demangled;
18891
18892           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18893           name
18894             = ((const char *)
18895                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18896                               base, strlen (base)));
18897           xfree (demangled);
18898         }
18899     }
18900
18901   fixup_called = 1;
18902 }
18903
18904 /* Read an attribute value described by an attribute form.  */
18905
18906 static const gdb_byte *
18907 read_attribute_value (const struct die_reader_specs *reader,
18908                       struct attribute *attr, unsigned form,
18909                       LONGEST implicit_const, const gdb_byte *info_ptr)
18910 {
18911   struct dwarf2_cu *cu = reader->cu;
18912   struct dwarf2_per_objfile *dwarf2_per_objfile
18913     = cu->per_cu->dwarf2_per_objfile;
18914   struct objfile *objfile = dwarf2_per_objfile->objfile;
18915   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18916   bfd *abfd = reader->abfd;
18917   struct comp_unit_head *cu_header = &cu->header;
18918   unsigned int bytes_read;
18919   struct dwarf_block *blk;
18920
18921   attr->form = (enum dwarf_form) form;
18922   switch (form)
18923     {
18924     case DW_FORM_ref_addr:
18925       if (cu->header.version == 2)
18926         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18927       else
18928         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18929                                        &cu->header, &bytes_read);
18930       info_ptr += bytes_read;
18931       break;
18932     case DW_FORM_GNU_ref_alt:
18933       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18934       info_ptr += bytes_read;
18935       break;
18936     case DW_FORM_addr:
18937       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18938       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18939       info_ptr += bytes_read;
18940       break;
18941     case DW_FORM_block2:
18942       blk = dwarf_alloc_block (cu);
18943       blk->size = read_2_bytes (abfd, info_ptr);
18944       info_ptr += 2;
18945       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18946       info_ptr += blk->size;
18947       DW_BLOCK (attr) = blk;
18948       break;
18949     case DW_FORM_block4:
18950       blk = dwarf_alloc_block (cu);
18951       blk->size = read_4_bytes (abfd, info_ptr);
18952       info_ptr += 4;
18953       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18954       info_ptr += blk->size;
18955       DW_BLOCK (attr) = blk;
18956       break;
18957     case DW_FORM_data2:
18958       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18959       info_ptr += 2;
18960       break;
18961     case DW_FORM_data4:
18962       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18963       info_ptr += 4;
18964       break;
18965     case DW_FORM_data8:
18966       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18967       info_ptr += 8;
18968       break;
18969     case DW_FORM_data16:
18970       blk = dwarf_alloc_block (cu);
18971       blk->size = 16;
18972       blk->data = read_n_bytes (abfd, info_ptr, 16);
18973       info_ptr += 16;
18974       DW_BLOCK (attr) = blk;
18975       break;
18976     case DW_FORM_sec_offset:
18977       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18978       info_ptr += bytes_read;
18979       break;
18980     case DW_FORM_string:
18981       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18982       DW_STRING_IS_CANONICAL (attr) = 0;
18983       info_ptr += bytes_read;
18984       break;
18985     case DW_FORM_strp:
18986       if (!cu->per_cu->is_dwz)
18987         {
18988           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18989                                                    abfd, info_ptr, cu_header,
18990                                                    &bytes_read);
18991           DW_STRING_IS_CANONICAL (attr) = 0;
18992           info_ptr += bytes_read;
18993           break;
18994         }
18995       /* FALLTHROUGH */
18996     case DW_FORM_line_strp:
18997       if (!cu->per_cu->is_dwz)
18998         {
18999           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
19000                                                         abfd, info_ptr,
19001                                                         cu_header, &bytes_read);
19002           DW_STRING_IS_CANONICAL (attr) = 0;
19003           info_ptr += bytes_read;
19004           break;
19005         }
19006       /* FALLTHROUGH */
19007     case DW_FORM_GNU_strp_alt:
19008       {
19009         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19010         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
19011                                           &bytes_read);
19012
19013         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
19014                                                           dwz, str_offset);
19015         DW_STRING_IS_CANONICAL (attr) = 0;
19016         info_ptr += bytes_read;
19017       }
19018       break;
19019     case DW_FORM_exprloc:
19020     case DW_FORM_block:
19021       blk = dwarf_alloc_block (cu);
19022       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19023       info_ptr += bytes_read;
19024       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19025       info_ptr += blk->size;
19026       DW_BLOCK (attr) = blk;
19027       break;
19028     case DW_FORM_block1:
19029       blk = dwarf_alloc_block (cu);
19030       blk->size = read_1_byte (abfd, info_ptr);
19031       info_ptr += 1;
19032       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
19033       info_ptr += blk->size;
19034       DW_BLOCK (attr) = blk;
19035       break;
19036     case DW_FORM_data1:
19037       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19038       info_ptr += 1;
19039       break;
19040     case DW_FORM_flag:
19041       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
19042       info_ptr += 1;
19043       break;
19044     case DW_FORM_flag_present:
19045       DW_UNSND (attr) = 1;
19046       break;
19047     case DW_FORM_sdata:
19048       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19049       info_ptr += bytes_read;
19050       break;
19051     case DW_FORM_udata:
19052       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19053       info_ptr += bytes_read;
19054       break;
19055     case DW_FORM_ref1:
19056       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19057                          + read_1_byte (abfd, info_ptr));
19058       info_ptr += 1;
19059       break;
19060     case DW_FORM_ref2:
19061       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19062                          + read_2_bytes (abfd, info_ptr));
19063       info_ptr += 2;
19064       break;
19065     case DW_FORM_ref4:
19066       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19067                          + read_4_bytes (abfd, info_ptr));
19068       info_ptr += 4;
19069       break;
19070     case DW_FORM_ref8:
19071       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19072                          + read_8_bytes (abfd, info_ptr));
19073       info_ptr += 8;
19074       break;
19075     case DW_FORM_ref_sig8:
19076       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
19077       info_ptr += 8;
19078       break;
19079     case DW_FORM_ref_udata:
19080       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
19081                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
19082       info_ptr += bytes_read;
19083       break;
19084     case DW_FORM_indirect:
19085       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19086       info_ptr += bytes_read;
19087       if (form == DW_FORM_implicit_const)
19088         {
19089           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
19090           info_ptr += bytes_read;
19091         }
19092       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
19093                                        info_ptr);
19094       break;
19095     case DW_FORM_implicit_const:
19096       DW_SND (attr) = implicit_const;
19097       break;
19098     case DW_FORM_GNU_addr_index:
19099       if (reader->dwo_file == NULL)
19100         {
19101           /* For now flag a hard error.
19102              Later we can turn this into a complaint.  */
19103           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19104                  dwarf_form_name (form),
19105                  bfd_get_filename (abfd));
19106         }
19107       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
19108       info_ptr += bytes_read;
19109       break;
19110     case DW_FORM_GNU_str_index:
19111       if (reader->dwo_file == NULL)
19112         {
19113           /* For now flag a hard error.
19114              Later we can turn this into a complaint if warranted.  */
19115           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19116                  dwarf_form_name (form),
19117                  bfd_get_filename (abfd));
19118         }
19119       {
19120         ULONGEST str_index =
19121           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19122
19123         DW_STRING (attr) = read_str_index (reader, str_index);
19124         DW_STRING_IS_CANONICAL (attr) = 0;
19125         info_ptr += bytes_read;
19126       }
19127       break;
19128     default:
19129       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19130              dwarf_form_name (form),
19131              bfd_get_filename (abfd));
19132     }
19133
19134   /* Super hack.  */
19135   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19136     attr->form = DW_FORM_GNU_ref_alt;
19137
19138   /* We have seen instances where the compiler tried to emit a byte
19139      size attribute of -1 which ended up being encoded as an unsigned
19140      0xffffffff.  Although 0xffffffff is technically a valid size value,
19141      an object of this size seems pretty unlikely so we can relatively
19142      safely treat these cases as if the size attribute was invalid and
19143      treat them as zero by default.  */
19144   if (attr->name == DW_AT_byte_size
19145       && form == DW_FORM_data4
19146       && DW_UNSND (attr) >= 0xffffffff)
19147     {
19148       complaint
19149         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19150          hex_string (DW_UNSND (attr)));
19151       DW_UNSND (attr) = 0;
19152     }
19153
19154   return info_ptr;
19155 }
19156
19157 /* Read an attribute described by an abbreviated attribute.  */
19158
19159 static const gdb_byte *
19160 read_attribute (const struct die_reader_specs *reader,
19161                 struct attribute *attr, struct attr_abbrev *abbrev,
19162                 const gdb_byte *info_ptr)
19163 {
19164   attr->name = abbrev->name;
19165   return read_attribute_value (reader, attr, abbrev->form,
19166                                abbrev->implicit_const, info_ptr);
19167 }
19168
19169 /* Read dwarf information from a buffer.  */
19170
19171 static unsigned int
19172 read_1_byte (bfd *abfd, const gdb_byte *buf)
19173 {
19174   return bfd_get_8 (abfd, buf);
19175 }
19176
19177 static int
19178 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19179 {
19180   return bfd_get_signed_8 (abfd, buf);
19181 }
19182
19183 static unsigned int
19184 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19185 {
19186   return bfd_get_16 (abfd, buf);
19187 }
19188
19189 static int
19190 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19191 {
19192   return bfd_get_signed_16 (abfd, buf);
19193 }
19194
19195 static unsigned int
19196 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19197 {
19198   return bfd_get_32 (abfd, buf);
19199 }
19200
19201 static int
19202 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19203 {
19204   return bfd_get_signed_32 (abfd, buf);
19205 }
19206
19207 static ULONGEST
19208 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19209 {
19210   return bfd_get_64 (abfd, buf);
19211 }
19212
19213 static CORE_ADDR
19214 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19215               unsigned int *bytes_read)
19216 {
19217   struct comp_unit_head *cu_header = &cu->header;
19218   CORE_ADDR retval = 0;
19219
19220   if (cu_header->signed_addr_p)
19221     {
19222       switch (cu_header->addr_size)
19223         {
19224         case 2:
19225           retval = bfd_get_signed_16 (abfd, buf);
19226           break;
19227         case 4:
19228           retval = bfd_get_signed_32 (abfd, buf);
19229           break;
19230         case 8:
19231           retval = bfd_get_signed_64 (abfd, buf);
19232           break;
19233         default:
19234           internal_error (__FILE__, __LINE__,
19235                           _("read_address: bad switch, signed [in module %s]"),
19236                           bfd_get_filename (abfd));
19237         }
19238     }
19239   else
19240     {
19241       switch (cu_header->addr_size)
19242         {
19243         case 2:
19244           retval = bfd_get_16 (abfd, buf);
19245           break;
19246         case 4:
19247           retval = bfd_get_32 (abfd, buf);
19248           break;
19249         case 8:
19250           retval = bfd_get_64 (abfd, buf);
19251           break;
19252         default:
19253           internal_error (__FILE__, __LINE__,
19254                           _("read_address: bad switch, "
19255                             "unsigned [in module %s]"),
19256                           bfd_get_filename (abfd));
19257         }
19258     }
19259
19260   *bytes_read = cu_header->addr_size;
19261   return retval;
19262 }
19263
19264 /* Read the initial length from a section.  The (draft) DWARF 3
19265    specification allows the initial length to take up either 4 bytes
19266    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19267    bytes describe the length and all offsets will be 8 bytes in length
19268    instead of 4.
19269
19270    An older, non-standard 64-bit format is also handled by this
19271    function.  The older format in question stores the initial length
19272    as an 8-byte quantity without an escape value.  Lengths greater
19273    than 2^32 aren't very common which means that the initial 4 bytes
19274    is almost always zero.  Since a length value of zero doesn't make
19275    sense for the 32-bit format, this initial zero can be considered to
19276    be an escape value which indicates the presence of the older 64-bit
19277    format.  As written, the code can't detect (old format) lengths
19278    greater than 4GB.  If it becomes necessary to handle lengths
19279    somewhat larger than 4GB, we could allow other small values (such
19280    as the non-sensical values of 1, 2, and 3) to also be used as
19281    escape values indicating the presence of the old format.
19282
19283    The value returned via bytes_read should be used to increment the
19284    relevant pointer after calling read_initial_length().
19285
19286    [ Note:  read_initial_length() and read_offset() are based on the
19287      document entitled "DWARF Debugging Information Format", revision
19288      3, draft 8, dated November 19, 2001.  This document was obtained
19289      from:
19290
19291         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19292
19293      This document is only a draft and is subject to change.  (So beware.)
19294
19295      Details regarding the older, non-standard 64-bit format were
19296      determined empirically by examining 64-bit ELF files produced by
19297      the SGI toolchain on an IRIX 6.5 machine.
19298
19299      - Kevin, July 16, 2002
19300    ] */
19301
19302 static LONGEST
19303 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19304 {
19305   LONGEST length = bfd_get_32 (abfd, buf);
19306
19307   if (length == 0xffffffff)
19308     {
19309       length = bfd_get_64 (abfd, buf + 4);
19310       *bytes_read = 12;
19311     }
19312   else if (length == 0)
19313     {
19314       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19315       length = bfd_get_64 (abfd, buf);
19316       *bytes_read = 8;
19317     }
19318   else
19319     {
19320       *bytes_read = 4;
19321     }
19322
19323   return length;
19324 }
19325
19326 /* Cover function for read_initial_length.
19327    Returns the length of the object at BUF, and stores the size of the
19328    initial length in *BYTES_READ and stores the size that offsets will be in
19329    *OFFSET_SIZE.
19330    If the initial length size is not equivalent to that specified in
19331    CU_HEADER then issue a complaint.
19332    This is useful when reading non-comp-unit headers.  */
19333
19334 static LONGEST
19335 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19336                                         const struct comp_unit_head *cu_header,
19337                                         unsigned int *bytes_read,
19338                                         unsigned int *offset_size)
19339 {
19340   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19341
19342   gdb_assert (cu_header->initial_length_size == 4
19343               || cu_header->initial_length_size == 8
19344               || cu_header->initial_length_size == 12);
19345
19346   if (cu_header->initial_length_size != *bytes_read)
19347     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19348
19349   *offset_size = (*bytes_read == 4) ? 4 : 8;
19350   return length;
19351 }
19352
19353 /* Read an offset from the data stream.  The size of the offset is
19354    given by cu_header->offset_size.  */
19355
19356 static LONGEST
19357 read_offset (bfd *abfd, const gdb_byte *buf,
19358              const struct comp_unit_head *cu_header,
19359              unsigned int *bytes_read)
19360 {
19361   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19362
19363   *bytes_read = cu_header->offset_size;
19364   return offset;
19365 }
19366
19367 /* Read an offset from the data stream.  */
19368
19369 static LONGEST
19370 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19371 {
19372   LONGEST retval = 0;
19373
19374   switch (offset_size)
19375     {
19376     case 4:
19377       retval = bfd_get_32 (abfd, buf);
19378       break;
19379     case 8:
19380       retval = bfd_get_64 (abfd, buf);
19381       break;
19382     default:
19383       internal_error (__FILE__, __LINE__,
19384                       _("read_offset_1: bad switch [in module %s]"),
19385                       bfd_get_filename (abfd));
19386     }
19387
19388   return retval;
19389 }
19390
19391 static const gdb_byte *
19392 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19393 {
19394   /* If the size of a host char is 8 bits, we can return a pointer
19395      to the buffer, otherwise we have to copy the data to a buffer
19396      allocated on the temporary obstack.  */
19397   gdb_assert (HOST_CHAR_BIT == 8);
19398   return buf;
19399 }
19400
19401 static const char *
19402 read_direct_string (bfd *abfd, const gdb_byte *buf,
19403                     unsigned int *bytes_read_ptr)
19404 {
19405   /* If the size of a host char is 8 bits, we can return a pointer
19406      to the string, otherwise we have to copy the string to a buffer
19407      allocated on the temporary obstack.  */
19408   gdb_assert (HOST_CHAR_BIT == 8);
19409   if (*buf == '\0')
19410     {
19411       *bytes_read_ptr = 1;
19412       return NULL;
19413     }
19414   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19415   return (const char *) buf;
19416 }
19417
19418 /* Return pointer to string at section SECT offset STR_OFFSET with error
19419    reporting strings FORM_NAME and SECT_NAME.  */
19420
19421 static const char *
19422 read_indirect_string_at_offset_from (struct objfile *objfile,
19423                                      bfd *abfd, LONGEST str_offset,
19424                                      struct dwarf2_section_info *sect,
19425                                      const char *form_name,
19426                                      const char *sect_name)
19427 {
19428   dwarf2_read_section (objfile, sect);
19429   if (sect->buffer == NULL)
19430     error (_("%s used without %s section [in module %s]"),
19431            form_name, sect_name, bfd_get_filename (abfd));
19432   if (str_offset >= sect->size)
19433     error (_("%s pointing outside of %s section [in module %s]"),
19434            form_name, sect_name, bfd_get_filename (abfd));
19435   gdb_assert (HOST_CHAR_BIT == 8);
19436   if (sect->buffer[str_offset] == '\0')
19437     return NULL;
19438   return (const char *) (sect->buffer + str_offset);
19439 }
19440
19441 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19442
19443 static const char *
19444 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19445                                 bfd *abfd, LONGEST str_offset)
19446 {
19447   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19448                                               abfd, str_offset,
19449                                               &dwarf2_per_objfile->str,
19450                                               "DW_FORM_strp", ".debug_str");
19451 }
19452
19453 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19454
19455 static const char *
19456 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19457                                      bfd *abfd, LONGEST str_offset)
19458 {
19459   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19460                                               abfd, str_offset,
19461                                               &dwarf2_per_objfile->line_str,
19462                                               "DW_FORM_line_strp",
19463                                               ".debug_line_str");
19464 }
19465
19466 /* Read a string at offset STR_OFFSET in the .debug_str section from
19467    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19468    the string consists of a single NUL byte, return NULL; otherwise
19469    return a pointer to the string.  */
19470
19471 static const char *
19472 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19473                                LONGEST str_offset)
19474 {
19475   dwarf2_read_section (objfile, &dwz->str);
19476
19477   if (dwz->str.buffer == NULL)
19478     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19479              "section [in module %s]"),
19480            bfd_get_filename (dwz->dwz_bfd));
19481   if (str_offset >= dwz->str.size)
19482     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19483              ".debug_str section [in module %s]"),
19484            bfd_get_filename (dwz->dwz_bfd));
19485   gdb_assert (HOST_CHAR_BIT == 8);
19486   if (dwz->str.buffer[str_offset] == '\0')
19487     return NULL;
19488   return (const char *) (dwz->str.buffer + str_offset);
19489 }
19490
19491 /* Return pointer to string at .debug_str offset as read from BUF.
19492    BUF is assumed to be in a compilation unit described by CU_HEADER.
19493    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19494
19495 static const char *
19496 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19497                       const gdb_byte *buf,
19498                       const struct comp_unit_head *cu_header,
19499                       unsigned int *bytes_read_ptr)
19500 {
19501   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19502
19503   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19504 }
19505
19506 /* Return pointer to string at .debug_line_str offset as read from BUF.
19507    BUF is assumed to be in a compilation unit described by CU_HEADER.
19508    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19509
19510 static const char *
19511 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19512                            bfd *abfd, const gdb_byte *buf,
19513                            const struct comp_unit_head *cu_header,
19514                            unsigned int *bytes_read_ptr)
19515 {
19516   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19517
19518   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19519                                               str_offset);
19520 }
19521
19522 ULONGEST
19523 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19524                           unsigned int *bytes_read_ptr)
19525 {
19526   ULONGEST result;
19527   unsigned int num_read;
19528   int shift;
19529   unsigned char byte;
19530
19531   result = 0;
19532   shift = 0;
19533   num_read = 0;
19534   while (1)
19535     {
19536       byte = bfd_get_8 (abfd, buf);
19537       buf++;
19538       num_read++;
19539       result |= ((ULONGEST) (byte & 127) << shift);
19540       if ((byte & 128) == 0)
19541         {
19542           break;
19543         }
19544       shift += 7;
19545     }
19546   *bytes_read_ptr = num_read;
19547   return result;
19548 }
19549
19550 static LONGEST
19551 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19552                     unsigned int *bytes_read_ptr)
19553 {
19554   LONGEST result;
19555   int shift, num_read;
19556   unsigned char byte;
19557
19558   result = 0;
19559   shift = 0;
19560   num_read = 0;
19561   while (1)
19562     {
19563       byte = bfd_get_8 (abfd, buf);
19564       buf++;
19565       num_read++;
19566       result |= ((LONGEST) (byte & 127) << shift);
19567       shift += 7;
19568       if ((byte & 128) == 0)
19569         {
19570           break;
19571         }
19572     }
19573   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19574     result |= -(((LONGEST) 1) << shift);
19575   *bytes_read_ptr = num_read;
19576   return result;
19577 }
19578
19579 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19580    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19581    ADDR_SIZE is the size of addresses from the CU header.  */
19582
19583 static CORE_ADDR
19584 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19585                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19586 {
19587   struct objfile *objfile = dwarf2_per_objfile->objfile;
19588   bfd *abfd = objfile->obfd;
19589   const gdb_byte *info_ptr;
19590
19591   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19592   if (dwarf2_per_objfile->addr.buffer == NULL)
19593     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19594            objfile_name (objfile));
19595   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19596     error (_("DW_FORM_addr_index pointing outside of "
19597              ".debug_addr section [in module %s]"),
19598            objfile_name (objfile));
19599   info_ptr = (dwarf2_per_objfile->addr.buffer
19600               + addr_base + addr_index * addr_size);
19601   if (addr_size == 4)
19602     return bfd_get_32 (abfd, info_ptr);
19603   else
19604     return bfd_get_64 (abfd, info_ptr);
19605 }
19606
19607 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19608
19609 static CORE_ADDR
19610 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19611 {
19612   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19613                             cu->addr_base, cu->header.addr_size);
19614 }
19615
19616 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19617
19618 static CORE_ADDR
19619 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19620                              unsigned int *bytes_read)
19621 {
19622   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19623   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19624
19625   return read_addr_index (cu, addr_index);
19626 }
19627
19628 /* Data structure to pass results from dwarf2_read_addr_index_reader
19629    back to dwarf2_read_addr_index.  */
19630
19631 struct dwarf2_read_addr_index_data
19632 {
19633   ULONGEST addr_base;
19634   int addr_size;
19635 };
19636
19637 /* die_reader_func for dwarf2_read_addr_index.  */
19638
19639 static void
19640 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19641                                const gdb_byte *info_ptr,
19642                                struct die_info *comp_unit_die,
19643                                int has_children,
19644                                void *data)
19645 {
19646   struct dwarf2_cu *cu = reader->cu;
19647   struct dwarf2_read_addr_index_data *aidata =
19648     (struct dwarf2_read_addr_index_data *) data;
19649
19650   aidata->addr_base = cu->addr_base;
19651   aidata->addr_size = cu->header.addr_size;
19652 }
19653
19654 /* Given an index in .debug_addr, fetch the value.
19655    NOTE: This can be called during dwarf expression evaluation,
19656    long after the debug information has been read, and thus per_cu->cu
19657    may no longer exist.  */
19658
19659 CORE_ADDR
19660 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19661                         unsigned int addr_index)
19662 {
19663   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19664   struct dwarf2_cu *cu = per_cu->cu;
19665   ULONGEST addr_base;
19666   int addr_size;
19667
19668   /* We need addr_base and addr_size.
19669      If we don't have PER_CU->cu, we have to get it.
19670      Nasty, but the alternative is storing the needed info in PER_CU,
19671      which at this point doesn't seem justified: it's not clear how frequently
19672      it would get used and it would increase the size of every PER_CU.
19673      Entry points like dwarf2_per_cu_addr_size do a similar thing
19674      so we're not in uncharted territory here.
19675      Alas we need to be a bit more complicated as addr_base is contained
19676      in the DIE.
19677
19678      We don't need to read the entire CU(/TU).
19679      We just need the header and top level die.
19680
19681      IWBN to use the aging mechanism to let us lazily later discard the CU.
19682      For now we skip this optimization.  */
19683
19684   if (cu != NULL)
19685     {
19686       addr_base = cu->addr_base;
19687       addr_size = cu->header.addr_size;
19688     }
19689   else
19690     {
19691       struct dwarf2_read_addr_index_data aidata;
19692
19693       /* Note: We can't use init_cutu_and_read_dies_simple here,
19694          we need addr_base.  */
19695       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19696                                dwarf2_read_addr_index_reader, &aidata);
19697       addr_base = aidata.addr_base;
19698       addr_size = aidata.addr_size;
19699     }
19700
19701   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19702                             addr_size);
19703 }
19704
19705 /* Given a DW_FORM_GNU_str_index, fetch the string.
19706    This is only used by the Fission support.  */
19707
19708 static const char *
19709 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19710 {
19711   struct dwarf2_cu *cu = reader->cu;
19712   struct dwarf2_per_objfile *dwarf2_per_objfile
19713     = cu->per_cu->dwarf2_per_objfile;
19714   struct objfile *objfile = dwarf2_per_objfile->objfile;
19715   const char *objf_name = objfile_name (objfile);
19716   bfd *abfd = objfile->obfd;
19717   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19718   struct dwarf2_section_info *str_offsets_section =
19719     &reader->dwo_file->sections.str_offsets;
19720   const gdb_byte *info_ptr;
19721   ULONGEST str_offset;
19722   static const char form_name[] = "DW_FORM_GNU_str_index";
19723
19724   dwarf2_read_section (objfile, str_section);
19725   dwarf2_read_section (objfile, str_offsets_section);
19726   if (str_section->buffer == NULL)
19727     error (_("%s used without .debug_str.dwo section"
19728              " in CU at offset %s [in module %s]"),
19729            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19730   if (str_offsets_section->buffer == NULL)
19731     error (_("%s used without .debug_str_offsets.dwo section"
19732              " in CU at offset %s [in module %s]"),
19733            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19734   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19735     error (_("%s pointing outside of .debug_str_offsets.dwo"
19736              " section in CU at offset %s [in module %s]"),
19737            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19738   info_ptr = (str_offsets_section->buffer
19739               + str_index * cu->header.offset_size);
19740   if (cu->header.offset_size == 4)
19741     str_offset = bfd_get_32 (abfd, info_ptr);
19742   else
19743     str_offset = bfd_get_64 (abfd, info_ptr);
19744   if (str_offset >= str_section->size)
19745     error (_("Offset from %s pointing outside of"
19746              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19747            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19748   return (const char *) (str_section->buffer + str_offset);
19749 }
19750
19751 /* Return the length of an LEB128 number in BUF.  */
19752
19753 static int
19754 leb128_size (const gdb_byte *buf)
19755 {
19756   const gdb_byte *begin = buf;
19757   gdb_byte byte;
19758
19759   while (1)
19760     {
19761       byte = *buf++;
19762       if ((byte & 128) == 0)
19763         return buf - begin;
19764     }
19765 }
19766
19767 static void
19768 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19769 {
19770   switch (lang)
19771     {
19772     case DW_LANG_C89:
19773     case DW_LANG_C99:
19774     case DW_LANG_C11:
19775     case DW_LANG_C:
19776     case DW_LANG_UPC:
19777       cu->language = language_c;
19778       break;
19779     case DW_LANG_Java:
19780     case DW_LANG_C_plus_plus:
19781     case DW_LANG_C_plus_plus_11:
19782     case DW_LANG_C_plus_plus_14:
19783       cu->language = language_cplus;
19784       break;
19785     case DW_LANG_D:
19786       cu->language = language_d;
19787       break;
19788     case DW_LANG_Fortran77:
19789     case DW_LANG_Fortran90:
19790     case DW_LANG_Fortran95:
19791     case DW_LANG_Fortran03:
19792     case DW_LANG_Fortran08:
19793       cu->language = language_fortran;
19794       break;
19795     case DW_LANG_Go:
19796       cu->language = language_go;
19797       break;
19798     case DW_LANG_Mips_Assembler:
19799       cu->language = language_asm;
19800       break;
19801     case DW_LANG_Ada83:
19802     case DW_LANG_Ada95:
19803       cu->language = language_ada;
19804       break;
19805     case DW_LANG_Modula2:
19806       cu->language = language_m2;
19807       break;
19808     case DW_LANG_Pascal83:
19809       cu->language = language_pascal;
19810       break;
19811     case DW_LANG_ObjC:
19812       cu->language = language_objc;
19813       break;
19814     case DW_LANG_Rust:
19815     case DW_LANG_Rust_old:
19816       cu->language = language_rust;
19817       break;
19818     case DW_LANG_Cobol74:
19819     case DW_LANG_Cobol85:
19820     default:
19821       cu->language = language_minimal;
19822       break;
19823     }
19824   cu->language_defn = language_def (cu->language);
19825 }
19826
19827 /* Return the named attribute or NULL if not there.  */
19828
19829 static struct attribute *
19830 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19831 {
19832   for (;;)
19833     {
19834       unsigned int i;
19835       struct attribute *spec = NULL;
19836
19837       for (i = 0; i < die->num_attrs; ++i)
19838         {
19839           if (die->attrs[i].name == name)
19840             return &die->attrs[i];
19841           if (die->attrs[i].name == DW_AT_specification
19842               || die->attrs[i].name == DW_AT_abstract_origin)
19843             spec = &die->attrs[i];
19844         }
19845
19846       if (!spec)
19847         break;
19848
19849       die = follow_die_ref (die, spec, &cu);
19850     }
19851
19852   return NULL;
19853 }
19854
19855 /* Return the named attribute or NULL if not there,
19856    but do not follow DW_AT_specification, etc.
19857    This is for use in contexts where we're reading .debug_types dies.
19858    Following DW_AT_specification, DW_AT_abstract_origin will take us
19859    back up the chain, and we want to go down.  */
19860
19861 static struct attribute *
19862 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19863 {
19864   unsigned int i;
19865
19866   for (i = 0; i < die->num_attrs; ++i)
19867     if (die->attrs[i].name == name)
19868       return &die->attrs[i];
19869
19870   return NULL;
19871 }
19872
19873 /* Return the string associated with a string-typed attribute, or NULL if it
19874    is either not found or is of an incorrect type.  */
19875
19876 static const char *
19877 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19878 {
19879   struct attribute *attr;
19880   const char *str = NULL;
19881
19882   attr = dwarf2_attr (die, name, cu);
19883
19884   if (attr != NULL)
19885     {
19886       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19887           || attr->form == DW_FORM_string
19888           || attr->form == DW_FORM_GNU_str_index
19889           || attr->form == DW_FORM_GNU_strp_alt)
19890         str = DW_STRING (attr);
19891       else
19892         complaint (_("string type expected for attribute %s for "
19893                      "DIE at %s in module %s"),
19894                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19895                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19896     }
19897
19898   return str;
19899 }
19900
19901 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19902    and holds a non-zero value.  This function should only be used for
19903    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19904
19905 static int
19906 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19907 {
19908   struct attribute *attr = dwarf2_attr (die, name, cu);
19909
19910   return (attr && DW_UNSND (attr));
19911 }
19912
19913 static int
19914 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19915 {
19916   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19917      which value is non-zero.  However, we have to be careful with
19918      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19919      (via dwarf2_flag_true_p) follows this attribute.  So we may
19920      end up accidently finding a declaration attribute that belongs
19921      to a different DIE referenced by the specification attribute,
19922      even though the given DIE does not have a declaration attribute.  */
19923   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19924           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19925 }
19926
19927 /* Return the die giving the specification for DIE, if there is
19928    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19929    containing the return value on output.  If there is no
19930    specification, but there is an abstract origin, that is
19931    returned.  */
19932
19933 static struct die_info *
19934 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19935 {
19936   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19937                                              *spec_cu);
19938
19939   if (spec_attr == NULL)
19940     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19941
19942   if (spec_attr == NULL)
19943     return NULL;
19944   else
19945     return follow_die_ref (die, spec_attr, spec_cu);
19946 }
19947
19948 /* Stub for free_line_header to match void * callback types.  */
19949
19950 static void
19951 free_line_header_voidp (void *arg)
19952 {
19953   struct line_header *lh = (struct line_header *) arg;
19954
19955   delete lh;
19956 }
19957
19958 void
19959 line_header::add_include_dir (const char *include_dir)
19960 {
19961   if (dwarf_line_debug >= 2)
19962     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19963                         include_dirs.size () + 1, include_dir);
19964
19965   include_dirs.push_back (include_dir);
19966 }
19967
19968 void
19969 line_header::add_file_name (const char *name,
19970                             dir_index d_index,
19971                             unsigned int mod_time,
19972                             unsigned int length)
19973 {
19974   if (dwarf_line_debug >= 2)
19975     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19976                         (unsigned) file_names.size () + 1, name);
19977
19978   file_names.emplace_back (name, d_index, mod_time, length);
19979 }
19980
19981 /* A convenience function to find the proper .debug_line section for a CU.  */
19982
19983 static struct dwarf2_section_info *
19984 get_debug_line_section (struct dwarf2_cu *cu)
19985 {
19986   struct dwarf2_section_info *section;
19987   struct dwarf2_per_objfile *dwarf2_per_objfile
19988     = cu->per_cu->dwarf2_per_objfile;
19989
19990   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19991      DWO file.  */
19992   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19993     section = &cu->dwo_unit->dwo_file->sections.line;
19994   else if (cu->per_cu->is_dwz)
19995     {
19996       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19997
19998       section = &dwz->line;
19999     }
20000   else
20001     section = &dwarf2_per_objfile->line;
20002
20003   return section;
20004 }
20005
20006 /* Read directory or file name entry format, starting with byte of
20007    format count entries, ULEB128 pairs of entry formats, ULEB128 of
20008    entries count and the entries themselves in the described entry
20009    format.  */
20010
20011 static void
20012 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
20013                         bfd *abfd, const gdb_byte **bufp,
20014                         struct line_header *lh,
20015                         const struct comp_unit_head *cu_header,
20016                         void (*callback) (struct line_header *lh,
20017                                           const char *name,
20018                                           dir_index d_index,
20019                                           unsigned int mod_time,
20020                                           unsigned int length))
20021 {
20022   gdb_byte format_count, formati;
20023   ULONGEST data_count, datai;
20024   const gdb_byte *buf = *bufp;
20025   const gdb_byte *format_header_data;
20026   unsigned int bytes_read;
20027
20028   format_count = read_1_byte (abfd, buf);
20029   buf += 1;
20030   format_header_data = buf;
20031   for (formati = 0; formati < format_count; formati++)
20032     {
20033       read_unsigned_leb128 (abfd, buf, &bytes_read);
20034       buf += bytes_read;
20035       read_unsigned_leb128 (abfd, buf, &bytes_read);
20036       buf += bytes_read;
20037     }
20038
20039   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
20040   buf += bytes_read;
20041   for (datai = 0; datai < data_count; datai++)
20042     {
20043       const gdb_byte *format = format_header_data;
20044       struct file_entry fe;
20045
20046       for (formati = 0; formati < format_count; formati++)
20047         {
20048           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
20049           format += bytes_read;
20050
20051           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
20052           format += bytes_read;
20053
20054           gdb::optional<const char *> string;
20055           gdb::optional<unsigned int> uint;
20056
20057           switch (form)
20058             {
20059             case DW_FORM_string:
20060               string.emplace (read_direct_string (abfd, buf, &bytes_read));
20061               buf += bytes_read;
20062               break;
20063
20064             case DW_FORM_line_strp:
20065               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
20066                                                          abfd, buf,
20067                                                          cu_header,
20068                                                          &bytes_read));
20069               buf += bytes_read;
20070               break;
20071
20072             case DW_FORM_data1:
20073               uint.emplace (read_1_byte (abfd, buf));
20074               buf += 1;
20075               break;
20076
20077             case DW_FORM_data2:
20078               uint.emplace (read_2_bytes (abfd, buf));
20079               buf += 2;
20080               break;
20081
20082             case DW_FORM_data4:
20083               uint.emplace (read_4_bytes (abfd, buf));
20084               buf += 4;
20085               break;
20086
20087             case DW_FORM_data8:
20088               uint.emplace (read_8_bytes (abfd, buf));
20089               buf += 8;
20090               break;
20091
20092             case DW_FORM_udata:
20093               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
20094               buf += bytes_read;
20095               break;
20096
20097             case DW_FORM_block:
20098               /* It is valid only for DW_LNCT_timestamp which is ignored by
20099                  current GDB.  */
20100               break;
20101             }
20102
20103           switch (content_type)
20104             {
20105             case DW_LNCT_path:
20106               if (string.has_value ())
20107                 fe.name = *string;
20108               break;
20109             case DW_LNCT_directory_index:
20110               if (uint.has_value ())
20111                 fe.d_index = (dir_index) *uint;
20112               break;
20113             case DW_LNCT_timestamp:
20114               if (uint.has_value ())
20115                 fe.mod_time = *uint;
20116               break;
20117             case DW_LNCT_size:
20118               if (uint.has_value ())
20119                 fe.length = *uint;
20120               break;
20121             case DW_LNCT_MD5:
20122               break;
20123             default:
20124               complaint (_("Unknown format content type %s"),
20125                          pulongest (content_type));
20126             }
20127         }
20128
20129       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20130     }
20131
20132   *bufp = buf;
20133 }
20134
20135 /* Read the statement program header starting at OFFSET in
20136    .debug_line, or .debug_line.dwo.  Return a pointer
20137    to a struct line_header, allocated using xmalloc.
20138    Returns NULL if there is a problem reading the header, e.g., if it
20139    has a version we don't understand.
20140
20141    NOTE: the strings in the include directory and file name tables of
20142    the returned object point into the dwarf line section buffer,
20143    and must not be freed.  */
20144
20145 static line_header_up
20146 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20147 {
20148   const gdb_byte *line_ptr;
20149   unsigned int bytes_read, offset_size;
20150   int i;
20151   const char *cur_dir, *cur_file;
20152   struct dwarf2_section_info *section;
20153   bfd *abfd;
20154   struct dwarf2_per_objfile *dwarf2_per_objfile
20155     = cu->per_cu->dwarf2_per_objfile;
20156
20157   section = get_debug_line_section (cu);
20158   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20159   if (section->buffer == NULL)
20160     {
20161       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20162         complaint (_("missing .debug_line.dwo section"));
20163       else
20164         complaint (_("missing .debug_line section"));
20165       return 0;
20166     }
20167
20168   /* We can't do this until we know the section is non-empty.
20169      Only then do we know we have such a section.  */
20170   abfd = get_section_bfd_owner (section);
20171
20172   /* Make sure that at least there's room for the total_length field.
20173      That could be 12 bytes long, but we're just going to fudge that.  */
20174   if (to_underlying (sect_off) + 4 >= section->size)
20175     {
20176       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20177       return 0;
20178     }
20179
20180   line_header_up lh (new line_header ());
20181
20182   lh->sect_off = sect_off;
20183   lh->offset_in_dwz = cu->per_cu->is_dwz;
20184
20185   line_ptr = section->buffer + to_underlying (sect_off);
20186
20187   /* Read in the header.  */
20188   lh->total_length =
20189     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20190                                             &bytes_read, &offset_size);
20191   line_ptr += bytes_read;
20192   if (line_ptr + lh->total_length > (section->buffer + section->size))
20193     {
20194       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20195       return 0;
20196     }
20197   lh->statement_program_end = line_ptr + lh->total_length;
20198   lh->version = read_2_bytes (abfd, line_ptr);
20199   line_ptr += 2;
20200   if (lh->version > 5)
20201     {
20202       /* This is a version we don't understand.  The format could have
20203          changed in ways we don't handle properly so just punt.  */
20204       complaint (_("unsupported version in .debug_line section"));
20205       return NULL;
20206     }
20207   if (lh->version >= 5)
20208     {
20209       gdb_byte segment_selector_size;
20210
20211       /* Skip address size.  */
20212       read_1_byte (abfd, line_ptr);
20213       line_ptr += 1;
20214
20215       segment_selector_size = read_1_byte (abfd, line_ptr);
20216       line_ptr += 1;
20217       if (segment_selector_size != 0)
20218         {
20219           complaint (_("unsupported segment selector size %u "
20220                        "in .debug_line section"),
20221                      segment_selector_size);
20222           return NULL;
20223         }
20224     }
20225   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20226   line_ptr += offset_size;
20227   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20228   line_ptr += 1;
20229   if (lh->version >= 4)
20230     {
20231       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20232       line_ptr += 1;
20233     }
20234   else
20235     lh->maximum_ops_per_instruction = 1;
20236
20237   if (lh->maximum_ops_per_instruction == 0)
20238     {
20239       lh->maximum_ops_per_instruction = 1;
20240       complaint (_("invalid maximum_ops_per_instruction "
20241                    "in `.debug_line' section"));
20242     }
20243
20244   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20245   line_ptr += 1;
20246   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20247   line_ptr += 1;
20248   lh->line_range = read_1_byte (abfd, line_ptr);
20249   line_ptr += 1;
20250   lh->opcode_base = read_1_byte (abfd, line_ptr);
20251   line_ptr += 1;
20252   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20253
20254   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20255   for (i = 1; i < lh->opcode_base; ++i)
20256     {
20257       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20258       line_ptr += 1;
20259     }
20260
20261   if (lh->version >= 5)
20262     {
20263       /* Read directory table.  */
20264       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20265                               &cu->header,
20266                               [] (struct line_header *lh, const char *name,
20267                                   dir_index d_index, unsigned int mod_time,
20268                                   unsigned int length)
20269         {
20270           lh->add_include_dir (name);
20271         });
20272
20273       /* Read file name table.  */
20274       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20275                               &cu->header,
20276                               [] (struct line_header *lh, const char *name,
20277                                   dir_index d_index, unsigned int mod_time,
20278                                   unsigned int length)
20279         {
20280           lh->add_file_name (name, d_index, mod_time, length);
20281         });
20282     }
20283   else
20284     {
20285       /* Read directory table.  */
20286       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20287         {
20288           line_ptr += bytes_read;
20289           lh->add_include_dir (cur_dir);
20290         }
20291       line_ptr += bytes_read;
20292
20293       /* Read file name table.  */
20294       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20295         {
20296           unsigned int mod_time, length;
20297           dir_index d_index;
20298
20299           line_ptr += bytes_read;
20300           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20301           line_ptr += bytes_read;
20302           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20303           line_ptr += bytes_read;
20304           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20305           line_ptr += bytes_read;
20306
20307           lh->add_file_name (cur_file, d_index, mod_time, length);
20308         }
20309       line_ptr += bytes_read;
20310     }
20311   lh->statement_program_start = line_ptr;
20312
20313   if (line_ptr > (section->buffer + section->size))
20314     complaint (_("line number info header doesn't "
20315                  "fit in `.debug_line' section"));
20316
20317   return lh;
20318 }
20319
20320 /* Subroutine of dwarf_decode_lines to simplify it.
20321    Return the file name of the psymtab for included file FILE_INDEX
20322    in line header LH of PST.
20323    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20324    If space for the result is malloc'd, *NAME_HOLDER will be set.
20325    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20326
20327 static const char *
20328 psymtab_include_file_name (const struct line_header *lh, int file_index,
20329                            const struct partial_symtab *pst,
20330                            const char *comp_dir,
20331                            gdb::unique_xmalloc_ptr<char> *name_holder)
20332 {
20333   const file_entry &fe = lh->file_names[file_index];
20334   const char *include_name = fe.name;
20335   const char *include_name_to_compare = include_name;
20336   const char *pst_filename;
20337   int file_is_pst;
20338
20339   const char *dir_name = fe.include_dir (lh);
20340
20341   gdb::unique_xmalloc_ptr<char> hold_compare;
20342   if (!IS_ABSOLUTE_PATH (include_name)
20343       && (dir_name != NULL || comp_dir != NULL))
20344     {
20345       /* Avoid creating a duplicate psymtab for PST.
20346          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20347          Before we do the comparison, however, we need to account
20348          for DIR_NAME and COMP_DIR.
20349          First prepend dir_name (if non-NULL).  If we still don't
20350          have an absolute path prepend comp_dir (if non-NULL).
20351          However, the directory we record in the include-file's
20352          psymtab does not contain COMP_DIR (to match the
20353          corresponding symtab(s)).
20354
20355          Example:
20356
20357          bash$ cd /tmp
20358          bash$ gcc -g ./hello.c
20359          include_name = "hello.c"
20360          dir_name = "."
20361          DW_AT_comp_dir = comp_dir = "/tmp"
20362          DW_AT_name = "./hello.c"
20363
20364       */
20365
20366       if (dir_name != NULL)
20367         {
20368           name_holder->reset (concat (dir_name, SLASH_STRING,
20369                                       include_name, (char *) NULL));
20370           include_name = name_holder->get ();
20371           include_name_to_compare = include_name;
20372         }
20373       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20374         {
20375           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20376                                       include_name, (char *) NULL));
20377           include_name_to_compare = hold_compare.get ();
20378         }
20379     }
20380
20381   pst_filename = pst->filename;
20382   gdb::unique_xmalloc_ptr<char> copied_name;
20383   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20384     {
20385       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20386                                  pst_filename, (char *) NULL));
20387       pst_filename = copied_name.get ();
20388     }
20389
20390   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20391
20392   if (file_is_pst)
20393     return NULL;
20394   return include_name;
20395 }
20396
20397 /* State machine to track the state of the line number program.  */
20398
20399 class lnp_state_machine
20400 {
20401 public:
20402   /* Initialize a machine state for the start of a line number
20403      program.  */
20404   lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch, line_header *lh,
20405                      bool record_lines_p);
20406
20407   file_entry *current_file ()
20408   {
20409     /* lh->file_names is 0-based, but the file name numbers in the
20410        statement program are 1-based.  */
20411     return m_line_header->file_name_at (m_file);
20412   }
20413
20414   /* Record the line in the state machine.  END_SEQUENCE is true if
20415      we're processing the end of a sequence.  */
20416   void record_line (bool end_sequence);
20417
20418   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20419      nop-out rest of the lines in this sequence.  */
20420   void check_line_address (struct dwarf2_cu *cu,
20421                            const gdb_byte *line_ptr,
20422                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20423
20424   void handle_set_discriminator (unsigned int discriminator)
20425   {
20426     m_discriminator = discriminator;
20427     m_line_has_non_zero_discriminator |= discriminator != 0;
20428   }
20429
20430   /* Handle DW_LNE_set_address.  */
20431   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20432   {
20433     m_op_index = 0;
20434     address += baseaddr;
20435     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20436   }
20437
20438   /* Handle DW_LNS_advance_pc.  */
20439   void handle_advance_pc (CORE_ADDR adjust);
20440
20441   /* Handle a special opcode.  */
20442   void handle_special_opcode (unsigned char op_code);
20443
20444   /* Handle DW_LNS_advance_line.  */
20445   void handle_advance_line (int line_delta)
20446   {
20447     advance_line (line_delta);
20448   }
20449
20450   /* Handle DW_LNS_set_file.  */
20451   void handle_set_file (file_name_index file);
20452
20453   /* Handle DW_LNS_negate_stmt.  */
20454   void handle_negate_stmt ()
20455   {
20456     m_is_stmt = !m_is_stmt;
20457   }
20458
20459   /* Handle DW_LNS_const_add_pc.  */
20460   void handle_const_add_pc ();
20461
20462   /* Handle DW_LNS_fixed_advance_pc.  */
20463   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20464   {
20465     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20466     m_op_index = 0;
20467   }
20468
20469   /* Handle DW_LNS_copy.  */
20470   void handle_copy ()
20471   {
20472     record_line (false);
20473     m_discriminator = 0;
20474   }
20475
20476   /* Handle DW_LNE_end_sequence.  */
20477   void handle_end_sequence ()
20478   {
20479     m_currently_recording_lines = true;
20480   }
20481
20482 private:
20483   /* Advance the line by LINE_DELTA.  */
20484   void advance_line (int line_delta)
20485   {
20486     m_line += line_delta;
20487
20488     if (line_delta != 0)
20489       m_line_has_non_zero_discriminator = m_discriminator != 0;
20490   }
20491
20492   struct dwarf2_cu *m_cu;
20493
20494   gdbarch *m_gdbarch;
20495
20496   /* True if we're recording lines.
20497      Otherwise we're building partial symtabs and are just interested in
20498      finding include files mentioned by the line number program.  */
20499   bool m_record_lines_p;
20500
20501   /* The line number header.  */
20502   line_header *m_line_header;
20503
20504   /* These are part of the standard DWARF line number state machine,
20505      and initialized according to the DWARF spec.  */
20506
20507   unsigned char m_op_index = 0;
20508   /* The line table index (1-based) of the current file.  */
20509   file_name_index m_file = (file_name_index) 1;
20510   unsigned int m_line = 1;
20511
20512   /* These are initialized in the constructor.  */
20513
20514   CORE_ADDR m_address;
20515   bool m_is_stmt;
20516   unsigned int m_discriminator;
20517
20518   /* Additional bits of state we need to track.  */
20519
20520   /* The last file that we called dwarf2_start_subfile for.
20521      This is only used for TLLs.  */
20522   unsigned int m_last_file = 0;
20523   /* The last file a line number was recorded for.  */
20524   struct subfile *m_last_subfile = NULL;
20525
20526   /* When true, record the lines we decode.  */
20527   bool m_currently_recording_lines = false;
20528
20529   /* The last line number that was recorded, used to coalesce
20530      consecutive entries for the same line.  This can happen, for
20531      example, when discriminators are present.  PR 17276.  */
20532   unsigned int m_last_line = 0;
20533   bool m_line_has_non_zero_discriminator = false;
20534 };
20535
20536 void
20537 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20538 {
20539   CORE_ADDR addr_adj = (((m_op_index + adjust)
20540                          / m_line_header->maximum_ops_per_instruction)
20541                         * m_line_header->minimum_instruction_length);
20542   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20543   m_op_index = ((m_op_index + adjust)
20544                 % m_line_header->maximum_ops_per_instruction);
20545 }
20546
20547 void
20548 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20549 {
20550   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20551   CORE_ADDR addr_adj = (((m_op_index
20552                           + (adj_opcode / m_line_header->line_range))
20553                          / m_line_header->maximum_ops_per_instruction)
20554                         * m_line_header->minimum_instruction_length);
20555   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20556   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20557                 % m_line_header->maximum_ops_per_instruction);
20558
20559   int line_delta = (m_line_header->line_base
20560                     + (adj_opcode % m_line_header->line_range));
20561   advance_line (line_delta);
20562   record_line (false);
20563   m_discriminator = 0;
20564 }
20565
20566 void
20567 lnp_state_machine::handle_set_file (file_name_index file)
20568 {
20569   m_file = file;
20570
20571   const file_entry *fe = current_file ();
20572   if (fe == NULL)
20573     dwarf2_debug_line_missing_file_complaint ();
20574   else if (m_record_lines_p)
20575     {
20576       const char *dir = fe->include_dir (m_line_header);
20577
20578       m_last_subfile = m_cu->builder->get_current_subfile ();
20579       m_line_has_non_zero_discriminator = m_discriminator != 0;
20580       dwarf2_start_subfile (m_cu, fe->name, dir);
20581     }
20582 }
20583
20584 void
20585 lnp_state_machine::handle_const_add_pc ()
20586 {
20587   CORE_ADDR adjust
20588     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20589
20590   CORE_ADDR addr_adj
20591     = (((m_op_index + adjust)
20592         / m_line_header->maximum_ops_per_instruction)
20593        * m_line_header->minimum_instruction_length);
20594
20595   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20596   m_op_index = ((m_op_index + adjust)
20597                 % m_line_header->maximum_ops_per_instruction);
20598 }
20599
20600 /* Return non-zero if we should add LINE to the line number table.
20601    LINE is the line to add, LAST_LINE is the last line that was added,
20602    LAST_SUBFILE is the subfile for LAST_LINE.
20603    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20604    had a non-zero discriminator.
20605
20606    We have to be careful in the presence of discriminators.
20607    E.g., for this line:
20608
20609      for (i = 0; i < 100000; i++);
20610
20611    clang can emit four line number entries for that one line,
20612    each with a different discriminator.
20613    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20614
20615    However, we want gdb to coalesce all four entries into one.
20616    Otherwise the user could stepi into the middle of the line and
20617    gdb would get confused about whether the pc really was in the
20618    middle of the line.
20619
20620    Things are further complicated by the fact that two consecutive
20621    line number entries for the same line is a heuristic used by gcc
20622    to denote the end of the prologue.  So we can't just discard duplicate
20623    entries, we have to be selective about it.  The heuristic we use is
20624    that we only collapse consecutive entries for the same line if at least
20625    one of those entries has a non-zero discriminator.  PR 17276.
20626
20627    Note: Addresses in the line number state machine can never go backwards
20628    within one sequence, thus this coalescing is ok.  */
20629
20630 static int
20631 dwarf_record_line_p (struct dwarf2_cu *cu,
20632                      unsigned int line, unsigned int last_line,
20633                      int line_has_non_zero_discriminator,
20634                      struct subfile *last_subfile)
20635 {
20636   if (cu->builder->get_current_subfile () != last_subfile)
20637     return 1;
20638   if (line != last_line)
20639     return 1;
20640   /* Same line for the same file that we've seen already.
20641      As a last check, for pr 17276, only record the line if the line
20642      has never had a non-zero discriminator.  */
20643   if (!line_has_non_zero_discriminator)
20644     return 1;
20645   return 0;
20646 }
20647
20648 /* Use the CU's builder to record line number LINE beginning at
20649    address ADDRESS in the line table of subfile SUBFILE.  */
20650
20651 static void
20652 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20653                      unsigned int line, CORE_ADDR address,
20654                      struct dwarf2_cu *cu)
20655 {
20656   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20657
20658   if (dwarf_line_debug)
20659     {
20660       fprintf_unfiltered (gdb_stdlog,
20661                           "Recording line %u, file %s, address %s\n",
20662                           line, lbasename (subfile->name),
20663                           paddress (gdbarch, address));
20664     }
20665
20666   if (cu != nullptr)
20667     cu->builder->record_line (subfile, line, addr);
20668 }
20669
20670 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20671    Mark the end of a set of line number records.
20672    The arguments are the same as for dwarf_record_line_1.
20673    If SUBFILE is NULL the request is ignored.  */
20674
20675 static void
20676 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20677                    CORE_ADDR address, struct dwarf2_cu *cu)
20678 {
20679   if (subfile == NULL)
20680     return;
20681
20682   if (dwarf_line_debug)
20683     {
20684       fprintf_unfiltered (gdb_stdlog,
20685                           "Finishing current line, file %s, address %s\n",
20686                           lbasename (subfile->name),
20687                           paddress (gdbarch, address));
20688     }
20689
20690   dwarf_record_line_1 (gdbarch, subfile, 0, address, cu);
20691 }
20692
20693 void
20694 lnp_state_machine::record_line (bool end_sequence)
20695 {
20696   if (dwarf_line_debug)
20697     {
20698       fprintf_unfiltered (gdb_stdlog,
20699                           "Processing actual line %u: file %u,"
20700                           " address %s, is_stmt %u, discrim %u\n",
20701                           m_line, to_underlying (m_file),
20702                           paddress (m_gdbarch, m_address),
20703                           m_is_stmt, m_discriminator);
20704     }
20705
20706   file_entry *fe = current_file ();
20707
20708   if (fe == NULL)
20709     dwarf2_debug_line_missing_file_complaint ();
20710   /* For now we ignore lines not starting on an instruction boundary.
20711      But not when processing end_sequence for compatibility with the
20712      previous version of the code.  */
20713   else if (m_op_index == 0 || end_sequence)
20714     {
20715       fe->included_p = 1;
20716       if (m_record_lines_p && m_is_stmt)
20717         {
20718           if (m_last_subfile != m_cu->builder->get_current_subfile ()
20719               || end_sequence)
20720             {
20721               dwarf_finish_line (m_gdbarch, m_last_subfile, m_address,
20722                                  m_currently_recording_lines ? m_cu : nullptr);
20723             }
20724
20725           if (!end_sequence)
20726             {
20727               if (dwarf_record_line_p (m_cu, m_line, m_last_line,
20728                                        m_line_has_non_zero_discriminator,
20729                                        m_last_subfile))
20730                 {
20731                   dwarf_record_line_1 (m_gdbarch,
20732                                        m_cu->builder->get_current_subfile (),
20733                                        m_line, m_address,
20734                                        m_currently_recording_lines ? m_cu : nullptr);
20735                 }
20736               m_last_subfile = m_cu->builder->get_current_subfile ();
20737               m_last_line = m_line;
20738             }
20739         }
20740     }
20741 }
20742
20743 lnp_state_machine::lnp_state_machine (struct dwarf2_cu *cu, gdbarch *arch,
20744                                       line_header *lh, bool record_lines_p)
20745 {
20746   m_cu = cu;
20747   m_gdbarch = arch;
20748   m_record_lines_p = record_lines_p;
20749   m_line_header = lh;
20750
20751   m_currently_recording_lines = true;
20752
20753   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20754      was a line entry for it so that the backend has a chance to adjust it
20755      and also record it in case it needs it.  This is currently used by MIPS
20756      code, cf. `mips_adjust_dwarf2_line'.  */
20757   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20758   m_is_stmt = lh->default_is_stmt;
20759   m_discriminator = 0;
20760 }
20761
20762 void
20763 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20764                                        const gdb_byte *line_ptr,
20765                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20766 {
20767   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20768      the pc range of the CU.  However, we restrict the test to only ADDRESS
20769      values of zero to preserve GDB's previous behaviour which is to handle
20770      the specific case of a function being GC'd by the linker.  */
20771
20772   if (address == 0 && address < unrelocated_lowpc)
20773     {
20774       /* This line table is for a function which has been
20775          GCd by the linker.  Ignore it.  PR gdb/12528 */
20776
20777       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20778       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20779
20780       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20781                  line_offset, objfile_name (objfile));
20782       m_currently_recording_lines = false;
20783       /* Note: m_currently_recording_lines is left as false until we see
20784          DW_LNE_end_sequence.  */
20785     }
20786 }
20787
20788 /* Subroutine of dwarf_decode_lines to simplify it.
20789    Process the line number information in LH.
20790    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20791    program in order to set included_p for every referenced header.  */
20792
20793 static void
20794 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20795                       const int decode_for_pst_p, CORE_ADDR lowpc)
20796 {
20797   const gdb_byte *line_ptr, *extended_end;
20798   const gdb_byte *line_end;
20799   unsigned int bytes_read, extended_len;
20800   unsigned char op_code, extended_op;
20801   CORE_ADDR baseaddr;
20802   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20803   bfd *abfd = objfile->obfd;
20804   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20805   /* True if we're recording line info (as opposed to building partial
20806      symtabs and just interested in finding include files mentioned by
20807      the line number program).  */
20808   bool record_lines_p = !decode_for_pst_p;
20809
20810   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20811
20812   line_ptr = lh->statement_program_start;
20813   line_end = lh->statement_program_end;
20814
20815   /* Read the statement sequences until there's nothing left.  */
20816   while (line_ptr < line_end)
20817     {
20818       /* The DWARF line number program state machine.  Reset the state
20819          machine at the start of each sequence.  */
20820       lnp_state_machine state_machine (cu, gdbarch, lh, record_lines_p);
20821       bool end_sequence = false;
20822
20823       if (record_lines_p)
20824         {
20825           /* Start a subfile for the current file of the state
20826              machine.  */
20827           const file_entry *fe = state_machine.current_file ();
20828
20829           if (fe != NULL)
20830             dwarf2_start_subfile (cu, fe->name, fe->include_dir (lh));
20831         }
20832
20833       /* Decode the table.  */
20834       while (line_ptr < line_end && !end_sequence)
20835         {
20836           op_code = read_1_byte (abfd, line_ptr);
20837           line_ptr += 1;
20838
20839           if (op_code >= lh->opcode_base)
20840             {
20841               /* Special opcode.  */
20842               state_machine.handle_special_opcode (op_code);
20843             }
20844           else switch (op_code)
20845             {
20846             case DW_LNS_extended_op:
20847               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20848                                                    &bytes_read);
20849               line_ptr += bytes_read;
20850               extended_end = line_ptr + extended_len;
20851               extended_op = read_1_byte (abfd, line_ptr);
20852               line_ptr += 1;
20853               switch (extended_op)
20854                 {
20855                 case DW_LNE_end_sequence:
20856                   state_machine.handle_end_sequence ();
20857                   end_sequence = true;
20858                   break;
20859                 case DW_LNE_set_address:
20860                   {
20861                     CORE_ADDR address
20862                       = read_address (abfd, line_ptr, cu, &bytes_read);
20863                     line_ptr += bytes_read;
20864
20865                     state_machine.check_line_address (cu, line_ptr,
20866                                                       lowpc - baseaddr, address);
20867                     state_machine.handle_set_address (baseaddr, address);
20868                   }
20869                   break;
20870                 case DW_LNE_define_file:
20871                   {
20872                     const char *cur_file;
20873                     unsigned int mod_time, length;
20874                     dir_index dindex;
20875
20876                     cur_file = read_direct_string (abfd, line_ptr,
20877                                                    &bytes_read);
20878                     line_ptr += bytes_read;
20879                     dindex = (dir_index)
20880                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20881                     line_ptr += bytes_read;
20882                     mod_time =
20883                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20884                     line_ptr += bytes_read;
20885                     length =
20886                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20887                     line_ptr += bytes_read;
20888                     lh->add_file_name (cur_file, dindex, mod_time, length);
20889                   }
20890                   break;
20891                 case DW_LNE_set_discriminator:
20892                   {
20893                     /* The discriminator is not interesting to the
20894                        debugger; just ignore it.  We still need to
20895                        check its value though:
20896                        if there are consecutive entries for the same
20897                        (non-prologue) line we want to coalesce them.
20898                        PR 17276.  */
20899                     unsigned int discr
20900                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20901                     line_ptr += bytes_read;
20902
20903                     state_machine.handle_set_discriminator (discr);
20904                   }
20905                   break;
20906                 default:
20907                   complaint (_("mangled .debug_line section"));
20908                   return;
20909                 }
20910               /* Make sure that we parsed the extended op correctly.  If e.g.
20911                  we expected a different address size than the producer used,
20912                  we may have read the wrong number of bytes.  */
20913               if (line_ptr != extended_end)
20914                 {
20915                   complaint (_("mangled .debug_line section"));
20916                   return;
20917                 }
20918               break;
20919             case DW_LNS_copy:
20920               state_machine.handle_copy ();
20921               break;
20922             case DW_LNS_advance_pc:
20923               {
20924                 CORE_ADDR adjust
20925                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20926                 line_ptr += bytes_read;
20927
20928                 state_machine.handle_advance_pc (adjust);
20929               }
20930               break;
20931             case DW_LNS_advance_line:
20932               {
20933                 int line_delta
20934                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20935                 line_ptr += bytes_read;
20936
20937                 state_machine.handle_advance_line (line_delta);
20938               }
20939               break;
20940             case DW_LNS_set_file:
20941               {
20942                 file_name_index file
20943                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20944                                                             &bytes_read);
20945                 line_ptr += bytes_read;
20946
20947                 state_machine.handle_set_file (file);
20948               }
20949               break;
20950             case DW_LNS_set_column:
20951               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20952               line_ptr += bytes_read;
20953               break;
20954             case DW_LNS_negate_stmt:
20955               state_machine.handle_negate_stmt ();
20956               break;
20957             case DW_LNS_set_basic_block:
20958               break;
20959             /* Add to the address register of the state machine the
20960                address increment value corresponding to special opcode
20961                255.  I.e., this value is scaled by the minimum
20962                instruction length since special opcode 255 would have
20963                scaled the increment.  */
20964             case DW_LNS_const_add_pc:
20965               state_machine.handle_const_add_pc ();
20966               break;
20967             case DW_LNS_fixed_advance_pc:
20968               {
20969                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20970                 line_ptr += 2;
20971
20972                 state_machine.handle_fixed_advance_pc (addr_adj);
20973               }
20974               break;
20975             default:
20976               {
20977                 /* Unknown standard opcode, ignore it.  */
20978                 int i;
20979
20980                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20981                   {
20982                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20983                     line_ptr += bytes_read;
20984                   }
20985               }
20986             }
20987         }
20988
20989       if (!end_sequence)
20990         dwarf2_debug_line_missing_end_sequence_complaint ();
20991
20992       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20993          in which case we still finish recording the last line).  */
20994       state_machine.record_line (true);
20995     }
20996 }
20997
20998 /* Decode the Line Number Program (LNP) for the given line_header
20999    structure and CU.  The actual information extracted and the type
21000    of structures created from the LNP depends on the value of PST.
21001
21002    1. If PST is NULL, then this procedure uses the data from the program
21003       to create all necessary symbol tables, and their linetables.
21004
21005    2. If PST is not NULL, this procedure reads the program to determine
21006       the list of files included by the unit represented by PST, and
21007       builds all the associated partial symbol tables.
21008
21009    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
21010    It is used for relative paths in the line table.
21011    NOTE: When processing partial symtabs (pst != NULL),
21012    comp_dir == pst->dirname.
21013
21014    NOTE: It is important that psymtabs have the same file name (via strcmp)
21015    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
21016    symtab we don't use it in the name of the psymtabs we create.
21017    E.g. expand_line_sal requires this when finding psymtabs to expand.
21018    A good testcase for this is mb-inline.exp.
21019
21020    LOWPC is the lowest address in CU (or 0 if not known).
21021
21022    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
21023    for its PC<->lines mapping information.  Otherwise only the filename
21024    table is read in.  */
21025
21026 static void
21027 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
21028                     struct dwarf2_cu *cu, struct partial_symtab *pst,
21029                     CORE_ADDR lowpc, int decode_mapping)
21030 {
21031   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21032   const int decode_for_pst_p = (pst != NULL);
21033
21034   if (decode_mapping)
21035     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
21036
21037   if (decode_for_pst_p)
21038     {
21039       int file_index;
21040
21041       /* Now that we're done scanning the Line Header Program, we can
21042          create the psymtab of each included file.  */
21043       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
21044         if (lh->file_names[file_index].included_p == 1)
21045           {
21046             gdb::unique_xmalloc_ptr<char> name_holder;
21047             const char *include_name =
21048               psymtab_include_file_name (lh, file_index, pst, comp_dir,
21049                                          &name_holder);
21050             if (include_name != NULL)
21051               dwarf2_create_include_psymtab (include_name, pst, objfile);
21052           }
21053     }
21054   else
21055     {
21056       /* Make sure a symtab is created for every file, even files
21057          which contain only variables (i.e. no code with associated
21058          line numbers).  */
21059       struct compunit_symtab *cust = cu->builder->get_compunit_symtab ();
21060       int i;
21061
21062       for (i = 0; i < lh->file_names.size (); i++)
21063         {
21064           file_entry &fe = lh->file_names[i];
21065
21066           dwarf2_start_subfile (cu, fe.name, fe.include_dir (lh));
21067
21068           if (cu->builder->get_current_subfile ()->symtab == NULL)
21069             {
21070               cu->builder->get_current_subfile ()->symtab
21071                 = allocate_symtab (cust,
21072                                    cu->builder->get_current_subfile ()->name);
21073             }
21074           fe.symtab = cu->builder->get_current_subfile ()->symtab;
21075         }
21076     }
21077 }
21078
21079 /* Start a subfile for DWARF.  FILENAME is the name of the file and
21080    DIRNAME the name of the source directory which contains FILENAME
21081    or NULL if not known.
21082    This routine tries to keep line numbers from identical absolute and
21083    relative file names in a common subfile.
21084
21085    Using the `list' example from the GDB testsuite, which resides in
21086    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
21087    of /srcdir/list0.c yields the following debugging information for list0.c:
21088
21089    DW_AT_name:          /srcdir/list0.c
21090    DW_AT_comp_dir:      /compdir
21091    files.files[0].name: list0.h
21092    files.files[0].dir:  /srcdir
21093    files.files[1].name: list0.c
21094    files.files[1].dir:  /srcdir
21095
21096    The line number information for list0.c has to end up in a single
21097    subfile, so that `break /srcdir/list0.c:1' works as expected.
21098    start_subfile will ensure that this happens provided that we pass the
21099    concatenation of files.files[1].dir and files.files[1].name as the
21100    subfile's name.  */
21101
21102 static void
21103 dwarf2_start_subfile (struct dwarf2_cu *cu, const char *filename,
21104                       const char *dirname)
21105 {
21106   char *copy = NULL;
21107
21108   /* In order not to lose the line information directory,
21109      we concatenate it to the filename when it makes sense.
21110      Note that the Dwarf3 standard says (speaking of filenames in line
21111      information): ``The directory index is ignored for file names
21112      that represent full path names''.  Thus ignoring dirname in the
21113      `else' branch below isn't an issue.  */
21114
21115   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21116     {
21117       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21118       filename = copy;
21119     }
21120
21121   cu->builder->start_subfile (filename);
21122
21123   if (copy != NULL)
21124     xfree (copy);
21125 }
21126
21127 /* Start a symtab for DWARF.  NAME, COMP_DIR, LOW_PC are passed to the
21128    buildsym_compunit constructor.  */
21129
21130 static struct compunit_symtab *
21131 dwarf2_start_symtab (struct dwarf2_cu *cu,
21132                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21133 {
21134   gdb_assert (cu->builder == nullptr);
21135
21136   cu->builder.reset (new struct buildsym_compunit
21137                      (cu->per_cu->dwarf2_per_objfile->objfile,
21138                       name, comp_dir, cu->language, low_pc));
21139
21140   cu->list_in_scope = cu->builder->get_file_symbols ();
21141
21142   cu->builder->record_debugformat ("DWARF 2");
21143   cu->builder->record_producer (cu->producer);
21144
21145   cu->processing_has_namespace_info = 0;
21146
21147   return cu->builder->get_compunit_symtab ();
21148 }
21149
21150 static void
21151 var_decode_location (struct attribute *attr, struct symbol *sym,
21152                      struct dwarf2_cu *cu)
21153 {
21154   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21155   struct comp_unit_head *cu_header = &cu->header;
21156
21157   /* NOTE drow/2003-01-30: There used to be a comment and some special
21158      code here to turn a symbol with DW_AT_external and a
21159      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21160      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21161      with some versions of binutils) where shared libraries could have
21162      relocations against symbols in their debug information - the
21163      minimal symbol would have the right address, but the debug info
21164      would not.  It's no longer necessary, because we will explicitly
21165      apply relocations when we read in the debug information now.  */
21166
21167   /* A DW_AT_location attribute with no contents indicates that a
21168      variable has been optimized away.  */
21169   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21170     {
21171       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21172       return;
21173     }
21174
21175   /* Handle one degenerate form of location expression specially, to
21176      preserve GDB's previous behavior when section offsets are
21177      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21178      then mark this symbol as LOC_STATIC.  */
21179
21180   if (attr_form_is_block (attr)
21181       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21182            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21183           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21184               && (DW_BLOCK (attr)->size
21185                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21186     {
21187       unsigned int dummy;
21188
21189       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21190         SYMBOL_VALUE_ADDRESS (sym) =
21191           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21192       else
21193         SYMBOL_VALUE_ADDRESS (sym) =
21194           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21195       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21196       fixup_symbol_section (sym, objfile);
21197       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21198                                               SYMBOL_SECTION (sym));
21199       return;
21200     }
21201
21202   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21203      expression evaluator, and use LOC_COMPUTED only when necessary
21204      (i.e. when the value of a register or memory location is
21205      referenced, or a thread-local block, etc.).  Then again, it might
21206      not be worthwhile.  I'm assuming that it isn't unless performance
21207      or memory numbers show me otherwise.  */
21208
21209   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21210
21211   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21212     cu->has_loclist = 1;
21213 }
21214
21215 /* Given a pointer to a DWARF information entry, figure out if we need
21216    to make a symbol table entry for it, and if so, create a new entry
21217    and return a pointer to it.
21218    If TYPE is NULL, determine symbol type from the die, otherwise
21219    used the passed type.
21220    If SPACE is not NULL, use it to hold the new symbol.  If it is
21221    NULL, allocate a new symbol on the objfile's obstack.  */
21222
21223 static struct symbol *
21224 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21225             struct symbol *space)
21226 {
21227   struct dwarf2_per_objfile *dwarf2_per_objfile
21228     = cu->per_cu->dwarf2_per_objfile;
21229   struct objfile *objfile = dwarf2_per_objfile->objfile;
21230   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21231   struct symbol *sym = NULL;
21232   const char *name;
21233   struct attribute *attr = NULL;
21234   struct attribute *attr2 = NULL;
21235   CORE_ADDR baseaddr;
21236   struct pending **list_to_add = NULL;
21237
21238   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21239
21240   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21241
21242   name = dwarf2_name (die, cu);
21243   if (name)
21244     {
21245       const char *linkagename;
21246       int suppress_add = 0;
21247
21248       if (space)
21249         sym = space;
21250       else
21251         sym = allocate_symbol (objfile);
21252       OBJSTAT (objfile, n_syms++);
21253
21254       /* Cache this symbol's name and the name's demangled form (if any).  */
21255       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21256       linkagename = dwarf2_physname (name, die, cu);
21257       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21258
21259       /* Fortran does not have mangling standard and the mangling does differ
21260          between gfortran, iFort etc.  */
21261       if (cu->language == language_fortran
21262           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21263         symbol_set_demangled_name (&(sym->ginfo),
21264                                    dwarf2_full_name (name, die, cu),
21265                                    NULL);
21266
21267       /* Default assumptions.
21268          Use the passed type or decode it from the die.  */
21269       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21270       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21271       if (type != NULL)
21272         SYMBOL_TYPE (sym) = type;
21273       else
21274         SYMBOL_TYPE (sym) = die_type (die, cu);
21275       attr = dwarf2_attr (die,
21276                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21277                           cu);
21278       if (attr)
21279         {
21280           SYMBOL_LINE (sym) = DW_UNSND (attr);
21281         }
21282
21283       attr = dwarf2_attr (die,
21284                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21285                           cu);
21286       if (attr)
21287         {
21288           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21289           struct file_entry *fe;
21290
21291           if (cu->line_header != NULL)
21292             fe = cu->line_header->file_name_at (file_index);
21293           else
21294             fe = NULL;
21295
21296           if (fe == NULL)
21297             complaint (_("file index out of range"));
21298           else
21299             symbol_set_symtab (sym, fe->symtab);
21300         }
21301
21302       switch (die->tag)
21303         {
21304         case DW_TAG_label:
21305           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21306           if (attr)
21307             {
21308               CORE_ADDR addr;
21309
21310               addr = attr_value_as_address (attr);
21311               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21312               SYMBOL_VALUE_ADDRESS (sym) = addr;
21313             }
21314           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21315           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21316           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21317           dw2_add_symbol_to_list (sym, cu->list_in_scope);
21318           break;
21319         case DW_TAG_subprogram:
21320           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21321              finish_block.  */
21322           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21323           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21324           if ((attr2 && (DW_UNSND (attr2) != 0))
21325               || cu->language == language_ada)
21326             {
21327               /* Subprograms marked external are stored as a global symbol.
21328                  Ada subprograms, whether marked external or not, are always
21329                  stored as a global symbol, because we want to be able to
21330                  access them globally.  For instance, we want to be able
21331                  to break on a nested subprogram without having to
21332                  specify the context.  */
21333               list_to_add = cu->builder->get_global_symbols ();
21334             }
21335           else
21336             {
21337               list_to_add = cu->list_in_scope;
21338             }
21339           break;
21340         case DW_TAG_inlined_subroutine:
21341           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21342              finish_block.  */
21343           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21344           SYMBOL_INLINED (sym) = 1;
21345           list_to_add = cu->list_in_scope;
21346           break;
21347         case DW_TAG_template_value_param:
21348           suppress_add = 1;
21349           /* Fall through.  */
21350         case DW_TAG_constant:
21351         case DW_TAG_variable:
21352         case DW_TAG_member:
21353           /* Compilation with minimal debug info may result in
21354              variables with missing type entries.  Change the
21355              misleading `void' type to something sensible.  */
21356           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21357             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21358
21359           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21360           /* In the case of DW_TAG_member, we should only be called for
21361              static const members.  */
21362           if (die->tag == DW_TAG_member)
21363             {
21364               /* dwarf2_add_field uses die_is_declaration,
21365                  so we do the same.  */
21366               gdb_assert (die_is_declaration (die, cu));
21367               gdb_assert (attr);
21368             }
21369           if (attr)
21370             {
21371               dwarf2_const_value (attr, sym, cu);
21372               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21373               if (!suppress_add)
21374                 {
21375                   if (attr2 && (DW_UNSND (attr2) != 0))
21376                     list_to_add = cu->builder->get_global_symbols ();
21377                   else
21378                     list_to_add = cu->list_in_scope;
21379                 }
21380               break;
21381             }
21382           attr = dwarf2_attr (die, DW_AT_location, cu);
21383           if (attr)
21384             {
21385               var_decode_location (attr, sym, cu);
21386               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21387
21388               /* Fortran explicitly imports any global symbols to the local
21389                  scope by DW_TAG_common_block.  */
21390               if (cu->language == language_fortran && die->parent
21391                   && die->parent->tag == DW_TAG_common_block)
21392                 attr2 = NULL;
21393
21394               if (SYMBOL_CLASS (sym) == LOC_STATIC
21395                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21396                   && !dwarf2_per_objfile->has_section_at_zero)
21397                 {
21398                   /* When a static variable is eliminated by the linker,
21399                      the corresponding debug information is not stripped
21400                      out, but the variable address is set to null;
21401                      do not add such variables into symbol table.  */
21402                 }
21403               else if (attr2 && (DW_UNSND (attr2) != 0))
21404                 {
21405                   /* Workaround gfortran PR debug/40040 - it uses
21406                      DW_AT_location for variables in -fPIC libraries which may
21407                      get overriden by other libraries/executable and get
21408                      a different address.  Resolve it by the minimal symbol
21409                      which may come from inferior's executable using copy
21410                      relocation.  Make this workaround only for gfortran as for
21411                      other compilers GDB cannot guess the minimal symbol
21412                      Fortran mangling kind.  */
21413                   if (cu->language == language_fortran && die->parent
21414                       && die->parent->tag == DW_TAG_module
21415                       && cu->producer
21416                       && startswith (cu->producer, "GNU Fortran"))
21417                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21418
21419                   /* A variable with DW_AT_external is never static,
21420                      but it may be block-scoped.  */
21421                   list_to_add
21422                     = (cu->list_in_scope == cu->builder->get_file_symbols ()
21423                        ? cu->builder->get_global_symbols ()
21424                        : cu->list_in_scope);
21425                 }
21426               else
21427                 list_to_add = cu->list_in_scope;
21428             }
21429           else
21430             {
21431               /* We do not know the address of this symbol.
21432                  If it is an external symbol and we have type information
21433                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21434                  The address of the variable will then be determined from
21435                  the minimal symbol table whenever the variable is
21436                  referenced.  */
21437               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21438
21439               /* Fortran explicitly imports any global symbols to the local
21440                  scope by DW_TAG_common_block.  */
21441               if (cu->language == language_fortran && die->parent
21442                   && die->parent->tag == DW_TAG_common_block)
21443                 {
21444                   /* SYMBOL_CLASS doesn't matter here because
21445                      read_common_block is going to reset it.  */
21446                   if (!suppress_add)
21447                     list_to_add = cu->list_in_scope;
21448                 }
21449               else if (attr2 && (DW_UNSND (attr2) != 0)
21450                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21451                 {
21452                   /* A variable with DW_AT_external is never static, but it
21453                      may be block-scoped.  */
21454                   list_to_add
21455                     = (cu->list_in_scope == cu->builder->get_file_symbols ()
21456                        ? cu->builder->get_global_symbols ()
21457                        : cu->list_in_scope);
21458
21459                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21460                 }
21461               else if (!die_is_declaration (die, cu))
21462                 {
21463                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21464                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21465                   if (!suppress_add)
21466                     list_to_add = cu->list_in_scope;
21467                 }
21468             }
21469           break;
21470         case DW_TAG_formal_parameter:
21471           {
21472             /* If we are inside a function, mark this as an argument.  If
21473                not, we might be looking at an argument to an inlined function
21474                when we do not have enough information to show inlined frames;
21475                pretend it's a local variable in that case so that the user can
21476                still see it.  */
21477             struct context_stack *curr
21478               = cu->builder->get_current_context_stack ();
21479             if (curr != nullptr && curr->name != nullptr)
21480               SYMBOL_IS_ARGUMENT (sym) = 1;
21481             attr = dwarf2_attr (die, DW_AT_location, cu);
21482             if (attr)
21483               {
21484                 var_decode_location (attr, sym, cu);
21485               }
21486             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21487             if (attr)
21488               {
21489                 dwarf2_const_value (attr, sym, cu);
21490               }
21491
21492             list_to_add = cu->list_in_scope;
21493           }
21494           break;
21495         case DW_TAG_unspecified_parameters:
21496           /* From varargs functions; gdb doesn't seem to have any
21497              interest in this information, so just ignore it for now.
21498              (FIXME?) */
21499           break;
21500         case DW_TAG_template_type_param:
21501           suppress_add = 1;
21502           /* Fall through.  */
21503         case DW_TAG_class_type:
21504         case DW_TAG_interface_type:
21505         case DW_TAG_structure_type:
21506         case DW_TAG_union_type:
21507         case DW_TAG_set_type:
21508         case DW_TAG_enumeration_type:
21509           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21510           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21511
21512           {
21513             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21514                really ever be static objects: otherwise, if you try
21515                to, say, break of a class's method and you're in a file
21516                which doesn't mention that class, it won't work unless
21517                the check for all static symbols in lookup_symbol_aux
21518                saves you.  See the OtherFileClass tests in
21519                gdb.c++/namespace.exp.  */
21520
21521             if (!suppress_add)
21522               {
21523                 list_to_add
21524                   = (cu->list_in_scope == cu->builder->get_file_symbols ()
21525                      && cu->language == language_cplus
21526                      ? cu->builder->get_global_symbols ()
21527                      : cu->list_in_scope);
21528
21529                 /* The semantics of C++ state that "struct foo {
21530                    ... }" also defines a typedef for "foo".  */
21531                 if (cu->language == language_cplus
21532                     || cu->language == language_ada
21533                     || cu->language == language_d
21534                     || cu->language == language_rust)
21535                   {
21536                     /* The symbol's name is already allocated along
21537                        with this objfile, so we don't need to
21538                        duplicate it for the type.  */
21539                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21540                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21541                   }
21542               }
21543           }
21544           break;
21545         case DW_TAG_typedef:
21546           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21547           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21548           list_to_add = cu->list_in_scope;
21549           break;
21550         case DW_TAG_base_type:
21551         case DW_TAG_subrange_type:
21552           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21553           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21554           list_to_add = cu->list_in_scope;
21555           break;
21556         case DW_TAG_enumerator:
21557           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21558           if (attr)
21559             {
21560               dwarf2_const_value (attr, sym, cu);
21561             }
21562           {
21563             /* NOTE: carlton/2003-11-10: See comment above in the
21564                DW_TAG_class_type, etc. block.  */
21565
21566             list_to_add
21567               = (cu->list_in_scope == cu->builder->get_file_symbols ()
21568                  && cu->language == language_cplus
21569                  ? cu->builder->get_global_symbols ()
21570                  : cu->list_in_scope);
21571           }
21572           break;
21573         case DW_TAG_imported_declaration:
21574         case DW_TAG_namespace:
21575           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21576           list_to_add = cu->builder->get_global_symbols ();
21577           break;
21578         case DW_TAG_module:
21579           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21580           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21581           list_to_add = cu->builder->get_global_symbols ();
21582           break;
21583         case DW_TAG_common_block:
21584           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21585           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21586           dw2_add_symbol_to_list (sym, cu->list_in_scope);
21587           break;
21588         default:
21589           /* Not a tag we recognize.  Hopefully we aren't processing
21590              trash data, but since we must specifically ignore things
21591              we don't recognize, there is nothing else we should do at
21592              this point.  */
21593           complaint (_("unsupported tag: '%s'"),
21594                      dwarf_tag_name (die->tag));
21595           break;
21596         }
21597
21598       if (suppress_add)
21599         {
21600           sym->hash_next = objfile->template_symbols;
21601           objfile->template_symbols = sym;
21602           list_to_add = NULL;
21603         }
21604
21605       if (list_to_add != NULL)
21606         dw2_add_symbol_to_list (sym, list_to_add);
21607
21608       /* For the benefit of old versions of GCC, check for anonymous
21609          namespaces based on the demangled name.  */
21610       if (!cu->processing_has_namespace_info
21611           && cu->language == language_cplus)
21612         cp_scan_for_anonymous_namespaces (cu->builder.get (), sym, objfile);
21613     }
21614   return (sym);
21615 }
21616
21617 /* Given an attr with a DW_FORM_dataN value in host byte order,
21618    zero-extend it as appropriate for the symbol's type.  The DWARF
21619    standard (v4) is not entirely clear about the meaning of using
21620    DW_FORM_dataN for a constant with a signed type, where the type is
21621    wider than the data.  The conclusion of a discussion on the DWARF
21622    list was that this is unspecified.  We choose to always zero-extend
21623    because that is the interpretation long in use by GCC.  */
21624
21625 static gdb_byte *
21626 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21627                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21628 {
21629   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21630   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21631                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21632   LONGEST l = DW_UNSND (attr);
21633
21634   if (bits < sizeof (*value) * 8)
21635     {
21636       l &= ((LONGEST) 1 << bits) - 1;
21637       *value = l;
21638     }
21639   else if (bits == sizeof (*value) * 8)
21640     *value = l;
21641   else
21642     {
21643       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21644       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21645       return bytes;
21646     }
21647
21648   return NULL;
21649 }
21650
21651 /* Read a constant value from an attribute.  Either set *VALUE, or if
21652    the value does not fit in *VALUE, set *BYTES - either already
21653    allocated on the objfile obstack, or newly allocated on OBSTACK,
21654    or, set *BATON, if we translated the constant to a location
21655    expression.  */
21656
21657 static void
21658 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21659                          const char *name, struct obstack *obstack,
21660                          struct dwarf2_cu *cu,
21661                          LONGEST *value, const gdb_byte **bytes,
21662                          struct dwarf2_locexpr_baton **baton)
21663 {
21664   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21665   struct comp_unit_head *cu_header = &cu->header;
21666   struct dwarf_block *blk;
21667   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21668                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21669
21670   *value = 0;
21671   *bytes = NULL;
21672   *baton = NULL;
21673
21674   switch (attr->form)
21675     {
21676     case DW_FORM_addr:
21677     case DW_FORM_GNU_addr_index:
21678       {
21679         gdb_byte *data;
21680
21681         if (TYPE_LENGTH (type) != cu_header->addr_size)
21682           dwarf2_const_value_length_mismatch_complaint (name,
21683                                                         cu_header->addr_size,
21684                                                         TYPE_LENGTH (type));
21685         /* Symbols of this form are reasonably rare, so we just
21686            piggyback on the existing location code rather than writing
21687            a new implementation of symbol_computed_ops.  */
21688         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21689         (*baton)->per_cu = cu->per_cu;
21690         gdb_assert ((*baton)->per_cu);
21691
21692         (*baton)->size = 2 + cu_header->addr_size;
21693         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21694         (*baton)->data = data;
21695
21696         data[0] = DW_OP_addr;
21697         store_unsigned_integer (&data[1], cu_header->addr_size,
21698                                 byte_order, DW_ADDR (attr));
21699         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21700       }
21701       break;
21702     case DW_FORM_string:
21703     case DW_FORM_strp:
21704     case DW_FORM_GNU_str_index:
21705     case DW_FORM_GNU_strp_alt:
21706       /* DW_STRING is already allocated on the objfile obstack, point
21707          directly to it.  */
21708       *bytes = (const gdb_byte *) DW_STRING (attr);
21709       break;
21710     case DW_FORM_block1:
21711     case DW_FORM_block2:
21712     case DW_FORM_block4:
21713     case DW_FORM_block:
21714     case DW_FORM_exprloc:
21715     case DW_FORM_data16:
21716       blk = DW_BLOCK (attr);
21717       if (TYPE_LENGTH (type) != blk->size)
21718         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21719                                                       TYPE_LENGTH (type));
21720       *bytes = blk->data;
21721       break;
21722
21723       /* The DW_AT_const_value attributes are supposed to carry the
21724          symbol's value "represented as it would be on the target
21725          architecture."  By the time we get here, it's already been
21726          converted to host endianness, so we just need to sign- or
21727          zero-extend it as appropriate.  */
21728     case DW_FORM_data1:
21729       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21730       break;
21731     case DW_FORM_data2:
21732       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21733       break;
21734     case DW_FORM_data4:
21735       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21736       break;
21737     case DW_FORM_data8:
21738       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21739       break;
21740
21741     case DW_FORM_sdata:
21742     case DW_FORM_implicit_const:
21743       *value = DW_SND (attr);
21744       break;
21745
21746     case DW_FORM_udata:
21747       *value = DW_UNSND (attr);
21748       break;
21749
21750     default:
21751       complaint (_("unsupported const value attribute form: '%s'"),
21752                  dwarf_form_name (attr->form));
21753       *value = 0;
21754       break;
21755     }
21756 }
21757
21758
21759 /* Copy constant value from an attribute to a symbol.  */
21760
21761 static void
21762 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21763                     struct dwarf2_cu *cu)
21764 {
21765   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21766   LONGEST value;
21767   const gdb_byte *bytes;
21768   struct dwarf2_locexpr_baton *baton;
21769
21770   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21771                            SYMBOL_PRINT_NAME (sym),
21772                            &objfile->objfile_obstack, cu,
21773                            &value, &bytes, &baton);
21774
21775   if (baton != NULL)
21776     {
21777       SYMBOL_LOCATION_BATON (sym) = baton;
21778       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21779     }
21780   else if (bytes != NULL)
21781      {
21782       SYMBOL_VALUE_BYTES (sym) = bytes;
21783       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21784     }
21785   else
21786     {
21787       SYMBOL_VALUE (sym) = value;
21788       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21789     }
21790 }
21791
21792 /* Return the type of the die in question using its DW_AT_type attribute.  */
21793
21794 static struct type *
21795 die_type (struct die_info *die, struct dwarf2_cu *cu)
21796 {
21797   struct attribute *type_attr;
21798
21799   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21800   if (!type_attr)
21801     {
21802       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21803       /* A missing DW_AT_type represents a void type.  */
21804       return objfile_type (objfile)->builtin_void;
21805     }
21806
21807   return lookup_die_type (die, type_attr, cu);
21808 }
21809
21810 /* True iff CU's producer generates GNAT Ada auxiliary information
21811    that allows to find parallel types through that information instead
21812    of having to do expensive parallel lookups by type name.  */
21813
21814 static int
21815 need_gnat_info (struct dwarf2_cu *cu)
21816 {
21817   /* Assume that the Ada compiler was GNAT, which always produces
21818      the auxiliary information.  */
21819   return (cu->language == language_ada);
21820 }
21821
21822 /* Return the auxiliary type of the die in question using its
21823    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21824    attribute is not present.  */
21825
21826 static struct type *
21827 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21828 {
21829   struct attribute *type_attr;
21830
21831   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21832   if (!type_attr)
21833     return NULL;
21834
21835   return lookup_die_type (die, type_attr, cu);
21836 }
21837
21838 /* If DIE has a descriptive_type attribute, then set the TYPE's
21839    descriptive type accordingly.  */
21840
21841 static void
21842 set_descriptive_type (struct type *type, struct die_info *die,
21843                       struct dwarf2_cu *cu)
21844 {
21845   struct type *descriptive_type = die_descriptive_type (die, cu);
21846
21847   if (descriptive_type)
21848     {
21849       ALLOCATE_GNAT_AUX_TYPE (type);
21850       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21851     }
21852 }
21853
21854 /* Return the containing type of the die in question using its
21855    DW_AT_containing_type attribute.  */
21856
21857 static struct type *
21858 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21859 {
21860   struct attribute *type_attr;
21861   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21862
21863   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21864   if (!type_attr)
21865     error (_("Dwarf Error: Problem turning containing type into gdb type "
21866              "[in module %s]"), objfile_name (objfile));
21867
21868   return lookup_die_type (die, type_attr, cu);
21869 }
21870
21871 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21872
21873 static struct type *
21874 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21875 {
21876   struct dwarf2_per_objfile *dwarf2_per_objfile
21877     = cu->per_cu->dwarf2_per_objfile;
21878   struct objfile *objfile = dwarf2_per_objfile->objfile;
21879   char *saved;
21880
21881   std::string message
21882     = string_printf (_("<unknown type in %s, CU %s, DIE %s>"),
21883                      objfile_name (objfile),
21884                      sect_offset_str (cu->header.sect_off),
21885                      sect_offset_str (die->sect_off));
21886   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21887                                   message.c_str (), message.length ());
21888
21889   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21890 }
21891
21892 /* Look up the type of DIE in CU using its type attribute ATTR.
21893    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21894    DW_AT_containing_type.
21895    If there is no type substitute an error marker.  */
21896
21897 static struct type *
21898 lookup_die_type (struct die_info *die, const struct attribute *attr,
21899                  struct dwarf2_cu *cu)
21900 {
21901   struct dwarf2_per_objfile *dwarf2_per_objfile
21902     = cu->per_cu->dwarf2_per_objfile;
21903   struct objfile *objfile = dwarf2_per_objfile->objfile;
21904   struct type *this_type;
21905
21906   gdb_assert (attr->name == DW_AT_type
21907               || attr->name == DW_AT_GNAT_descriptive_type
21908               || attr->name == DW_AT_containing_type);
21909
21910   /* First see if we have it cached.  */
21911
21912   if (attr->form == DW_FORM_GNU_ref_alt)
21913     {
21914       struct dwarf2_per_cu_data *per_cu;
21915       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21916
21917       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21918                                                  dwarf2_per_objfile);
21919       this_type = get_die_type_at_offset (sect_off, per_cu);
21920     }
21921   else if (attr_form_is_ref (attr))
21922     {
21923       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21924
21925       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21926     }
21927   else if (attr->form == DW_FORM_ref_sig8)
21928     {
21929       ULONGEST signature = DW_SIGNATURE (attr);
21930
21931       return get_signatured_type (die, signature, cu);
21932     }
21933   else
21934     {
21935       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
21936                    " at %s [in module %s]"),
21937                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21938                  objfile_name (objfile));
21939       return build_error_marker_type (cu, die);
21940     }
21941
21942   /* If not cached we need to read it in.  */
21943
21944   if (this_type == NULL)
21945     {
21946       struct die_info *type_die = NULL;
21947       struct dwarf2_cu *type_cu = cu;
21948
21949       if (attr_form_is_ref (attr))
21950         type_die = follow_die_ref (die, attr, &type_cu);
21951       if (type_die == NULL)
21952         return build_error_marker_type (cu, die);
21953       /* If we find the type now, it's probably because the type came
21954          from an inter-CU reference and the type's CU got expanded before
21955          ours.  */
21956       this_type = read_type_die (type_die, type_cu);
21957     }
21958
21959   /* If we still don't have a type use an error marker.  */
21960
21961   if (this_type == NULL)
21962     return build_error_marker_type (cu, die);
21963
21964   return this_type;
21965 }
21966
21967 /* Return the type in DIE, CU.
21968    Returns NULL for invalid types.
21969
21970    This first does a lookup in die_type_hash,
21971    and only reads the die in if necessary.
21972
21973    NOTE: This can be called when reading in partial or full symbols.  */
21974
21975 static struct type *
21976 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21977 {
21978   struct type *this_type;
21979
21980   this_type = get_die_type (die, cu);
21981   if (this_type)
21982     return this_type;
21983
21984   return read_type_die_1 (die, cu);
21985 }
21986
21987 /* Read the type in DIE, CU.
21988    Returns NULL for invalid types.  */
21989
21990 static struct type *
21991 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21992 {
21993   struct type *this_type = NULL;
21994
21995   switch (die->tag)
21996     {
21997     case DW_TAG_class_type:
21998     case DW_TAG_interface_type:
21999     case DW_TAG_structure_type:
22000     case DW_TAG_union_type:
22001       this_type = read_structure_type (die, cu);
22002       break;
22003     case DW_TAG_enumeration_type:
22004       this_type = read_enumeration_type (die, cu);
22005       break;
22006     case DW_TAG_subprogram:
22007     case DW_TAG_subroutine_type:
22008     case DW_TAG_inlined_subroutine:
22009       this_type = read_subroutine_type (die, cu);
22010       break;
22011     case DW_TAG_array_type:
22012       this_type = read_array_type (die, cu);
22013       break;
22014     case DW_TAG_set_type:
22015       this_type = read_set_type (die, cu);
22016       break;
22017     case DW_TAG_pointer_type:
22018       this_type = read_tag_pointer_type (die, cu);
22019       break;
22020     case DW_TAG_ptr_to_member_type:
22021       this_type = read_tag_ptr_to_member_type (die, cu);
22022       break;
22023     case DW_TAG_reference_type:
22024       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
22025       break;
22026     case DW_TAG_rvalue_reference_type:
22027       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
22028       break;
22029     case DW_TAG_const_type:
22030       this_type = read_tag_const_type (die, cu);
22031       break;
22032     case DW_TAG_volatile_type:
22033       this_type = read_tag_volatile_type (die, cu);
22034       break;
22035     case DW_TAG_restrict_type:
22036       this_type = read_tag_restrict_type (die, cu);
22037       break;
22038     case DW_TAG_string_type:
22039       this_type = read_tag_string_type (die, cu);
22040       break;
22041     case DW_TAG_typedef:
22042       this_type = read_typedef (die, cu);
22043       break;
22044     case DW_TAG_subrange_type:
22045       this_type = read_subrange_type (die, cu);
22046       break;
22047     case DW_TAG_base_type:
22048       this_type = read_base_type (die, cu);
22049       break;
22050     case DW_TAG_unspecified_type:
22051       this_type = read_unspecified_type (die, cu);
22052       break;
22053     case DW_TAG_namespace:
22054       this_type = read_namespace_type (die, cu);
22055       break;
22056     case DW_TAG_module:
22057       this_type = read_module_type (die, cu);
22058       break;
22059     case DW_TAG_atomic_type:
22060       this_type = read_tag_atomic_type (die, cu);
22061       break;
22062     default:
22063       complaint (_("unexpected tag in read_type_die: '%s'"),
22064                  dwarf_tag_name (die->tag));
22065       break;
22066     }
22067
22068   return this_type;
22069 }
22070
22071 /* See if we can figure out if the class lives in a namespace.  We do
22072    this by looking for a member function; its demangled name will
22073    contain namespace info, if there is any.
22074    Return the computed name or NULL.
22075    Space for the result is allocated on the objfile's obstack.
22076    This is the full-die version of guess_partial_die_structure_name.
22077    In this case we know DIE has no useful parent.  */
22078
22079 static char *
22080 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
22081 {
22082   struct die_info *spec_die;
22083   struct dwarf2_cu *spec_cu;
22084   struct die_info *child;
22085   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22086
22087   spec_cu = cu;
22088   spec_die = die_specification (die, &spec_cu);
22089   if (spec_die != NULL)
22090     {
22091       die = spec_die;
22092       cu = spec_cu;
22093     }
22094
22095   for (child = die->child;
22096        child != NULL;
22097        child = child->sibling)
22098     {
22099       if (child->tag == DW_TAG_subprogram)
22100         {
22101           const char *linkage_name = dw2_linkage_name (child, cu);
22102
22103           if (linkage_name != NULL)
22104             {
22105               char *actual_name
22106                 = language_class_name_from_physname (cu->language_defn,
22107                                                      linkage_name);
22108               char *name = NULL;
22109
22110               if (actual_name != NULL)
22111                 {
22112                   const char *die_name = dwarf2_name (die, cu);
22113
22114                   if (die_name != NULL
22115                       && strcmp (die_name, actual_name) != 0)
22116                     {
22117                       /* Strip off the class name from the full name.
22118                          We want the prefix.  */
22119                       int die_name_len = strlen (die_name);
22120                       int actual_name_len = strlen (actual_name);
22121
22122                       /* Test for '::' as a sanity check.  */
22123                       if (actual_name_len > die_name_len + 2
22124                           && actual_name[actual_name_len
22125                                          - die_name_len - 1] == ':')
22126                         name = (char *) obstack_copy0 (
22127                           &objfile->per_bfd->storage_obstack,
22128                           actual_name, actual_name_len - die_name_len - 2);
22129                     }
22130                 }
22131               xfree (actual_name);
22132               return name;
22133             }
22134         }
22135     }
22136
22137   return NULL;
22138 }
22139
22140 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22141    prefix part in such case.  See
22142    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22143
22144 static const char *
22145 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22146 {
22147   struct attribute *attr;
22148   const char *base;
22149
22150   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22151       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22152     return NULL;
22153
22154   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22155     return NULL;
22156
22157   attr = dw2_linkage_name_attr (die, cu);
22158   if (attr == NULL || DW_STRING (attr) == NULL)
22159     return NULL;
22160
22161   /* dwarf2_name had to be already called.  */
22162   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22163
22164   /* Strip the base name, keep any leading namespaces/classes.  */
22165   base = strrchr (DW_STRING (attr), ':');
22166   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22167     return "";
22168
22169   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22170   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22171                                  DW_STRING (attr),
22172                                  &base[-1] - DW_STRING (attr));
22173 }
22174
22175 /* Return the name of the namespace/class that DIE is defined within,
22176    or "" if we can't tell.  The caller should not xfree the result.
22177
22178    For example, if we're within the method foo() in the following
22179    code:
22180
22181    namespace N {
22182      class C {
22183        void foo () {
22184        }
22185      };
22186    }
22187
22188    then determine_prefix on foo's die will return "N::C".  */
22189
22190 static const char *
22191 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22192 {
22193   struct dwarf2_per_objfile *dwarf2_per_objfile
22194     = cu->per_cu->dwarf2_per_objfile;
22195   struct die_info *parent, *spec_die;
22196   struct dwarf2_cu *spec_cu;
22197   struct type *parent_type;
22198   const char *retval;
22199
22200   if (cu->language != language_cplus
22201       && cu->language != language_fortran && cu->language != language_d
22202       && cu->language != language_rust)
22203     return "";
22204
22205   retval = anonymous_struct_prefix (die, cu);
22206   if (retval)
22207     return retval;
22208
22209   /* We have to be careful in the presence of DW_AT_specification.
22210      For example, with GCC 3.4, given the code
22211
22212      namespace N {
22213        void foo() {
22214          // Definition of N::foo.
22215        }
22216      }
22217
22218      then we'll have a tree of DIEs like this:
22219
22220      1: DW_TAG_compile_unit
22221        2: DW_TAG_namespace        // N
22222          3: DW_TAG_subprogram     // declaration of N::foo
22223        4: DW_TAG_subprogram       // definition of N::foo
22224             DW_AT_specification   // refers to die #3
22225
22226      Thus, when processing die #4, we have to pretend that we're in
22227      the context of its DW_AT_specification, namely the contex of die
22228      #3.  */
22229   spec_cu = cu;
22230   spec_die = die_specification (die, &spec_cu);
22231   if (spec_die == NULL)
22232     parent = die->parent;
22233   else
22234     {
22235       parent = spec_die->parent;
22236       cu = spec_cu;
22237     }
22238
22239   if (parent == NULL)
22240     return "";
22241   else if (parent->building_fullname)
22242     {
22243       const char *name;
22244       const char *parent_name;
22245
22246       /* It has been seen on RealView 2.2 built binaries,
22247          DW_TAG_template_type_param types actually _defined_ as
22248          children of the parent class:
22249
22250          enum E {};
22251          template class <class Enum> Class{};
22252          Class<enum E> class_e;
22253
22254          1: DW_TAG_class_type (Class)
22255            2: DW_TAG_enumeration_type (E)
22256              3: DW_TAG_enumerator (enum1:0)
22257              3: DW_TAG_enumerator (enum2:1)
22258              ...
22259            2: DW_TAG_template_type_param
22260               DW_AT_type  DW_FORM_ref_udata (E)
22261
22262          Besides being broken debug info, it can put GDB into an
22263          infinite loop.  Consider:
22264
22265          When we're building the full name for Class<E>, we'll start
22266          at Class, and go look over its template type parameters,
22267          finding E.  We'll then try to build the full name of E, and
22268          reach here.  We're now trying to build the full name of E,
22269          and look over the parent DIE for containing scope.  In the
22270          broken case, if we followed the parent DIE of E, we'd again
22271          find Class, and once again go look at its template type
22272          arguments, etc., etc.  Simply don't consider such parent die
22273          as source-level parent of this die (it can't be, the language
22274          doesn't allow it), and break the loop here.  */
22275       name = dwarf2_name (die, cu);
22276       parent_name = dwarf2_name (parent, cu);
22277       complaint (_("template param type '%s' defined within parent '%s'"),
22278                  name ? name : "<unknown>",
22279                  parent_name ? parent_name : "<unknown>");
22280       return "";
22281     }
22282   else
22283     switch (parent->tag)
22284       {
22285       case DW_TAG_namespace:
22286         parent_type = read_type_die (parent, cu);
22287         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22288            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22289            Work around this problem here.  */
22290         if (cu->language == language_cplus
22291             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22292           return "";
22293         /* We give a name to even anonymous namespaces.  */
22294         return TYPE_NAME (parent_type);
22295       case DW_TAG_class_type:
22296       case DW_TAG_interface_type:
22297       case DW_TAG_structure_type:
22298       case DW_TAG_union_type:
22299       case DW_TAG_module:
22300         parent_type = read_type_die (parent, cu);
22301         if (TYPE_NAME (parent_type) != NULL)
22302           return TYPE_NAME (parent_type);
22303         else
22304           /* An anonymous structure is only allowed non-static data
22305              members; no typedefs, no member functions, et cetera.
22306              So it does not need a prefix.  */
22307           return "";
22308       case DW_TAG_compile_unit:
22309       case DW_TAG_partial_unit:
22310         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22311         if (cu->language == language_cplus
22312             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22313             && die->child != NULL
22314             && (die->tag == DW_TAG_class_type
22315                 || die->tag == DW_TAG_structure_type
22316                 || die->tag == DW_TAG_union_type))
22317           {
22318             char *name = guess_full_die_structure_name (die, cu);
22319             if (name != NULL)
22320               return name;
22321           }
22322         return "";
22323       case DW_TAG_enumeration_type:
22324         parent_type = read_type_die (parent, cu);
22325         if (TYPE_DECLARED_CLASS (parent_type))
22326           {
22327             if (TYPE_NAME (parent_type) != NULL)
22328               return TYPE_NAME (parent_type);
22329             return "";
22330           }
22331         /* Fall through.  */
22332       default:
22333         return determine_prefix (parent, cu);
22334       }
22335 }
22336
22337 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22338    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22339    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22340    an obconcat, otherwise allocate storage for the result.  The CU argument is
22341    used to determine the language and hence, the appropriate separator.  */
22342
22343 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22344
22345 static char *
22346 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22347                  int physname, struct dwarf2_cu *cu)
22348 {
22349   const char *lead = "";
22350   const char *sep;
22351
22352   if (suffix == NULL || suffix[0] == '\0'
22353       || prefix == NULL || prefix[0] == '\0')
22354     sep = "";
22355   else if (cu->language == language_d)
22356     {
22357       /* For D, the 'main' function could be defined in any module, but it
22358          should never be prefixed.  */
22359       if (strcmp (suffix, "D main") == 0)
22360         {
22361           prefix = "";
22362           sep = "";
22363         }
22364       else
22365         sep = ".";
22366     }
22367   else if (cu->language == language_fortran && physname)
22368     {
22369       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22370          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22371
22372       lead = "__";
22373       sep = "_MOD_";
22374     }
22375   else
22376     sep = "::";
22377
22378   if (prefix == NULL)
22379     prefix = "";
22380   if (suffix == NULL)
22381     suffix = "";
22382
22383   if (obs == NULL)
22384     {
22385       char *retval
22386         = ((char *)
22387            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22388
22389       strcpy (retval, lead);
22390       strcat (retval, prefix);
22391       strcat (retval, sep);
22392       strcat (retval, suffix);
22393       return retval;
22394     }
22395   else
22396     {
22397       /* We have an obstack.  */
22398       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22399     }
22400 }
22401
22402 /* Return sibling of die, NULL if no sibling.  */
22403
22404 static struct die_info *
22405 sibling_die (struct die_info *die)
22406 {
22407   return die->sibling;
22408 }
22409
22410 /* Get name of a die, return NULL if not found.  */
22411
22412 static const char *
22413 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22414                           struct obstack *obstack)
22415 {
22416   if (name && cu->language == language_cplus)
22417     {
22418       std::string canon_name = cp_canonicalize_string (name);
22419
22420       if (!canon_name.empty ())
22421         {
22422           if (canon_name != name)
22423             name = (const char *) obstack_copy0 (obstack,
22424                                                  canon_name.c_str (),
22425                                                  canon_name.length ());
22426         }
22427     }
22428
22429   return name;
22430 }
22431
22432 /* Get name of a die, return NULL if not found.
22433    Anonymous namespaces are converted to their magic string.  */
22434
22435 static const char *
22436 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22437 {
22438   struct attribute *attr;
22439   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22440
22441   attr = dwarf2_attr (die, DW_AT_name, cu);
22442   if ((!attr || !DW_STRING (attr))
22443       && die->tag != DW_TAG_namespace
22444       && die->tag != DW_TAG_class_type
22445       && die->tag != DW_TAG_interface_type
22446       && die->tag != DW_TAG_structure_type
22447       && die->tag != DW_TAG_union_type)
22448     return NULL;
22449
22450   switch (die->tag)
22451     {
22452     case DW_TAG_compile_unit:
22453     case DW_TAG_partial_unit:
22454       /* Compilation units have a DW_AT_name that is a filename, not
22455          a source language identifier.  */
22456     case DW_TAG_enumeration_type:
22457     case DW_TAG_enumerator:
22458       /* These tags always have simple identifiers already; no need
22459          to canonicalize them.  */
22460       return DW_STRING (attr);
22461
22462     case DW_TAG_namespace:
22463       if (attr != NULL && DW_STRING (attr) != NULL)
22464         return DW_STRING (attr);
22465       return CP_ANONYMOUS_NAMESPACE_STR;
22466
22467     case DW_TAG_class_type:
22468     case DW_TAG_interface_type:
22469     case DW_TAG_structure_type:
22470     case DW_TAG_union_type:
22471       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22472          structures or unions.  These were of the form "._%d" in GCC 4.1,
22473          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22474          and GCC 4.4.  We work around this problem by ignoring these.  */
22475       if (attr && DW_STRING (attr)
22476           && (startswith (DW_STRING (attr), "._")
22477               || startswith (DW_STRING (attr), "<anonymous")))
22478         return NULL;
22479
22480       /* GCC might emit a nameless typedef that has a linkage name.  See
22481          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22482       if (!attr || DW_STRING (attr) == NULL)
22483         {
22484           char *demangled = NULL;
22485
22486           attr = dw2_linkage_name_attr (die, cu);
22487           if (attr == NULL || DW_STRING (attr) == NULL)
22488             return NULL;
22489
22490           /* Avoid demangling DW_STRING (attr) the second time on a second
22491              call for the same DIE.  */
22492           if (!DW_STRING_IS_CANONICAL (attr))
22493             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22494
22495           if (demangled)
22496             {
22497               const char *base;
22498
22499               /* FIXME: we already did this for the partial symbol... */
22500               DW_STRING (attr)
22501                 = ((const char *)
22502                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22503                                   demangled, strlen (demangled)));
22504               DW_STRING_IS_CANONICAL (attr) = 1;
22505               xfree (demangled);
22506
22507               /* Strip any leading namespaces/classes, keep only the base name.
22508                  DW_AT_name for named DIEs does not contain the prefixes.  */
22509               base = strrchr (DW_STRING (attr), ':');
22510               if (base && base > DW_STRING (attr) && base[-1] == ':')
22511                 return &base[1];
22512               else
22513                 return DW_STRING (attr);
22514             }
22515         }
22516       break;
22517
22518     default:
22519       break;
22520     }
22521
22522   if (!DW_STRING_IS_CANONICAL (attr))
22523     {
22524       DW_STRING (attr)
22525         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22526                                     &objfile->per_bfd->storage_obstack);
22527       DW_STRING_IS_CANONICAL (attr) = 1;
22528     }
22529   return DW_STRING (attr);
22530 }
22531
22532 /* Return the die that this die in an extension of, or NULL if there
22533    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22534    containing the return value on output.  */
22535
22536 static struct die_info *
22537 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22538 {
22539   struct attribute *attr;
22540
22541   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22542   if (attr == NULL)
22543     return NULL;
22544
22545   return follow_die_ref (die, attr, ext_cu);
22546 }
22547
22548 /* Convert a DIE tag into its string name.  */
22549
22550 static const char *
22551 dwarf_tag_name (unsigned tag)
22552 {
22553   const char *name = get_DW_TAG_name (tag);
22554
22555   if (name == NULL)
22556     return "DW_TAG_<unknown>";
22557
22558   return name;
22559 }
22560
22561 /* Convert a DWARF attribute code into its string name.  */
22562
22563 static const char *
22564 dwarf_attr_name (unsigned attr)
22565 {
22566   const char *name;
22567
22568 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22569   if (attr == DW_AT_MIPS_fde)
22570     return "DW_AT_MIPS_fde";
22571 #else
22572   if (attr == DW_AT_HP_block_index)
22573     return "DW_AT_HP_block_index";
22574 #endif
22575
22576   name = get_DW_AT_name (attr);
22577
22578   if (name == NULL)
22579     return "DW_AT_<unknown>";
22580
22581   return name;
22582 }
22583
22584 /* Convert a DWARF value form code into its string name.  */
22585
22586 static const char *
22587 dwarf_form_name (unsigned form)
22588 {
22589   const char *name = get_DW_FORM_name (form);
22590
22591   if (name == NULL)
22592     return "DW_FORM_<unknown>";
22593
22594   return name;
22595 }
22596
22597 static const char *
22598 dwarf_bool_name (unsigned mybool)
22599 {
22600   if (mybool)
22601     return "TRUE";
22602   else
22603     return "FALSE";
22604 }
22605
22606 /* Convert a DWARF type code into its string name.  */
22607
22608 static const char *
22609 dwarf_type_encoding_name (unsigned enc)
22610 {
22611   const char *name = get_DW_ATE_name (enc);
22612
22613   if (name == NULL)
22614     return "DW_ATE_<unknown>";
22615
22616   return name;
22617 }
22618
22619 static void
22620 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22621 {
22622   unsigned int i;
22623
22624   print_spaces (indent, f);
22625   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22626                       dwarf_tag_name (die->tag), die->abbrev,
22627                       sect_offset_str (die->sect_off));
22628
22629   if (die->parent != NULL)
22630     {
22631       print_spaces (indent, f);
22632       fprintf_unfiltered (f, "  parent at offset: %s\n",
22633                           sect_offset_str (die->parent->sect_off));
22634     }
22635
22636   print_spaces (indent, f);
22637   fprintf_unfiltered (f, "  has children: %s\n",
22638            dwarf_bool_name (die->child != NULL));
22639
22640   print_spaces (indent, f);
22641   fprintf_unfiltered (f, "  attributes:\n");
22642
22643   for (i = 0; i < die->num_attrs; ++i)
22644     {
22645       print_spaces (indent, f);
22646       fprintf_unfiltered (f, "    %s (%s) ",
22647                dwarf_attr_name (die->attrs[i].name),
22648                dwarf_form_name (die->attrs[i].form));
22649
22650       switch (die->attrs[i].form)
22651         {
22652         case DW_FORM_addr:
22653         case DW_FORM_GNU_addr_index:
22654           fprintf_unfiltered (f, "address: ");
22655           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22656           break;
22657         case DW_FORM_block2:
22658         case DW_FORM_block4:
22659         case DW_FORM_block:
22660         case DW_FORM_block1:
22661           fprintf_unfiltered (f, "block: size %s",
22662                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22663           break;
22664         case DW_FORM_exprloc:
22665           fprintf_unfiltered (f, "expression: size %s",
22666                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22667           break;
22668         case DW_FORM_data16:
22669           fprintf_unfiltered (f, "constant of 16 bytes");
22670           break;
22671         case DW_FORM_ref_addr:
22672           fprintf_unfiltered (f, "ref address: ");
22673           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22674           break;
22675         case DW_FORM_GNU_ref_alt:
22676           fprintf_unfiltered (f, "alt ref address: ");
22677           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22678           break;
22679         case DW_FORM_ref1:
22680         case DW_FORM_ref2:
22681         case DW_FORM_ref4:
22682         case DW_FORM_ref8:
22683         case DW_FORM_ref_udata:
22684           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22685                               (long) (DW_UNSND (&die->attrs[i])));
22686           break;
22687         case DW_FORM_data1:
22688         case DW_FORM_data2:
22689         case DW_FORM_data4:
22690         case DW_FORM_data8:
22691         case DW_FORM_udata:
22692         case DW_FORM_sdata:
22693           fprintf_unfiltered (f, "constant: %s",
22694                               pulongest (DW_UNSND (&die->attrs[i])));
22695           break;
22696         case DW_FORM_sec_offset:
22697           fprintf_unfiltered (f, "section offset: %s",
22698                               pulongest (DW_UNSND (&die->attrs[i])));
22699           break;
22700         case DW_FORM_ref_sig8:
22701           fprintf_unfiltered (f, "signature: %s",
22702                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22703           break;
22704         case DW_FORM_string:
22705         case DW_FORM_strp:
22706         case DW_FORM_line_strp:
22707         case DW_FORM_GNU_str_index:
22708         case DW_FORM_GNU_strp_alt:
22709           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22710                    DW_STRING (&die->attrs[i])
22711                    ? DW_STRING (&die->attrs[i]) : "",
22712                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22713           break;
22714         case DW_FORM_flag:
22715           if (DW_UNSND (&die->attrs[i]))
22716             fprintf_unfiltered (f, "flag: TRUE");
22717           else
22718             fprintf_unfiltered (f, "flag: FALSE");
22719           break;
22720         case DW_FORM_flag_present:
22721           fprintf_unfiltered (f, "flag: TRUE");
22722           break;
22723         case DW_FORM_indirect:
22724           /* The reader will have reduced the indirect form to
22725              the "base form" so this form should not occur.  */
22726           fprintf_unfiltered (f, 
22727                               "unexpected attribute form: DW_FORM_indirect");
22728           break;
22729         case DW_FORM_implicit_const:
22730           fprintf_unfiltered (f, "constant: %s",
22731                               plongest (DW_SND (&die->attrs[i])));
22732           break;
22733         default:
22734           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22735                    die->attrs[i].form);
22736           break;
22737         }
22738       fprintf_unfiltered (f, "\n");
22739     }
22740 }
22741
22742 static void
22743 dump_die_for_error (struct die_info *die)
22744 {
22745   dump_die_shallow (gdb_stderr, 0, die);
22746 }
22747
22748 static void
22749 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22750 {
22751   int indent = level * 4;
22752
22753   gdb_assert (die != NULL);
22754
22755   if (level >= max_level)
22756     return;
22757
22758   dump_die_shallow (f, indent, die);
22759
22760   if (die->child != NULL)
22761     {
22762       print_spaces (indent, f);
22763       fprintf_unfiltered (f, "  Children:");
22764       if (level + 1 < max_level)
22765         {
22766           fprintf_unfiltered (f, "\n");
22767           dump_die_1 (f, level + 1, max_level, die->child);
22768         }
22769       else
22770         {
22771           fprintf_unfiltered (f,
22772                               " [not printed, max nesting level reached]\n");
22773         }
22774     }
22775
22776   if (die->sibling != NULL && level > 0)
22777     {
22778       dump_die_1 (f, level, max_level, die->sibling);
22779     }
22780 }
22781
22782 /* This is called from the pdie macro in gdbinit.in.
22783    It's not static so gcc will keep a copy callable from gdb.  */
22784
22785 void
22786 dump_die (struct die_info *die, int max_level)
22787 {
22788   dump_die_1 (gdb_stdlog, 0, max_level, die);
22789 }
22790
22791 static void
22792 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22793 {
22794   void **slot;
22795
22796   slot = htab_find_slot_with_hash (cu->die_hash, die,
22797                                    to_underlying (die->sect_off),
22798                                    INSERT);
22799
22800   *slot = die;
22801 }
22802
22803 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22804    required kind.  */
22805
22806 static sect_offset
22807 dwarf2_get_ref_die_offset (const struct attribute *attr)
22808 {
22809   if (attr_form_is_ref (attr))
22810     return (sect_offset) DW_UNSND (attr);
22811
22812   complaint (_("unsupported die ref attribute form: '%s'"),
22813              dwarf_form_name (attr->form));
22814   return {};
22815 }
22816
22817 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22818  * the value held by the attribute is not constant.  */
22819
22820 static LONGEST
22821 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22822 {
22823   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22824     return DW_SND (attr);
22825   else if (attr->form == DW_FORM_udata
22826            || attr->form == DW_FORM_data1
22827            || attr->form == DW_FORM_data2
22828            || attr->form == DW_FORM_data4
22829            || attr->form == DW_FORM_data8)
22830     return DW_UNSND (attr);
22831   else
22832     {
22833       /* For DW_FORM_data16 see attr_form_is_constant.  */
22834       complaint (_("Attribute value is not a constant (%s)"),
22835                  dwarf_form_name (attr->form));
22836       return default_value;
22837     }
22838 }
22839
22840 /* Follow reference or signature attribute ATTR of SRC_DIE.
22841    On entry *REF_CU is the CU of SRC_DIE.
22842    On exit *REF_CU is the CU of the result.  */
22843
22844 static struct die_info *
22845 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22846                        struct dwarf2_cu **ref_cu)
22847 {
22848   struct die_info *die;
22849
22850   if (attr_form_is_ref (attr))
22851     die = follow_die_ref (src_die, attr, ref_cu);
22852   else if (attr->form == DW_FORM_ref_sig8)
22853     die = follow_die_sig (src_die, attr, ref_cu);
22854   else
22855     {
22856       dump_die_for_error (src_die);
22857       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22858              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22859     }
22860
22861   return die;
22862 }
22863
22864 /* Follow reference OFFSET.
22865    On entry *REF_CU is the CU of the source die referencing OFFSET.
22866    On exit *REF_CU is the CU of the result.
22867    Returns NULL if OFFSET is invalid.  */
22868
22869 static struct die_info *
22870 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22871                    struct dwarf2_cu **ref_cu)
22872 {
22873   struct die_info temp_die;
22874   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22875   struct dwarf2_per_objfile *dwarf2_per_objfile
22876     = cu->per_cu->dwarf2_per_objfile;
22877
22878   gdb_assert (cu->per_cu != NULL);
22879
22880   target_cu = cu;
22881
22882   if (cu->per_cu->is_debug_types)
22883     {
22884       /* .debug_types CUs cannot reference anything outside their CU.
22885          If they need to, they have to reference a signatured type via
22886          DW_FORM_ref_sig8.  */
22887       if (!offset_in_cu_p (&cu->header, sect_off))
22888         return NULL;
22889     }
22890   else if (offset_in_dwz != cu->per_cu->is_dwz
22891            || !offset_in_cu_p (&cu->header, sect_off))
22892     {
22893       struct dwarf2_per_cu_data *per_cu;
22894
22895       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22896                                                  dwarf2_per_objfile);
22897
22898       /* If necessary, add it to the queue and load its DIEs.  */
22899       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22900         load_full_comp_unit (per_cu, false, cu->language);
22901
22902       target_cu = per_cu->cu;
22903     }
22904   else if (cu->dies == NULL)
22905     {
22906       /* We're loading full DIEs during partial symbol reading.  */
22907       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22908       load_full_comp_unit (cu->per_cu, false, language_minimal);
22909     }
22910
22911   *ref_cu = target_cu;
22912   temp_die.sect_off = sect_off;
22913   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22914                                                   &temp_die,
22915                                                   to_underlying (sect_off));
22916 }
22917
22918 /* Follow reference attribute ATTR of SRC_DIE.
22919    On entry *REF_CU is the CU of SRC_DIE.
22920    On exit *REF_CU is the CU of the result.  */
22921
22922 static struct die_info *
22923 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22924                 struct dwarf2_cu **ref_cu)
22925 {
22926   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22927   struct dwarf2_cu *cu = *ref_cu;
22928   struct die_info *die;
22929
22930   die = follow_die_offset (sect_off,
22931                            (attr->form == DW_FORM_GNU_ref_alt
22932                             || cu->per_cu->is_dwz),
22933                            ref_cu);
22934   if (!die)
22935     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22936            "at %s [in module %s]"),
22937            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22938            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22939
22940   return die;
22941 }
22942
22943 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22944    Returned value is intended for DW_OP_call*.  Returned
22945    dwarf2_locexpr_baton->data has lifetime of
22946    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22947
22948 struct dwarf2_locexpr_baton
22949 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22950                                struct dwarf2_per_cu_data *per_cu,
22951                                CORE_ADDR (*get_frame_pc) (void *baton),
22952                                void *baton)
22953 {
22954   struct dwarf2_cu *cu;
22955   struct die_info *die;
22956   struct attribute *attr;
22957   struct dwarf2_locexpr_baton retval;
22958   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22959   struct objfile *objfile = dwarf2_per_objfile->objfile;
22960
22961   if (per_cu->cu == NULL)
22962     load_cu (per_cu, false);
22963   cu = per_cu->cu;
22964   if (cu == NULL)
22965     {
22966       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22967          Instead just throw an error, not much else we can do.  */
22968       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22969              sect_offset_str (sect_off), objfile_name (objfile));
22970     }
22971
22972   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22973   if (!die)
22974     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22975            sect_offset_str (sect_off), objfile_name (objfile));
22976
22977   attr = dwarf2_attr (die, DW_AT_location, cu);
22978   if (!attr)
22979     {
22980       /* DWARF: "If there is no such attribute, then there is no effect.".
22981          DATA is ignored if SIZE is 0.  */
22982
22983       retval.data = NULL;
22984       retval.size = 0;
22985     }
22986   else if (attr_form_is_section_offset (attr))
22987     {
22988       struct dwarf2_loclist_baton loclist_baton;
22989       CORE_ADDR pc = (*get_frame_pc) (baton);
22990       size_t size;
22991
22992       fill_in_loclist_baton (cu, &loclist_baton, attr);
22993
22994       retval.data = dwarf2_find_location_expression (&loclist_baton,
22995                                                      &size, pc);
22996       retval.size = size;
22997     }
22998   else
22999     {
23000       if (!attr_form_is_block (attr))
23001         error (_("Dwarf Error: DIE at %s referenced in module %s "
23002                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
23003                sect_offset_str (sect_off), objfile_name (objfile));
23004
23005       retval.data = DW_BLOCK (attr)->data;
23006       retval.size = DW_BLOCK (attr)->size;
23007     }
23008   retval.per_cu = cu->per_cu;
23009
23010   age_cached_comp_units (dwarf2_per_objfile);
23011
23012   return retval;
23013 }
23014
23015 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
23016    offset.  */
23017
23018 struct dwarf2_locexpr_baton
23019 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
23020                              struct dwarf2_per_cu_data *per_cu,
23021                              CORE_ADDR (*get_frame_pc) (void *baton),
23022                              void *baton)
23023 {
23024   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
23025
23026   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
23027 }
23028
23029 /* Write a constant of a given type as target-ordered bytes into
23030    OBSTACK.  */
23031
23032 static const gdb_byte *
23033 write_constant_as_bytes (struct obstack *obstack,
23034                          enum bfd_endian byte_order,
23035                          struct type *type,
23036                          ULONGEST value,
23037                          LONGEST *len)
23038 {
23039   gdb_byte *result;
23040
23041   *len = TYPE_LENGTH (type);
23042   result = (gdb_byte *) obstack_alloc (obstack, *len);
23043   store_unsigned_integer (result, *len, byte_order, value);
23044
23045   return result;
23046 }
23047
23048 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
23049    pointer to the constant bytes and set LEN to the length of the
23050    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
23051    does not have a DW_AT_const_value, return NULL.  */
23052
23053 const gdb_byte *
23054 dwarf2_fetch_constant_bytes (sect_offset sect_off,
23055                              struct dwarf2_per_cu_data *per_cu,
23056                              struct obstack *obstack,
23057                              LONGEST *len)
23058 {
23059   struct dwarf2_cu *cu;
23060   struct die_info *die;
23061   struct attribute *attr;
23062   const gdb_byte *result = NULL;
23063   struct type *type;
23064   LONGEST value;
23065   enum bfd_endian byte_order;
23066   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
23067
23068   if (per_cu->cu == NULL)
23069     load_cu (per_cu, false);
23070   cu = per_cu->cu;
23071   if (cu == NULL)
23072     {
23073       /* We shouldn't get here for a dummy CU, but don't crash on the user.
23074          Instead just throw an error, not much else we can do.  */
23075       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
23076              sect_offset_str (sect_off), objfile_name (objfile));
23077     }
23078
23079   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23080   if (!die)
23081     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
23082            sect_offset_str (sect_off), objfile_name (objfile));
23083
23084   attr = dwarf2_attr (die, DW_AT_const_value, cu);
23085   if (attr == NULL)
23086     return NULL;
23087
23088   byte_order = (bfd_big_endian (objfile->obfd)
23089                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
23090
23091   switch (attr->form)
23092     {
23093     case DW_FORM_addr:
23094     case DW_FORM_GNU_addr_index:
23095       {
23096         gdb_byte *tem;
23097
23098         *len = cu->header.addr_size;
23099         tem = (gdb_byte *) obstack_alloc (obstack, *len);
23100         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
23101         result = tem;
23102       }
23103       break;
23104     case DW_FORM_string:
23105     case DW_FORM_strp:
23106     case DW_FORM_GNU_str_index:
23107     case DW_FORM_GNU_strp_alt:
23108       /* DW_STRING is already allocated on the objfile obstack, point
23109          directly to it.  */
23110       result = (const gdb_byte *) DW_STRING (attr);
23111       *len = strlen (DW_STRING (attr));
23112       break;
23113     case DW_FORM_block1:
23114     case DW_FORM_block2:
23115     case DW_FORM_block4:
23116     case DW_FORM_block:
23117     case DW_FORM_exprloc:
23118     case DW_FORM_data16:
23119       result = DW_BLOCK (attr)->data;
23120       *len = DW_BLOCK (attr)->size;
23121       break;
23122
23123       /* The DW_AT_const_value attributes are supposed to carry the
23124          symbol's value "represented as it would be on the target
23125          architecture."  By the time we get here, it's already been
23126          converted to host endianness, so we just need to sign- or
23127          zero-extend it as appropriate.  */
23128     case DW_FORM_data1:
23129       type = die_type (die, cu);
23130       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23131       if (result == NULL)
23132         result = write_constant_as_bytes (obstack, byte_order,
23133                                           type, value, len);
23134       break;
23135     case DW_FORM_data2:
23136       type = die_type (die, cu);
23137       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23138       if (result == NULL)
23139         result = write_constant_as_bytes (obstack, byte_order,
23140                                           type, value, len);
23141       break;
23142     case DW_FORM_data4:
23143       type = die_type (die, cu);
23144       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23145       if (result == NULL)
23146         result = write_constant_as_bytes (obstack, byte_order,
23147                                           type, value, len);
23148       break;
23149     case DW_FORM_data8:
23150       type = die_type (die, cu);
23151       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23152       if (result == NULL)
23153         result = write_constant_as_bytes (obstack, byte_order,
23154                                           type, value, len);
23155       break;
23156
23157     case DW_FORM_sdata:
23158     case DW_FORM_implicit_const:
23159       type = die_type (die, cu);
23160       result = write_constant_as_bytes (obstack, byte_order,
23161                                         type, DW_SND (attr), len);
23162       break;
23163
23164     case DW_FORM_udata:
23165       type = die_type (die, cu);
23166       result = write_constant_as_bytes (obstack, byte_order,
23167                                         type, DW_UNSND (attr), len);
23168       break;
23169
23170     default:
23171       complaint (_("unsupported const value attribute form: '%s'"),
23172                  dwarf_form_name (attr->form));
23173       break;
23174     }
23175
23176   return result;
23177 }
23178
23179 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23180    valid type for this die is found.  */
23181
23182 struct type *
23183 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23184                                 struct dwarf2_per_cu_data *per_cu)
23185 {
23186   struct dwarf2_cu *cu;
23187   struct die_info *die;
23188
23189   if (per_cu->cu == NULL)
23190     load_cu (per_cu, false);
23191   cu = per_cu->cu;
23192   if (!cu)
23193     return NULL;
23194
23195   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23196   if (!die)
23197     return NULL;
23198
23199   return die_type (die, cu);
23200 }
23201
23202 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23203    PER_CU.  */
23204
23205 struct type *
23206 dwarf2_get_die_type (cu_offset die_offset,
23207                      struct dwarf2_per_cu_data *per_cu)
23208 {
23209   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23210   return get_die_type_at_offset (die_offset_sect, per_cu);
23211 }
23212
23213 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23214    On entry *REF_CU is the CU of SRC_DIE.
23215    On exit *REF_CU is the CU of the result.
23216    Returns NULL if the referenced DIE isn't found.  */
23217
23218 static struct die_info *
23219 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23220                   struct dwarf2_cu **ref_cu)
23221 {
23222   struct die_info temp_die;
23223   struct dwarf2_cu *sig_cu;
23224   struct die_info *die;
23225
23226   /* While it might be nice to assert sig_type->type == NULL here,
23227      we can get here for DW_AT_imported_declaration where we need
23228      the DIE not the type.  */
23229
23230   /* If necessary, add it to the queue and load its DIEs.  */
23231
23232   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23233     read_signatured_type (sig_type);
23234
23235   sig_cu = sig_type->per_cu.cu;
23236   gdb_assert (sig_cu != NULL);
23237   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23238   temp_die.sect_off = sig_type->type_offset_in_section;
23239   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23240                                                  to_underlying (temp_die.sect_off));
23241   if (die)
23242     {
23243       struct dwarf2_per_objfile *dwarf2_per_objfile
23244         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23245
23246       /* For .gdb_index version 7 keep track of included TUs.
23247          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23248       if (dwarf2_per_objfile->index_table != NULL
23249           && dwarf2_per_objfile->index_table->version <= 7)
23250         {
23251           VEC_safe_push (dwarf2_per_cu_ptr,
23252                          (*ref_cu)->per_cu->imported_symtabs,
23253                          sig_cu->per_cu);
23254         }
23255
23256       *ref_cu = sig_cu;
23257       return die;
23258     }
23259
23260   return NULL;
23261 }
23262
23263 /* Follow signatured type referenced by ATTR in SRC_DIE.
23264    On entry *REF_CU is the CU of SRC_DIE.
23265    On exit *REF_CU is the CU of the result.
23266    The result is the DIE of the type.
23267    If the referenced type cannot be found an error is thrown.  */
23268
23269 static struct die_info *
23270 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23271                 struct dwarf2_cu **ref_cu)
23272 {
23273   ULONGEST signature = DW_SIGNATURE (attr);
23274   struct signatured_type *sig_type;
23275   struct die_info *die;
23276
23277   gdb_assert (attr->form == DW_FORM_ref_sig8);
23278
23279   sig_type = lookup_signatured_type (*ref_cu, signature);
23280   /* sig_type will be NULL if the signatured type is missing from
23281      the debug info.  */
23282   if (sig_type == NULL)
23283     {
23284       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23285                " from DIE at %s [in module %s]"),
23286              hex_string (signature), sect_offset_str (src_die->sect_off),
23287              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23288     }
23289
23290   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23291   if (die == NULL)
23292     {
23293       dump_die_for_error (src_die);
23294       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23295                " from DIE at %s [in module %s]"),
23296              hex_string (signature), sect_offset_str (src_die->sect_off),
23297              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23298     }
23299
23300   return die;
23301 }
23302
23303 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23304    reading in and processing the type unit if necessary.  */
23305
23306 static struct type *
23307 get_signatured_type (struct die_info *die, ULONGEST signature,
23308                      struct dwarf2_cu *cu)
23309 {
23310   struct dwarf2_per_objfile *dwarf2_per_objfile
23311     = cu->per_cu->dwarf2_per_objfile;
23312   struct signatured_type *sig_type;
23313   struct dwarf2_cu *type_cu;
23314   struct die_info *type_die;
23315   struct type *type;
23316
23317   sig_type = lookup_signatured_type (cu, signature);
23318   /* sig_type will be NULL if the signatured type is missing from
23319      the debug info.  */
23320   if (sig_type == NULL)
23321     {
23322       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23323                    " from DIE at %s [in module %s]"),
23324                  hex_string (signature), sect_offset_str (die->sect_off),
23325                  objfile_name (dwarf2_per_objfile->objfile));
23326       return build_error_marker_type (cu, die);
23327     }
23328
23329   /* If we already know the type we're done.  */
23330   if (sig_type->type != NULL)
23331     return sig_type->type;
23332
23333   type_cu = cu;
23334   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23335   if (type_die != NULL)
23336     {
23337       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23338          is created.  This is important, for example, because for c++ classes
23339          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23340       type = read_type_die (type_die, type_cu);
23341       if (type == NULL)
23342         {
23343           complaint (_("Dwarf Error: Cannot build signatured type %s"
23344                        " referenced from DIE at %s [in module %s]"),
23345                      hex_string (signature), sect_offset_str (die->sect_off),
23346                      objfile_name (dwarf2_per_objfile->objfile));
23347           type = build_error_marker_type (cu, die);
23348         }
23349     }
23350   else
23351     {
23352       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23353                    " from DIE at %s [in module %s]"),
23354                  hex_string (signature), sect_offset_str (die->sect_off),
23355                  objfile_name (dwarf2_per_objfile->objfile));
23356       type = build_error_marker_type (cu, die);
23357     }
23358   sig_type->type = type;
23359
23360   return type;
23361 }
23362
23363 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23364    reading in and processing the type unit if necessary.  */
23365
23366 static struct type *
23367 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23368                           struct dwarf2_cu *cu) /* ARI: editCase function */
23369 {
23370   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23371   if (attr_form_is_ref (attr))
23372     {
23373       struct dwarf2_cu *type_cu = cu;
23374       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23375
23376       return read_type_die (type_die, type_cu);
23377     }
23378   else if (attr->form == DW_FORM_ref_sig8)
23379     {
23380       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23381     }
23382   else
23383     {
23384       struct dwarf2_per_objfile *dwarf2_per_objfile
23385         = cu->per_cu->dwarf2_per_objfile;
23386
23387       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23388                    " at %s [in module %s]"),
23389                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23390                  objfile_name (dwarf2_per_objfile->objfile));
23391       return build_error_marker_type (cu, die);
23392     }
23393 }
23394
23395 /* Load the DIEs associated with type unit PER_CU into memory.  */
23396
23397 static void
23398 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23399 {
23400   struct signatured_type *sig_type;
23401
23402   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23403   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23404
23405   /* We have the per_cu, but we need the signatured_type.
23406      Fortunately this is an easy translation.  */
23407   gdb_assert (per_cu->is_debug_types);
23408   sig_type = (struct signatured_type *) per_cu;
23409
23410   gdb_assert (per_cu->cu == NULL);
23411
23412   read_signatured_type (sig_type);
23413
23414   gdb_assert (per_cu->cu != NULL);
23415 }
23416
23417 /* die_reader_func for read_signatured_type.
23418    This is identical to load_full_comp_unit_reader,
23419    but is kept separate for now.  */
23420
23421 static void
23422 read_signatured_type_reader (const struct die_reader_specs *reader,
23423                              const gdb_byte *info_ptr,
23424                              struct die_info *comp_unit_die,
23425                              int has_children,
23426                              void *data)
23427 {
23428   struct dwarf2_cu *cu = reader->cu;
23429
23430   gdb_assert (cu->die_hash == NULL);
23431   cu->die_hash =
23432     htab_create_alloc_ex (cu->header.length / 12,
23433                           die_hash,
23434                           die_eq,
23435                           NULL,
23436                           &cu->comp_unit_obstack,
23437                           hashtab_obstack_allocate,
23438                           dummy_obstack_deallocate);
23439
23440   if (has_children)
23441     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23442                                                   &info_ptr, comp_unit_die);
23443   cu->dies = comp_unit_die;
23444   /* comp_unit_die is not stored in die_hash, no need.  */
23445
23446   /* We try not to read any attributes in this function, because not
23447      all CUs needed for references have been loaded yet, and symbol
23448      table processing isn't initialized.  But we have to set the CU language,
23449      or we won't be able to build types correctly.
23450      Similarly, if we do not read the producer, we can not apply
23451      producer-specific interpretation.  */
23452   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23453 }
23454
23455 /* Read in a signatured type and build its CU and DIEs.
23456    If the type is a stub for the real type in a DWO file,
23457    read in the real type from the DWO file as well.  */
23458
23459 static void
23460 read_signatured_type (struct signatured_type *sig_type)
23461 {
23462   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23463
23464   gdb_assert (per_cu->is_debug_types);
23465   gdb_assert (per_cu->cu == NULL);
23466
23467   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23468                            read_signatured_type_reader, NULL);
23469   sig_type->per_cu.tu_read = 1;
23470 }
23471
23472 /* Decode simple location descriptions.
23473    Given a pointer to a dwarf block that defines a location, compute
23474    the location and return the value.
23475
23476    NOTE drow/2003-11-18: This function is called in two situations
23477    now: for the address of static or global variables (partial symbols
23478    only) and for offsets into structures which are expected to be
23479    (more or less) constant.  The partial symbol case should go away,
23480    and only the constant case should remain.  That will let this
23481    function complain more accurately.  A few special modes are allowed
23482    without complaint for global variables (for instance, global
23483    register values and thread-local values).
23484
23485    A location description containing no operations indicates that the
23486    object is optimized out.  The return value is 0 for that case.
23487    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23488    callers will only want a very basic result and this can become a
23489    complaint.
23490
23491    Note that stack[0] is unused except as a default error return.  */
23492
23493 static CORE_ADDR
23494 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23495 {
23496   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23497   size_t i;
23498   size_t size = blk->size;
23499   const gdb_byte *data = blk->data;
23500   CORE_ADDR stack[64];
23501   int stacki;
23502   unsigned int bytes_read, unsnd;
23503   gdb_byte op;
23504
23505   i = 0;
23506   stacki = 0;
23507   stack[stacki] = 0;
23508   stack[++stacki] = 0;
23509
23510   while (i < size)
23511     {
23512       op = data[i++];
23513       switch (op)
23514         {
23515         case DW_OP_lit0:
23516         case DW_OP_lit1:
23517         case DW_OP_lit2:
23518         case DW_OP_lit3:
23519         case DW_OP_lit4:
23520         case DW_OP_lit5:
23521         case DW_OP_lit6:
23522         case DW_OP_lit7:
23523         case DW_OP_lit8:
23524         case DW_OP_lit9:
23525         case DW_OP_lit10:
23526         case DW_OP_lit11:
23527         case DW_OP_lit12:
23528         case DW_OP_lit13:
23529         case DW_OP_lit14:
23530         case DW_OP_lit15:
23531         case DW_OP_lit16:
23532         case DW_OP_lit17:
23533         case DW_OP_lit18:
23534         case DW_OP_lit19:
23535         case DW_OP_lit20:
23536         case DW_OP_lit21:
23537         case DW_OP_lit22:
23538         case DW_OP_lit23:
23539         case DW_OP_lit24:
23540         case DW_OP_lit25:
23541         case DW_OP_lit26:
23542         case DW_OP_lit27:
23543         case DW_OP_lit28:
23544         case DW_OP_lit29:
23545         case DW_OP_lit30:
23546         case DW_OP_lit31:
23547           stack[++stacki] = op - DW_OP_lit0;
23548           break;
23549
23550         case DW_OP_reg0:
23551         case DW_OP_reg1:
23552         case DW_OP_reg2:
23553         case DW_OP_reg3:
23554         case DW_OP_reg4:
23555         case DW_OP_reg5:
23556         case DW_OP_reg6:
23557         case DW_OP_reg7:
23558         case DW_OP_reg8:
23559         case DW_OP_reg9:
23560         case DW_OP_reg10:
23561         case DW_OP_reg11:
23562         case DW_OP_reg12:
23563         case DW_OP_reg13:
23564         case DW_OP_reg14:
23565         case DW_OP_reg15:
23566         case DW_OP_reg16:
23567         case DW_OP_reg17:
23568         case DW_OP_reg18:
23569         case DW_OP_reg19:
23570         case DW_OP_reg20:
23571         case DW_OP_reg21:
23572         case DW_OP_reg22:
23573         case DW_OP_reg23:
23574         case DW_OP_reg24:
23575         case DW_OP_reg25:
23576         case DW_OP_reg26:
23577         case DW_OP_reg27:
23578         case DW_OP_reg28:
23579         case DW_OP_reg29:
23580         case DW_OP_reg30:
23581         case DW_OP_reg31:
23582           stack[++stacki] = op - DW_OP_reg0;
23583           if (i < size)
23584             dwarf2_complex_location_expr_complaint ();
23585           break;
23586
23587         case DW_OP_regx:
23588           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23589           i += bytes_read;
23590           stack[++stacki] = unsnd;
23591           if (i < size)
23592             dwarf2_complex_location_expr_complaint ();
23593           break;
23594
23595         case DW_OP_addr:
23596           stack[++stacki] = read_address (objfile->obfd, &data[i],
23597                                           cu, &bytes_read);
23598           i += bytes_read;
23599           break;
23600
23601         case DW_OP_const1u:
23602           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23603           i += 1;
23604           break;
23605
23606         case DW_OP_const1s:
23607           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23608           i += 1;
23609           break;
23610
23611         case DW_OP_const2u:
23612           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23613           i += 2;
23614           break;
23615
23616         case DW_OP_const2s:
23617           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23618           i += 2;
23619           break;
23620
23621         case DW_OP_const4u:
23622           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23623           i += 4;
23624           break;
23625
23626         case DW_OP_const4s:
23627           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23628           i += 4;
23629           break;
23630
23631         case DW_OP_const8u:
23632           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23633           i += 8;
23634           break;
23635
23636         case DW_OP_constu:
23637           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23638                                                   &bytes_read);
23639           i += bytes_read;
23640           break;
23641
23642         case DW_OP_consts:
23643           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23644           i += bytes_read;
23645           break;
23646
23647         case DW_OP_dup:
23648           stack[stacki + 1] = stack[stacki];
23649           stacki++;
23650           break;
23651
23652         case DW_OP_plus:
23653           stack[stacki - 1] += stack[stacki];
23654           stacki--;
23655           break;
23656
23657         case DW_OP_plus_uconst:
23658           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23659                                                  &bytes_read);
23660           i += bytes_read;
23661           break;
23662
23663         case DW_OP_minus:
23664           stack[stacki - 1] -= stack[stacki];
23665           stacki--;
23666           break;
23667
23668         case DW_OP_deref:
23669           /* If we're not the last op, then we definitely can't encode
23670              this using GDB's address_class enum.  This is valid for partial
23671              global symbols, although the variable's address will be bogus
23672              in the psymtab.  */
23673           if (i < size)
23674             dwarf2_complex_location_expr_complaint ();
23675           break;
23676
23677         case DW_OP_GNU_push_tls_address:
23678         case DW_OP_form_tls_address:
23679           /* The top of the stack has the offset from the beginning
23680              of the thread control block at which the variable is located.  */
23681           /* Nothing should follow this operator, so the top of stack would
23682              be returned.  */
23683           /* This is valid for partial global symbols, but the variable's
23684              address will be bogus in the psymtab.  Make it always at least
23685              non-zero to not look as a variable garbage collected by linker
23686              which have DW_OP_addr 0.  */
23687           if (i < size)
23688             dwarf2_complex_location_expr_complaint ();
23689           stack[stacki]++;
23690           break;
23691
23692         case DW_OP_GNU_uninit:
23693           break;
23694
23695         case DW_OP_GNU_addr_index:
23696         case DW_OP_GNU_const_index:
23697           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23698                                                          &bytes_read);
23699           i += bytes_read;
23700           break;
23701
23702         default:
23703           {
23704             const char *name = get_DW_OP_name (op);
23705
23706             if (name)
23707               complaint (_("unsupported stack op: '%s'"),
23708                          name);
23709             else
23710               complaint (_("unsupported stack op: '%02x'"),
23711                          op);
23712           }
23713
23714           return (stack[stacki]);
23715         }
23716
23717       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23718          outside of the allocated space.  Also enforce minimum>0.  */
23719       if (stacki >= ARRAY_SIZE (stack) - 1)
23720         {
23721           complaint (_("location description stack overflow"));
23722           return 0;
23723         }
23724
23725       if (stacki <= 0)
23726         {
23727           complaint (_("location description stack underflow"));
23728           return 0;
23729         }
23730     }
23731   return (stack[stacki]);
23732 }
23733
23734 /* memory allocation interface */
23735
23736 static struct dwarf_block *
23737 dwarf_alloc_block (struct dwarf2_cu *cu)
23738 {
23739   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23740 }
23741
23742 static struct die_info *
23743 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23744 {
23745   struct die_info *die;
23746   size_t size = sizeof (struct die_info);
23747
23748   if (num_attrs > 1)
23749     size += (num_attrs - 1) * sizeof (struct attribute);
23750
23751   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23752   memset (die, 0, sizeof (struct die_info));
23753   return (die);
23754 }
23755
23756 \f
23757 /* Macro support.  */
23758
23759 /* Return file name relative to the compilation directory of file number I in
23760    *LH's file name table.  The result is allocated using xmalloc; the caller is
23761    responsible for freeing it.  */
23762
23763 static char *
23764 file_file_name (int file, struct line_header *lh)
23765 {
23766   /* Is the file number a valid index into the line header's file name
23767      table?  Remember that file numbers start with one, not zero.  */
23768   if (1 <= file && file <= lh->file_names.size ())
23769     {
23770       const file_entry &fe = lh->file_names[file - 1];
23771
23772       if (!IS_ABSOLUTE_PATH (fe.name))
23773         {
23774           const char *dir = fe.include_dir (lh);
23775           if (dir != NULL)
23776             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23777         }
23778       return xstrdup (fe.name);
23779     }
23780   else
23781     {
23782       /* The compiler produced a bogus file number.  We can at least
23783          record the macro definitions made in the file, even if we
23784          won't be able to find the file by name.  */
23785       char fake_name[80];
23786
23787       xsnprintf (fake_name, sizeof (fake_name),
23788                  "<bad macro file number %d>", file);
23789
23790       complaint (_("bad file number in macro information (%d)"),
23791                  file);
23792
23793       return xstrdup (fake_name);
23794     }
23795 }
23796
23797 /* Return the full name of file number I in *LH's file name table.
23798    Use COMP_DIR as the name of the current directory of the
23799    compilation.  The result is allocated using xmalloc; the caller is
23800    responsible for freeing it.  */
23801 static char *
23802 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23803 {
23804   /* Is the file number a valid index into the line header's file name
23805      table?  Remember that file numbers start with one, not zero.  */
23806   if (1 <= file && file <= lh->file_names.size ())
23807     {
23808       char *relative = file_file_name (file, lh);
23809
23810       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23811         return relative;
23812       return reconcat (relative, comp_dir, SLASH_STRING,
23813                        relative, (char *) NULL);
23814     }
23815   else
23816     return file_file_name (file, lh);
23817 }
23818
23819
23820 static struct macro_source_file *
23821 macro_start_file (struct dwarf2_cu *cu,
23822                   int file, int line,
23823                   struct macro_source_file *current_file,
23824                   struct line_header *lh)
23825 {
23826   /* File name relative to the compilation directory of this source file.  */
23827   char *file_name = file_file_name (file, lh);
23828
23829   if (! current_file)
23830     {
23831       /* Note: We don't create a macro table for this compilation unit
23832          at all until we actually get a filename.  */
23833       struct macro_table *macro_table = cu->builder->get_macro_table ();
23834
23835       /* If we have no current file, then this must be the start_file
23836          directive for the compilation unit's main source file.  */
23837       current_file = macro_set_main (macro_table, file_name);
23838       macro_define_special (macro_table);
23839     }
23840   else
23841     current_file = macro_include (current_file, line, file_name);
23842
23843   xfree (file_name);
23844
23845   return current_file;
23846 }
23847
23848 static const char *
23849 consume_improper_spaces (const char *p, const char *body)
23850 {
23851   if (*p == ' ')
23852     {
23853       complaint (_("macro definition contains spaces "
23854                    "in formal argument list:\n`%s'"),
23855                  body);
23856
23857       while (*p == ' ')
23858         p++;
23859     }
23860
23861   return p;
23862 }
23863
23864
23865 static void
23866 parse_macro_definition (struct macro_source_file *file, int line,
23867                         const char *body)
23868 {
23869   const char *p;
23870
23871   /* The body string takes one of two forms.  For object-like macro
23872      definitions, it should be:
23873
23874         <macro name> " " <definition>
23875
23876      For function-like macro definitions, it should be:
23877
23878         <macro name> "() " <definition>
23879      or
23880         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23881
23882      Spaces may appear only where explicitly indicated, and in the
23883      <definition>.
23884
23885      The Dwarf 2 spec says that an object-like macro's name is always
23886      followed by a space, but versions of GCC around March 2002 omit
23887      the space when the macro's definition is the empty string.
23888
23889      The Dwarf 2 spec says that there should be no spaces between the
23890      formal arguments in a function-like macro's formal argument list,
23891      but versions of GCC around March 2002 include spaces after the
23892      commas.  */
23893
23894
23895   /* Find the extent of the macro name.  The macro name is terminated
23896      by either a space or null character (for an object-like macro) or
23897      an opening paren (for a function-like macro).  */
23898   for (p = body; *p; p++)
23899     if (*p == ' ' || *p == '(')
23900       break;
23901
23902   if (*p == ' ' || *p == '\0')
23903     {
23904       /* It's an object-like macro.  */
23905       int name_len = p - body;
23906       char *name = savestring (body, name_len);
23907       const char *replacement;
23908
23909       if (*p == ' ')
23910         replacement = body + name_len + 1;
23911       else
23912         {
23913           dwarf2_macro_malformed_definition_complaint (body);
23914           replacement = body + name_len;
23915         }
23916
23917       macro_define_object (file, line, name, replacement);
23918
23919       xfree (name);
23920     }
23921   else if (*p == '(')
23922     {
23923       /* It's a function-like macro.  */
23924       char *name = savestring (body, p - body);
23925       int argc = 0;
23926       int argv_size = 1;
23927       char **argv = XNEWVEC (char *, argv_size);
23928
23929       p++;
23930
23931       p = consume_improper_spaces (p, body);
23932
23933       /* Parse the formal argument list.  */
23934       while (*p && *p != ')')
23935         {
23936           /* Find the extent of the current argument name.  */
23937           const char *arg_start = p;
23938
23939           while (*p && *p != ',' && *p != ')' && *p != ' ')
23940             p++;
23941
23942           if (! *p || p == arg_start)
23943             dwarf2_macro_malformed_definition_complaint (body);
23944           else
23945             {
23946               /* Make sure argv has room for the new argument.  */
23947               if (argc >= argv_size)
23948                 {
23949                   argv_size *= 2;
23950                   argv = XRESIZEVEC (char *, argv, argv_size);
23951                 }
23952
23953               argv[argc++] = savestring (arg_start, p - arg_start);
23954             }
23955
23956           p = consume_improper_spaces (p, body);
23957
23958           /* Consume the comma, if present.  */
23959           if (*p == ',')
23960             {
23961               p++;
23962
23963               p = consume_improper_spaces (p, body);
23964             }
23965         }
23966
23967       if (*p == ')')
23968         {
23969           p++;
23970
23971           if (*p == ' ')
23972             /* Perfectly formed definition, no complaints.  */
23973             macro_define_function (file, line, name,
23974                                    argc, (const char **) argv,
23975                                    p + 1);
23976           else if (*p == '\0')
23977             {
23978               /* Complain, but do define it.  */
23979               dwarf2_macro_malformed_definition_complaint (body);
23980               macro_define_function (file, line, name,
23981                                      argc, (const char **) argv,
23982                                      p);
23983             }
23984           else
23985             /* Just complain.  */
23986             dwarf2_macro_malformed_definition_complaint (body);
23987         }
23988       else
23989         /* Just complain.  */
23990         dwarf2_macro_malformed_definition_complaint (body);
23991
23992       xfree (name);
23993       {
23994         int i;
23995
23996         for (i = 0; i < argc; i++)
23997           xfree (argv[i]);
23998       }
23999       xfree (argv);
24000     }
24001   else
24002     dwarf2_macro_malformed_definition_complaint (body);
24003 }
24004
24005 /* Skip some bytes from BYTES according to the form given in FORM.
24006    Returns the new pointer.  */
24007
24008 static const gdb_byte *
24009 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
24010                  enum dwarf_form form,
24011                  unsigned int offset_size,
24012                  struct dwarf2_section_info *section)
24013 {
24014   unsigned int bytes_read;
24015
24016   switch (form)
24017     {
24018     case DW_FORM_data1:
24019     case DW_FORM_flag:
24020       ++bytes;
24021       break;
24022
24023     case DW_FORM_data2:
24024       bytes += 2;
24025       break;
24026
24027     case DW_FORM_data4:
24028       bytes += 4;
24029       break;
24030
24031     case DW_FORM_data8:
24032       bytes += 8;
24033       break;
24034
24035     case DW_FORM_data16:
24036       bytes += 16;
24037       break;
24038
24039     case DW_FORM_string:
24040       read_direct_string (abfd, bytes, &bytes_read);
24041       bytes += bytes_read;
24042       break;
24043
24044     case DW_FORM_sec_offset:
24045     case DW_FORM_strp:
24046     case DW_FORM_GNU_strp_alt:
24047       bytes += offset_size;
24048       break;
24049
24050     case DW_FORM_block:
24051       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
24052       bytes += bytes_read;
24053       break;
24054
24055     case DW_FORM_block1:
24056       bytes += 1 + read_1_byte (abfd, bytes);
24057       break;
24058     case DW_FORM_block2:
24059       bytes += 2 + read_2_bytes (abfd, bytes);
24060       break;
24061     case DW_FORM_block4:
24062       bytes += 4 + read_4_bytes (abfd, bytes);
24063       break;
24064
24065     case DW_FORM_sdata:
24066     case DW_FORM_udata:
24067     case DW_FORM_GNU_addr_index:
24068     case DW_FORM_GNU_str_index:
24069       bytes = gdb_skip_leb128 (bytes, buffer_end);
24070       if (bytes == NULL)
24071         {
24072           dwarf2_section_buffer_overflow_complaint (section);
24073           return NULL;
24074         }
24075       break;
24076
24077     case DW_FORM_implicit_const:
24078       break;
24079
24080     default:
24081       {
24082         complaint (_("invalid form 0x%x in `%s'"),
24083                    form, get_section_name (section));
24084         return NULL;
24085       }
24086     }
24087
24088   return bytes;
24089 }
24090
24091 /* A helper for dwarf_decode_macros that handles skipping an unknown
24092    opcode.  Returns an updated pointer to the macro data buffer; or,
24093    on error, issues a complaint and returns NULL.  */
24094
24095 static const gdb_byte *
24096 skip_unknown_opcode (unsigned int opcode,
24097                      const gdb_byte **opcode_definitions,
24098                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24099                      bfd *abfd,
24100                      unsigned int offset_size,
24101                      struct dwarf2_section_info *section)
24102 {
24103   unsigned int bytes_read, i;
24104   unsigned long arg;
24105   const gdb_byte *defn;
24106
24107   if (opcode_definitions[opcode] == NULL)
24108     {
24109       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
24110                  opcode);
24111       return NULL;
24112     }
24113
24114   defn = opcode_definitions[opcode];
24115   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
24116   defn += bytes_read;
24117
24118   for (i = 0; i < arg; ++i)
24119     {
24120       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
24121                                  (enum dwarf_form) defn[i], offset_size,
24122                                  section);
24123       if (mac_ptr == NULL)
24124         {
24125           /* skip_form_bytes already issued the complaint.  */
24126           return NULL;
24127         }
24128     }
24129
24130   return mac_ptr;
24131 }
24132
24133 /* A helper function which parses the header of a macro section.
24134    If the macro section is the extended (for now called "GNU") type,
24135    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24136    the header, or issues a complaint and returns NULL on error.  */
24137
24138 static const gdb_byte *
24139 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24140                           bfd *abfd,
24141                           const gdb_byte *mac_ptr,
24142                           unsigned int *offset_size,
24143                           int section_is_gnu)
24144 {
24145   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24146
24147   if (section_is_gnu)
24148     {
24149       unsigned int version, flags;
24150
24151       version = read_2_bytes (abfd, mac_ptr);
24152       if (version != 4 && version != 5)
24153         {
24154           complaint (_("unrecognized version `%d' in .debug_macro section"),
24155                      version);
24156           return NULL;
24157         }
24158       mac_ptr += 2;
24159
24160       flags = read_1_byte (abfd, mac_ptr);
24161       ++mac_ptr;
24162       *offset_size = (flags & 1) ? 8 : 4;
24163
24164       if ((flags & 2) != 0)
24165         /* We don't need the line table offset.  */
24166         mac_ptr += *offset_size;
24167
24168       /* Vendor opcode descriptions.  */
24169       if ((flags & 4) != 0)
24170         {
24171           unsigned int i, count;
24172
24173           count = read_1_byte (abfd, mac_ptr);
24174           ++mac_ptr;
24175           for (i = 0; i < count; ++i)
24176             {
24177               unsigned int opcode, bytes_read;
24178               unsigned long arg;
24179
24180               opcode = read_1_byte (abfd, mac_ptr);
24181               ++mac_ptr;
24182               opcode_definitions[opcode] = mac_ptr;
24183               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24184               mac_ptr += bytes_read;
24185               mac_ptr += arg;
24186             }
24187         }
24188     }
24189
24190   return mac_ptr;
24191 }
24192
24193 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24194    including DW_MACRO_import.  */
24195
24196 static void
24197 dwarf_decode_macro_bytes (struct dwarf2_cu *cu,
24198                           bfd *abfd,
24199                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24200                           struct macro_source_file *current_file,
24201                           struct line_header *lh,
24202                           struct dwarf2_section_info *section,
24203                           int section_is_gnu, int section_is_dwz,
24204                           unsigned int offset_size,
24205                           htab_t include_hash)
24206 {
24207   struct dwarf2_per_objfile *dwarf2_per_objfile
24208     = cu->per_cu->dwarf2_per_objfile;
24209   struct objfile *objfile = dwarf2_per_objfile->objfile;
24210   enum dwarf_macro_record_type macinfo_type;
24211   int at_commandline;
24212   const gdb_byte *opcode_definitions[256];
24213
24214   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24215                                       &offset_size, section_is_gnu);
24216   if (mac_ptr == NULL)
24217     {
24218       /* We already issued a complaint.  */
24219       return;
24220     }
24221
24222   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24223      GDB is still reading the definitions from command line.  First
24224      DW_MACINFO_start_file will need to be ignored as it was already executed
24225      to create CURRENT_FILE for the main source holding also the command line
24226      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24227      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24228
24229   at_commandline = 1;
24230
24231   do
24232     {
24233       /* Do we at least have room for a macinfo type byte?  */
24234       if (mac_ptr >= mac_end)
24235         {
24236           dwarf2_section_buffer_overflow_complaint (section);
24237           break;
24238         }
24239
24240       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24241       mac_ptr++;
24242
24243       /* Note that we rely on the fact that the corresponding GNU and
24244          DWARF constants are the same.  */
24245       DIAGNOSTIC_PUSH
24246       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24247       switch (macinfo_type)
24248         {
24249           /* A zero macinfo type indicates the end of the macro
24250              information.  */
24251         case 0:
24252           break;
24253
24254         case DW_MACRO_define:
24255         case DW_MACRO_undef:
24256         case DW_MACRO_define_strp:
24257         case DW_MACRO_undef_strp:
24258         case DW_MACRO_define_sup:
24259         case DW_MACRO_undef_sup:
24260           {
24261             unsigned int bytes_read;
24262             int line;
24263             const char *body;
24264             int is_define;
24265
24266             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24267             mac_ptr += bytes_read;
24268
24269             if (macinfo_type == DW_MACRO_define
24270                 || macinfo_type == DW_MACRO_undef)
24271               {
24272                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24273                 mac_ptr += bytes_read;
24274               }
24275             else
24276               {
24277                 LONGEST str_offset;
24278
24279                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24280                 mac_ptr += offset_size;
24281
24282                 if (macinfo_type == DW_MACRO_define_sup
24283                     || macinfo_type == DW_MACRO_undef_sup
24284                     || section_is_dwz)
24285                   {
24286                     struct dwz_file *dwz
24287                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24288
24289                     body = read_indirect_string_from_dwz (objfile,
24290                                                           dwz, str_offset);
24291                   }
24292                 else
24293                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24294                                                          abfd, str_offset);
24295               }
24296
24297             is_define = (macinfo_type == DW_MACRO_define
24298                          || macinfo_type == DW_MACRO_define_strp
24299                          || macinfo_type == DW_MACRO_define_sup);
24300             if (! current_file)
24301               {
24302                 /* DWARF violation as no main source is present.  */
24303                 complaint (_("debug info with no main source gives macro %s "
24304                              "on line %d: %s"),
24305                            is_define ? _("definition") : _("undefinition"),
24306                            line, body);
24307                 break;
24308               }
24309             if ((line == 0 && !at_commandline)
24310                 || (line != 0 && at_commandline))
24311               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24312                          at_commandline ? _("command-line") : _("in-file"),
24313                          is_define ? _("definition") : _("undefinition"),
24314                          line == 0 ? _("zero") : _("non-zero"), line, body);
24315
24316             if (is_define)
24317               parse_macro_definition (current_file, line, body);
24318             else
24319               {
24320                 gdb_assert (macinfo_type == DW_MACRO_undef
24321                             || macinfo_type == DW_MACRO_undef_strp
24322                             || macinfo_type == DW_MACRO_undef_sup);
24323                 macro_undef (current_file, line, body);
24324               }
24325           }
24326           break;
24327
24328         case DW_MACRO_start_file:
24329           {
24330             unsigned int bytes_read;
24331             int line, file;
24332
24333             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24334             mac_ptr += bytes_read;
24335             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24336             mac_ptr += bytes_read;
24337
24338             if ((line == 0 && !at_commandline)
24339                 || (line != 0 && at_commandline))
24340               complaint (_("debug info gives source %d included "
24341                            "from %s at %s line %d"),
24342                          file, at_commandline ? _("command-line") : _("file"),
24343                          line == 0 ? _("zero") : _("non-zero"), line);
24344
24345             if (at_commandline)
24346               {
24347                 /* This DW_MACRO_start_file was executed in the
24348                    pass one.  */
24349                 at_commandline = 0;
24350               }
24351             else
24352               current_file = macro_start_file (cu, file, line, current_file,
24353                                                lh);
24354           }
24355           break;
24356
24357         case DW_MACRO_end_file:
24358           if (! current_file)
24359             complaint (_("macro debug info has an unmatched "
24360                          "`close_file' directive"));
24361           else
24362             {
24363               current_file = current_file->included_by;
24364               if (! current_file)
24365                 {
24366                   enum dwarf_macro_record_type next_type;
24367
24368                   /* GCC circa March 2002 doesn't produce the zero
24369                      type byte marking the end of the compilation
24370                      unit.  Complain if it's not there, but exit no
24371                      matter what.  */
24372
24373                   /* Do we at least have room for a macinfo type byte?  */
24374                   if (mac_ptr >= mac_end)
24375                     {
24376                       dwarf2_section_buffer_overflow_complaint (section);
24377                       return;
24378                     }
24379
24380                   /* We don't increment mac_ptr here, so this is just
24381                      a look-ahead.  */
24382                   next_type
24383                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24384                                                                   mac_ptr);
24385                   if (next_type != 0)
24386                     complaint (_("no terminating 0-type entry for "
24387                                  "macros in `.debug_macinfo' section"));
24388
24389                   return;
24390                 }
24391             }
24392           break;
24393
24394         case DW_MACRO_import:
24395         case DW_MACRO_import_sup:
24396           {
24397             LONGEST offset;
24398             void **slot;
24399             bfd *include_bfd = abfd;
24400             struct dwarf2_section_info *include_section = section;
24401             const gdb_byte *include_mac_end = mac_end;
24402             int is_dwz = section_is_dwz;
24403             const gdb_byte *new_mac_ptr;
24404
24405             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24406             mac_ptr += offset_size;
24407
24408             if (macinfo_type == DW_MACRO_import_sup)
24409               {
24410                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24411
24412                 dwarf2_read_section (objfile, &dwz->macro);
24413
24414                 include_section = &dwz->macro;
24415                 include_bfd = get_section_bfd_owner (include_section);
24416                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24417                 is_dwz = 1;
24418               }
24419
24420             new_mac_ptr = include_section->buffer + offset;
24421             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24422
24423             if (*slot != NULL)
24424               {
24425                 /* This has actually happened; see
24426                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24427                 complaint (_("recursive DW_MACRO_import in "
24428                              ".debug_macro section"));
24429               }
24430             else
24431               {
24432                 *slot = (void *) new_mac_ptr;
24433
24434                 dwarf_decode_macro_bytes (cu, include_bfd, new_mac_ptr,
24435                                           include_mac_end, current_file, lh,
24436                                           section, section_is_gnu, is_dwz,
24437                                           offset_size, include_hash);
24438
24439                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24440               }
24441           }
24442           break;
24443
24444         case DW_MACINFO_vendor_ext:
24445           if (!section_is_gnu)
24446             {
24447               unsigned int bytes_read;
24448
24449               /* This reads the constant, but since we don't recognize
24450                  any vendor extensions, we ignore it.  */
24451               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24452               mac_ptr += bytes_read;
24453               read_direct_string (abfd, mac_ptr, &bytes_read);
24454               mac_ptr += bytes_read;
24455
24456               /* We don't recognize any vendor extensions.  */
24457               break;
24458             }
24459           /* FALLTHROUGH */
24460
24461         default:
24462           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24463                                          mac_ptr, mac_end, abfd, offset_size,
24464                                          section);
24465           if (mac_ptr == NULL)
24466             return;
24467           break;
24468         }
24469       DIAGNOSTIC_POP
24470     } while (macinfo_type != 0);
24471 }
24472
24473 static void
24474 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24475                      int section_is_gnu)
24476 {
24477   struct dwarf2_per_objfile *dwarf2_per_objfile
24478     = cu->per_cu->dwarf2_per_objfile;
24479   struct objfile *objfile = dwarf2_per_objfile->objfile;
24480   struct line_header *lh = cu->line_header;
24481   bfd *abfd;
24482   const gdb_byte *mac_ptr, *mac_end;
24483   struct macro_source_file *current_file = 0;
24484   enum dwarf_macro_record_type macinfo_type;
24485   unsigned int offset_size = cu->header.offset_size;
24486   const gdb_byte *opcode_definitions[256];
24487   void **slot;
24488   struct dwarf2_section_info *section;
24489   const char *section_name;
24490
24491   if (cu->dwo_unit != NULL)
24492     {
24493       if (section_is_gnu)
24494         {
24495           section = &cu->dwo_unit->dwo_file->sections.macro;
24496           section_name = ".debug_macro.dwo";
24497         }
24498       else
24499         {
24500           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24501           section_name = ".debug_macinfo.dwo";
24502         }
24503     }
24504   else
24505     {
24506       if (section_is_gnu)
24507         {
24508           section = &dwarf2_per_objfile->macro;
24509           section_name = ".debug_macro";
24510         }
24511       else
24512         {
24513           section = &dwarf2_per_objfile->macinfo;
24514           section_name = ".debug_macinfo";
24515         }
24516     }
24517
24518   dwarf2_read_section (objfile, section);
24519   if (section->buffer == NULL)
24520     {
24521       complaint (_("missing %s section"), section_name);
24522       return;
24523     }
24524   abfd = get_section_bfd_owner (section);
24525
24526   /* First pass: Find the name of the base filename.
24527      This filename is needed in order to process all macros whose definition
24528      (or undefinition) comes from the command line.  These macros are defined
24529      before the first DW_MACINFO_start_file entry, and yet still need to be
24530      associated to the base file.
24531
24532      To determine the base file name, we scan the macro definitions until we
24533      reach the first DW_MACINFO_start_file entry.  We then initialize
24534      CURRENT_FILE accordingly so that any macro definition found before the
24535      first DW_MACINFO_start_file can still be associated to the base file.  */
24536
24537   mac_ptr = section->buffer + offset;
24538   mac_end = section->buffer + section->size;
24539
24540   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24541                                       &offset_size, section_is_gnu);
24542   if (mac_ptr == NULL)
24543     {
24544       /* We already issued a complaint.  */
24545       return;
24546     }
24547
24548   do
24549     {
24550       /* Do we at least have room for a macinfo type byte?  */
24551       if (mac_ptr >= mac_end)
24552         {
24553           /* Complaint is printed during the second pass as GDB will probably
24554              stop the first pass earlier upon finding
24555              DW_MACINFO_start_file.  */
24556           break;
24557         }
24558
24559       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24560       mac_ptr++;
24561
24562       /* Note that we rely on the fact that the corresponding GNU and
24563          DWARF constants are the same.  */
24564       DIAGNOSTIC_PUSH
24565       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24566       switch (macinfo_type)
24567         {
24568           /* A zero macinfo type indicates the end of the macro
24569              information.  */
24570         case 0:
24571           break;
24572
24573         case DW_MACRO_define:
24574         case DW_MACRO_undef:
24575           /* Only skip the data by MAC_PTR.  */
24576           {
24577             unsigned int bytes_read;
24578
24579             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24580             mac_ptr += bytes_read;
24581             read_direct_string (abfd, mac_ptr, &bytes_read);
24582             mac_ptr += bytes_read;
24583           }
24584           break;
24585
24586         case DW_MACRO_start_file:
24587           {
24588             unsigned int bytes_read;
24589             int line, file;
24590
24591             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24592             mac_ptr += bytes_read;
24593             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24594             mac_ptr += bytes_read;
24595
24596             current_file = macro_start_file (cu, file, line, current_file, lh);
24597           }
24598           break;
24599
24600         case DW_MACRO_end_file:
24601           /* No data to skip by MAC_PTR.  */
24602           break;
24603
24604         case DW_MACRO_define_strp:
24605         case DW_MACRO_undef_strp:
24606         case DW_MACRO_define_sup:
24607         case DW_MACRO_undef_sup:
24608           {
24609             unsigned int bytes_read;
24610
24611             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24612             mac_ptr += bytes_read;
24613             mac_ptr += offset_size;
24614           }
24615           break;
24616
24617         case DW_MACRO_import:
24618         case DW_MACRO_import_sup:
24619           /* Note that, according to the spec, a transparent include
24620              chain cannot call DW_MACRO_start_file.  So, we can just
24621              skip this opcode.  */
24622           mac_ptr += offset_size;
24623           break;
24624
24625         case DW_MACINFO_vendor_ext:
24626           /* Only skip the data by MAC_PTR.  */
24627           if (!section_is_gnu)
24628             {
24629               unsigned int bytes_read;
24630
24631               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24632               mac_ptr += bytes_read;
24633               read_direct_string (abfd, mac_ptr, &bytes_read);
24634               mac_ptr += bytes_read;
24635             }
24636           /* FALLTHROUGH */
24637
24638         default:
24639           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24640                                          mac_ptr, mac_end, abfd, offset_size,
24641                                          section);
24642           if (mac_ptr == NULL)
24643             return;
24644           break;
24645         }
24646       DIAGNOSTIC_POP
24647     } while (macinfo_type != 0 && current_file == NULL);
24648
24649   /* Second pass: Process all entries.
24650
24651      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24652      command-line macro definitions/undefinitions.  This flag is unset when we
24653      reach the first DW_MACINFO_start_file entry.  */
24654
24655   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24656                                            htab_eq_pointer,
24657                                            NULL, xcalloc, xfree));
24658   mac_ptr = section->buffer + offset;
24659   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24660   *slot = (void *) mac_ptr;
24661   dwarf_decode_macro_bytes (cu, abfd, mac_ptr, mac_end,
24662                             current_file, lh, section,
24663                             section_is_gnu, 0, offset_size,
24664                             include_hash.get ());
24665 }
24666
24667 /* Check if the attribute's form is a DW_FORM_block*
24668    if so return true else false.  */
24669
24670 static int
24671 attr_form_is_block (const struct attribute *attr)
24672 {
24673   return (attr == NULL ? 0 :
24674       attr->form == DW_FORM_block1
24675       || attr->form == DW_FORM_block2
24676       || attr->form == DW_FORM_block4
24677       || attr->form == DW_FORM_block
24678       || attr->form == DW_FORM_exprloc);
24679 }
24680
24681 /* Return non-zero if ATTR's value is a section offset --- classes
24682    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24683    You may use DW_UNSND (attr) to retrieve such offsets.
24684
24685    Section 7.5.4, "Attribute Encodings", explains that no attribute
24686    may have a value that belongs to more than one of these classes; it
24687    would be ambiguous if we did, because we use the same forms for all
24688    of them.  */
24689
24690 static int
24691 attr_form_is_section_offset (const struct attribute *attr)
24692 {
24693   return (attr->form == DW_FORM_data4
24694           || attr->form == DW_FORM_data8
24695           || attr->form == DW_FORM_sec_offset);
24696 }
24697
24698 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24699    zero otherwise.  When this function returns true, you can apply
24700    dwarf2_get_attr_constant_value to it.
24701
24702    However, note that for some attributes you must check
24703    attr_form_is_section_offset before using this test.  DW_FORM_data4
24704    and DW_FORM_data8 are members of both the constant class, and of
24705    the classes that contain offsets into other debug sections
24706    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24707    that, if an attribute's can be either a constant or one of the
24708    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24709    taken as section offsets, not constants.
24710
24711    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24712    cannot handle that.  */
24713
24714 static int
24715 attr_form_is_constant (const struct attribute *attr)
24716 {
24717   switch (attr->form)
24718     {
24719     case DW_FORM_sdata:
24720     case DW_FORM_udata:
24721     case DW_FORM_data1:
24722     case DW_FORM_data2:
24723     case DW_FORM_data4:
24724     case DW_FORM_data8:
24725     case DW_FORM_implicit_const:
24726       return 1;
24727     default:
24728       return 0;
24729     }
24730 }
24731
24732
24733 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24734    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24735
24736 static int
24737 attr_form_is_ref (const struct attribute *attr)
24738 {
24739   switch (attr->form)
24740     {
24741     case DW_FORM_ref_addr:
24742     case DW_FORM_ref1:
24743     case DW_FORM_ref2:
24744     case DW_FORM_ref4:
24745     case DW_FORM_ref8:
24746     case DW_FORM_ref_udata:
24747     case DW_FORM_GNU_ref_alt:
24748       return 1;
24749     default:
24750       return 0;
24751     }
24752 }
24753
24754 /* Return the .debug_loc section to use for CU.
24755    For DWO files use .debug_loc.dwo.  */
24756
24757 static struct dwarf2_section_info *
24758 cu_debug_loc_section (struct dwarf2_cu *cu)
24759 {
24760   struct dwarf2_per_objfile *dwarf2_per_objfile
24761     = cu->per_cu->dwarf2_per_objfile;
24762
24763   if (cu->dwo_unit)
24764     {
24765       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24766       
24767       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24768     }
24769   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24770                                   : &dwarf2_per_objfile->loc);
24771 }
24772
24773 /* A helper function that fills in a dwarf2_loclist_baton.  */
24774
24775 static void
24776 fill_in_loclist_baton (struct dwarf2_cu *cu,
24777                        struct dwarf2_loclist_baton *baton,
24778                        const struct attribute *attr)
24779 {
24780   struct dwarf2_per_objfile *dwarf2_per_objfile
24781     = cu->per_cu->dwarf2_per_objfile;
24782   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24783
24784   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24785
24786   baton->per_cu = cu->per_cu;
24787   gdb_assert (baton->per_cu);
24788   /* We don't know how long the location list is, but make sure we
24789      don't run off the edge of the section.  */
24790   baton->size = section->size - DW_UNSND (attr);
24791   baton->data = section->buffer + DW_UNSND (attr);
24792   baton->base_address = cu->base_address;
24793   baton->from_dwo = cu->dwo_unit != NULL;
24794 }
24795
24796 static void
24797 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24798                              struct dwarf2_cu *cu, int is_block)
24799 {
24800   struct dwarf2_per_objfile *dwarf2_per_objfile
24801     = cu->per_cu->dwarf2_per_objfile;
24802   struct objfile *objfile = dwarf2_per_objfile->objfile;
24803   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24804
24805   if (attr_form_is_section_offset (attr)
24806       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24807          the section.  If so, fall through to the complaint in the
24808          other branch.  */
24809       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24810     {
24811       struct dwarf2_loclist_baton *baton;
24812
24813       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24814
24815       fill_in_loclist_baton (cu, baton, attr);
24816
24817       if (cu->base_known == 0)
24818         complaint (_("Location list used without "
24819                      "specifying the CU base address."));
24820
24821       SYMBOL_ACLASS_INDEX (sym) = (is_block
24822                                    ? dwarf2_loclist_block_index
24823                                    : dwarf2_loclist_index);
24824       SYMBOL_LOCATION_BATON (sym) = baton;
24825     }
24826   else
24827     {
24828       struct dwarf2_locexpr_baton *baton;
24829
24830       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24831       baton->per_cu = cu->per_cu;
24832       gdb_assert (baton->per_cu);
24833
24834       if (attr_form_is_block (attr))
24835         {
24836           /* Note that we're just copying the block's data pointer
24837              here, not the actual data.  We're still pointing into the
24838              info_buffer for SYM's objfile; right now we never release
24839              that buffer, but when we do clean up properly this may
24840              need to change.  */
24841           baton->size = DW_BLOCK (attr)->size;
24842           baton->data = DW_BLOCK (attr)->data;
24843         }
24844       else
24845         {
24846           dwarf2_invalid_attrib_class_complaint ("location description",
24847                                                  SYMBOL_NATURAL_NAME (sym));
24848           baton->size = 0;
24849         }
24850
24851       SYMBOL_ACLASS_INDEX (sym) = (is_block
24852                                    ? dwarf2_locexpr_block_index
24853                                    : dwarf2_locexpr_index);
24854       SYMBOL_LOCATION_BATON (sym) = baton;
24855     }
24856 }
24857
24858 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24859    came from a separate debuginfo file, then the master objfile is
24860    returned.  */
24861
24862 struct objfile *
24863 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24864 {
24865   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24866
24867   /* Return the master objfile, so that we can report and look up the
24868      correct file containing this variable.  */
24869   if (objfile->separate_debug_objfile_backlink)
24870     objfile = objfile->separate_debug_objfile_backlink;
24871
24872   return objfile;
24873 }
24874
24875 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24876    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24877    CU_HEADERP first.  */
24878
24879 static const struct comp_unit_head *
24880 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24881                        struct dwarf2_per_cu_data *per_cu)
24882 {
24883   const gdb_byte *info_ptr;
24884
24885   if (per_cu->cu)
24886     return &per_cu->cu->header;
24887
24888   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24889
24890   memset (cu_headerp, 0, sizeof (*cu_headerp));
24891   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24892                        rcuh_kind::COMPILE);
24893
24894   return cu_headerp;
24895 }
24896
24897 /* Return the address size given in the compilation unit header for CU.  */
24898
24899 int
24900 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24901 {
24902   struct comp_unit_head cu_header_local;
24903   const struct comp_unit_head *cu_headerp;
24904
24905   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24906
24907   return cu_headerp->addr_size;
24908 }
24909
24910 /* Return the offset size given in the compilation unit header for CU.  */
24911
24912 int
24913 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24914 {
24915   struct comp_unit_head cu_header_local;
24916   const struct comp_unit_head *cu_headerp;
24917
24918   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24919
24920   return cu_headerp->offset_size;
24921 }
24922
24923 /* See its dwarf2loc.h declaration.  */
24924
24925 int
24926 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24927 {
24928   struct comp_unit_head cu_header_local;
24929   const struct comp_unit_head *cu_headerp;
24930
24931   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24932
24933   if (cu_headerp->version == 2)
24934     return cu_headerp->addr_size;
24935   else
24936     return cu_headerp->offset_size;
24937 }
24938
24939 /* Return the text offset of the CU.  The returned offset comes from
24940    this CU's objfile.  If this objfile came from a separate debuginfo
24941    file, then the offset may be different from the corresponding
24942    offset in the parent objfile.  */
24943
24944 CORE_ADDR
24945 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24946 {
24947   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24948
24949   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24950 }
24951
24952 /* Return DWARF version number of PER_CU.  */
24953
24954 short
24955 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24956 {
24957   return per_cu->dwarf_version;
24958 }
24959
24960 /* Locate the .debug_info compilation unit from CU's objfile which contains
24961    the DIE at OFFSET.  Raises an error on failure.  */
24962
24963 static struct dwarf2_per_cu_data *
24964 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24965                                   unsigned int offset_in_dwz,
24966                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24967 {
24968   struct dwarf2_per_cu_data *this_cu;
24969   int low, high;
24970   const sect_offset *cu_off;
24971
24972   low = 0;
24973   high = dwarf2_per_objfile->all_comp_units.size () - 1;
24974   while (high > low)
24975     {
24976       struct dwarf2_per_cu_data *mid_cu;
24977       int mid = low + (high - low) / 2;
24978
24979       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24980       cu_off = &mid_cu->sect_off;
24981       if (mid_cu->is_dwz > offset_in_dwz
24982           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24983         high = mid;
24984       else
24985         low = mid + 1;
24986     }
24987   gdb_assert (low == high);
24988   this_cu = dwarf2_per_objfile->all_comp_units[low];
24989   cu_off = &this_cu->sect_off;
24990   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24991     {
24992       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24993         error (_("Dwarf Error: could not find partial DIE containing "
24994                "offset %s [in module %s]"),
24995                sect_offset_str (sect_off),
24996                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
24997
24998       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24999                   <= sect_off);
25000       return dwarf2_per_objfile->all_comp_units[low-1];
25001     }
25002   else
25003     {
25004       this_cu = dwarf2_per_objfile->all_comp_units[low];
25005       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
25006           && sect_off >= this_cu->sect_off + this_cu->length)
25007         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
25008       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
25009       return this_cu;
25010     }
25011 }
25012
25013 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
25014
25015 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
25016   : per_cu (per_cu_),
25017     mark (0),
25018     has_loclist (0),
25019     checked_producer (0),
25020     producer_is_gxx_lt_4_6 (0),
25021     producer_is_gcc_lt_4_3 (0),
25022     producer_is_icc_lt_14 (0),
25023     processing_has_namespace_info (0)
25024 {
25025   per_cu->cu = this;
25026 }
25027
25028 /* Destroy a dwarf2_cu.  */
25029
25030 dwarf2_cu::~dwarf2_cu ()
25031 {
25032   per_cu->cu = NULL;
25033 }
25034
25035 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
25036
25037 static void
25038 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
25039                        enum language pretend_language)
25040 {
25041   struct attribute *attr;
25042
25043   /* Set the language we're debugging.  */
25044   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
25045   if (attr)
25046     set_cu_language (DW_UNSND (attr), cu);
25047   else
25048     {
25049       cu->language = pretend_language;
25050       cu->language_defn = language_def (cu->language);
25051     }
25052
25053   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
25054 }
25055
25056 /* Increase the age counter on each cached compilation unit, and free
25057    any that are too old.  */
25058
25059 static void
25060 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
25061 {
25062   struct dwarf2_per_cu_data *per_cu, **last_chain;
25063
25064   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
25065   per_cu = dwarf2_per_objfile->read_in_chain;
25066   while (per_cu != NULL)
25067     {
25068       per_cu->cu->last_used ++;
25069       if (per_cu->cu->last_used <= dwarf_max_cache_age)
25070         dwarf2_mark (per_cu->cu);
25071       per_cu = per_cu->cu->read_in_chain;
25072     }
25073
25074   per_cu = dwarf2_per_objfile->read_in_chain;
25075   last_chain = &dwarf2_per_objfile->read_in_chain;
25076   while (per_cu != NULL)
25077     {
25078       struct dwarf2_per_cu_data *next_cu;
25079
25080       next_cu = per_cu->cu->read_in_chain;
25081
25082       if (!per_cu->cu->mark)
25083         {
25084           delete per_cu->cu;
25085           *last_chain = next_cu;
25086         }
25087       else
25088         last_chain = &per_cu->cu->read_in_chain;
25089
25090       per_cu = next_cu;
25091     }
25092 }
25093
25094 /* Remove a single compilation unit from the cache.  */
25095
25096 static void
25097 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
25098 {
25099   struct dwarf2_per_cu_data *per_cu, **last_chain;
25100   struct dwarf2_per_objfile *dwarf2_per_objfile
25101     = target_per_cu->dwarf2_per_objfile;
25102
25103   per_cu = dwarf2_per_objfile->read_in_chain;
25104   last_chain = &dwarf2_per_objfile->read_in_chain;
25105   while (per_cu != NULL)
25106     {
25107       struct dwarf2_per_cu_data *next_cu;
25108
25109       next_cu = per_cu->cu->read_in_chain;
25110
25111       if (per_cu == target_per_cu)
25112         {
25113           delete per_cu->cu;
25114           per_cu->cu = NULL;
25115           *last_chain = next_cu;
25116           break;
25117         }
25118       else
25119         last_chain = &per_cu->cu->read_in_chain;
25120
25121       per_cu = next_cu;
25122     }
25123 }
25124
25125 /* Cleanup function for the dwarf2_per_objfile data.  */
25126
25127 static void
25128 dwarf2_free_objfile (struct objfile *objfile, void *datum)
25129 {
25130   struct dwarf2_per_objfile *dwarf2_per_objfile
25131     = static_cast<struct dwarf2_per_objfile *> (datum);
25132
25133   delete dwarf2_per_objfile;
25134 }
25135
25136 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25137    We store these in a hash table separate from the DIEs, and preserve them
25138    when the DIEs are flushed out of cache.
25139
25140    The CU "per_cu" pointer is needed because offset alone is not enough to
25141    uniquely identify the type.  A file may have multiple .debug_types sections,
25142    or the type may come from a DWO file.  Furthermore, while it's more logical
25143    to use per_cu->section+offset, with Fission the section with the data is in
25144    the DWO file but we don't know that section at the point we need it.
25145    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25146    because we can enter the lookup routine, get_die_type_at_offset, from
25147    outside this file, and thus won't necessarily have PER_CU->cu.
25148    Fortunately, PER_CU is stable for the life of the objfile.  */
25149
25150 struct dwarf2_per_cu_offset_and_type
25151 {
25152   const struct dwarf2_per_cu_data *per_cu;
25153   sect_offset sect_off;
25154   struct type *type;
25155 };
25156
25157 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25158
25159 static hashval_t
25160 per_cu_offset_and_type_hash (const void *item)
25161 {
25162   const struct dwarf2_per_cu_offset_and_type *ofs
25163     = (const struct dwarf2_per_cu_offset_and_type *) item;
25164
25165   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25166 }
25167
25168 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25169
25170 static int
25171 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25172 {
25173   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25174     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25175   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25176     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25177
25178   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25179           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25180 }
25181
25182 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25183    table if necessary.  For convenience, return TYPE.
25184
25185    The DIEs reading must have careful ordering to:
25186     * Not cause infite loops trying to read in DIEs as a prerequisite for
25187       reading current DIE.
25188     * Not trying to dereference contents of still incompletely read in types
25189       while reading in other DIEs.
25190     * Enable referencing still incompletely read in types just by a pointer to
25191       the type without accessing its fields.
25192
25193    Therefore caller should follow these rules:
25194      * Try to fetch any prerequisite types we may need to build this DIE type
25195        before building the type and calling set_die_type.
25196      * After building type call set_die_type for current DIE as soon as
25197        possible before fetching more types to complete the current type.
25198      * Make the type as complete as possible before fetching more types.  */
25199
25200 static struct type *
25201 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25202 {
25203   struct dwarf2_per_objfile *dwarf2_per_objfile
25204     = cu->per_cu->dwarf2_per_objfile;
25205   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25206   struct objfile *objfile = dwarf2_per_objfile->objfile;
25207   struct attribute *attr;
25208   struct dynamic_prop prop;
25209
25210   /* For Ada types, make sure that the gnat-specific data is always
25211      initialized (if not already set).  There are a few types where
25212      we should not be doing so, because the type-specific area is
25213      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25214      where the type-specific area is used to store the floatformat).
25215      But this is not a problem, because the gnat-specific information
25216      is actually not needed for these types.  */
25217   if (need_gnat_info (cu)
25218       && TYPE_CODE (type) != TYPE_CODE_FUNC
25219       && TYPE_CODE (type) != TYPE_CODE_FLT
25220       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25221       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25222       && TYPE_CODE (type) != TYPE_CODE_METHOD
25223       && !HAVE_GNAT_AUX_INFO (type))
25224     INIT_GNAT_SPECIFIC (type);
25225
25226   /* Read DW_AT_allocated and set in type.  */
25227   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25228   if (attr_form_is_block (attr))
25229     {
25230       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25231         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25232     }
25233   else if (attr != NULL)
25234     {
25235       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25236                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25237                  sect_offset_str (die->sect_off));
25238     }
25239
25240   /* Read DW_AT_associated and set in type.  */
25241   attr = dwarf2_attr (die, DW_AT_associated, cu);
25242   if (attr_form_is_block (attr))
25243     {
25244       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25245         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25246     }
25247   else if (attr != NULL)
25248     {
25249       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25250                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25251                  sect_offset_str (die->sect_off));
25252     }
25253
25254   /* Read DW_AT_data_location and set in type.  */
25255   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25256   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25257     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25258
25259   if (dwarf2_per_objfile->die_type_hash == NULL)
25260     {
25261       dwarf2_per_objfile->die_type_hash =
25262         htab_create_alloc_ex (127,
25263                               per_cu_offset_and_type_hash,
25264                               per_cu_offset_and_type_eq,
25265                               NULL,
25266                               &objfile->objfile_obstack,
25267                               hashtab_obstack_allocate,
25268                               dummy_obstack_deallocate);
25269     }
25270
25271   ofs.per_cu = cu->per_cu;
25272   ofs.sect_off = die->sect_off;
25273   ofs.type = type;
25274   slot = (struct dwarf2_per_cu_offset_and_type **)
25275     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25276   if (*slot)
25277     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25278                sect_offset_str (die->sect_off));
25279   *slot = XOBNEW (&objfile->objfile_obstack,
25280                   struct dwarf2_per_cu_offset_and_type);
25281   **slot = ofs;
25282   return type;
25283 }
25284
25285 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25286    or return NULL if the die does not have a saved type.  */
25287
25288 static struct type *
25289 get_die_type_at_offset (sect_offset sect_off,
25290                         struct dwarf2_per_cu_data *per_cu)
25291 {
25292   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25293   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25294
25295   if (dwarf2_per_objfile->die_type_hash == NULL)
25296     return NULL;
25297
25298   ofs.per_cu = per_cu;
25299   ofs.sect_off = sect_off;
25300   slot = ((struct dwarf2_per_cu_offset_and_type *)
25301           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25302   if (slot)
25303     return slot->type;
25304   else
25305     return NULL;
25306 }
25307
25308 /* Look up the type for DIE in CU in die_type_hash,
25309    or return NULL if DIE does not have a saved type.  */
25310
25311 static struct type *
25312 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25313 {
25314   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25315 }
25316
25317 /* Add a dependence relationship from CU to REF_PER_CU.  */
25318
25319 static void
25320 dwarf2_add_dependence (struct dwarf2_cu *cu,
25321                        struct dwarf2_per_cu_data *ref_per_cu)
25322 {
25323   void **slot;
25324
25325   if (cu->dependencies == NULL)
25326     cu->dependencies
25327       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25328                               NULL, &cu->comp_unit_obstack,
25329                               hashtab_obstack_allocate,
25330                               dummy_obstack_deallocate);
25331
25332   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25333   if (*slot == NULL)
25334     *slot = ref_per_cu;
25335 }
25336
25337 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25338    Set the mark field in every compilation unit in the
25339    cache that we must keep because we are keeping CU.  */
25340
25341 static int
25342 dwarf2_mark_helper (void **slot, void *data)
25343 {
25344   struct dwarf2_per_cu_data *per_cu;
25345
25346   per_cu = (struct dwarf2_per_cu_data *) *slot;
25347
25348   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25349      reading of the chain.  As such dependencies remain valid it is not much
25350      useful to track and undo them during QUIT cleanups.  */
25351   if (per_cu->cu == NULL)
25352     return 1;
25353
25354   if (per_cu->cu->mark)
25355     return 1;
25356   per_cu->cu->mark = 1;
25357
25358   if (per_cu->cu->dependencies != NULL)
25359     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25360
25361   return 1;
25362 }
25363
25364 /* Set the mark field in CU and in every other compilation unit in the
25365    cache that we must keep because we are keeping CU.  */
25366
25367 static void
25368 dwarf2_mark (struct dwarf2_cu *cu)
25369 {
25370   if (cu->mark)
25371     return;
25372   cu->mark = 1;
25373   if (cu->dependencies != NULL)
25374     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25375 }
25376
25377 static void
25378 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25379 {
25380   while (per_cu)
25381     {
25382       per_cu->cu->mark = 0;
25383       per_cu = per_cu->cu->read_in_chain;
25384     }
25385 }
25386
25387 /* Trivial hash function for partial_die_info: the hash value of a DIE
25388    is its offset in .debug_info for this objfile.  */
25389
25390 static hashval_t
25391 partial_die_hash (const void *item)
25392 {
25393   const struct partial_die_info *part_die
25394     = (const struct partial_die_info *) item;
25395
25396   return to_underlying (part_die->sect_off);
25397 }
25398
25399 /* Trivial comparison function for partial_die_info structures: two DIEs
25400    are equal if they have the same offset.  */
25401
25402 static int
25403 partial_die_eq (const void *item_lhs, const void *item_rhs)
25404 {
25405   const struct partial_die_info *part_die_lhs
25406     = (const struct partial_die_info *) item_lhs;
25407   const struct partial_die_info *part_die_rhs
25408     = (const struct partial_die_info *) item_rhs;
25409
25410   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25411 }
25412
25413 struct cmd_list_element *set_dwarf_cmdlist;
25414 struct cmd_list_element *show_dwarf_cmdlist;
25415
25416 static void
25417 set_dwarf_cmd (const char *args, int from_tty)
25418 {
25419   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25420              gdb_stdout);
25421 }
25422
25423 static void
25424 show_dwarf_cmd (const char *args, int from_tty)
25425 {
25426   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25427 }
25428
25429 int dwarf_always_disassemble;
25430
25431 static void
25432 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25433                                struct cmd_list_element *c, const char *value)
25434 {
25435   fprintf_filtered (file,
25436                     _("Whether to always disassemble "
25437                       "DWARF expressions is %s.\n"),
25438                     value);
25439 }
25440
25441 static void
25442 show_check_physname (struct ui_file *file, int from_tty,
25443                      struct cmd_list_element *c, const char *value)
25444 {
25445   fprintf_filtered (file,
25446                     _("Whether to check \"physname\" is %s.\n"),
25447                     value);
25448 }
25449
25450 void
25451 _initialize_dwarf2_read (void)
25452 {
25453   dwarf2_objfile_data_key
25454     = register_objfile_data_with_cleanup (nullptr, dwarf2_free_objfile);
25455
25456   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25457 Set DWARF specific variables.\n\
25458 Configure DWARF variables such as the cache size"),
25459                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25460                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25461
25462   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25463 Show DWARF specific variables\n\
25464 Show DWARF variables such as the cache size"),
25465                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25466                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25467
25468   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25469                             &dwarf_max_cache_age, _("\
25470 Set the upper bound on the age of cached DWARF compilation units."), _("\
25471 Show the upper bound on the age of cached DWARF compilation units."), _("\
25472 A higher limit means that cached compilation units will be stored\n\
25473 in memory longer, and more total memory will be used.  Zero disables\n\
25474 caching, which can slow down startup."),
25475                             NULL,
25476                             show_dwarf_max_cache_age,
25477                             &set_dwarf_cmdlist,
25478                             &show_dwarf_cmdlist);
25479
25480   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25481                            &dwarf_always_disassemble, _("\
25482 Set whether `info address' always disassembles DWARF expressions."), _("\
25483 Show whether `info address' always disassembles DWARF expressions."), _("\
25484 When enabled, DWARF expressions are always printed in an assembly-like\n\
25485 syntax.  When disabled, expressions will be printed in a more\n\
25486 conversational style, when possible."),
25487                            NULL,
25488                            show_dwarf_always_disassemble,
25489                            &set_dwarf_cmdlist,
25490                            &show_dwarf_cmdlist);
25491
25492   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25493 Set debugging of the DWARF reader."), _("\
25494 Show debugging of the DWARF reader."), _("\
25495 When enabled (non-zero), debugging messages are printed during DWARF\n\
25496 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25497 information.  A value greater than 1 provides more verbose information."),
25498                             NULL,
25499                             NULL,
25500                             &setdebuglist, &showdebuglist);
25501
25502   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25503 Set debugging of the DWARF DIE reader."), _("\
25504 Show debugging of the DWARF DIE reader."), _("\
25505 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25506 The value is the maximum depth to print."),
25507                              NULL,
25508                              NULL,
25509                              &setdebuglist, &showdebuglist);
25510
25511   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25512 Set debugging of the dwarf line reader."), _("\
25513 Show debugging of the dwarf line reader."), _("\
25514 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25515 A value of 1 (one) provides basic information.\n\
25516 A value greater than 1 provides more verbose information."),
25517                              NULL,
25518                              NULL,
25519                              &setdebuglist, &showdebuglist);
25520
25521   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25522 Set cross-checking of \"physname\" code against demangler."), _("\
25523 Show cross-checking of \"physname\" code against demangler."), _("\
25524 When enabled, GDB's internal \"physname\" code is checked against\n\
25525 the demangler."),
25526                            NULL, show_check_physname,
25527                            &setdebuglist, &showdebuglist);
25528
25529   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25530                            no_class, &use_deprecated_index_sections, _("\
25531 Set whether to use deprecated gdb_index sections."), _("\
25532 Show whether to use deprecated gdb_index sections."), _("\
25533 When enabled, deprecated .gdb_index sections are used anyway.\n\
25534 Normally they are ignored either because of a missing feature or\n\
25535 performance issue.\n\
25536 Warning: This option must be enabled before gdb reads the file."),
25537                            NULL,
25538                            NULL,
25539                            &setlist, &showlist);
25540
25541   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25542                                                         &dwarf2_locexpr_funcs);
25543   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25544                                                         &dwarf2_loclist_funcs);
25545
25546   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25547                                         &dwarf2_block_frame_base_locexpr_funcs);
25548   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25549                                         &dwarf2_block_frame_base_loclist_funcs);
25550
25551 #if GDB_SELF_TEST
25552   selftests::register_test ("dw2_expand_symtabs_matching",
25553                             selftests::dw2_expand_symtabs_matching::run_test);
25554 #endif
25555 }