[gdb/symtab] Fix version check in dwarf compilation unit header
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2018 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "dwarf2read.h"
33 #include "dwarf-index-common.h"
34 #include "bfd.h"
35 #include "elf-bfd.h"
36 #include "symtab.h"
37 #include "gdbtypes.h"
38 #include "objfiles.h"
39 #include "dwarf2.h"
40 #include "buildsym.h"
41 #include "demangle.h"
42 #include "gdb-demangle.h"
43 #include "expression.h"
44 #include "filenames.h"  /* for DOSish file names */
45 #include "macrotab.h"
46 #include "language.h"
47 #include "complaints.h"
48 #include "bcache.h"
49 #include "dwarf2expr.h"
50 #include "dwarf2loc.h"
51 #include "cp-support.h"
52 #include "hashtab.h"
53 #include "command.h"
54 #include "gdbcmd.h"
55 #include "block.h"
56 #include "addrmap.h"
57 #include "typeprint.h"
58 #include "psympriv.h"
59 #include <sys/stat.h>
60 #include "completer.h"
61 #include "vec.h"
62 #include "c-lang.h"
63 #include "go-lang.h"
64 #include "valprint.h"
65 #include "gdbcore.h" /* for gnutarget */
66 #include "gdb/gdb-index.h"
67 #include <ctype.h>
68 #include "gdb_bfd.h"
69 #include "f-lang.h"
70 #include "source.h"
71 #include "filestuff.h"
72 #include "build-id.h"
73 #include "namespace.h"
74 #include "common/gdb_unlinker.h"
75 #include "common/function-view.h"
76 #include "common/gdb_optional.h"
77 #include "common/underlying.h"
78 #include "common/byte-vector.h"
79 #include "common/hash_enum.h"
80 #include "filename-seen-cache.h"
81 #include "producer.h"
82 #include <fcntl.h>
83 #include <sys/types.h>
84 #include <algorithm>
85 #include <unordered_set>
86 #include <unordered_map>
87 #include "selftest.h"
88 #include <cmath>
89 #include <set>
90 #include <forward_list>
91 #include "rust-lang.h"
92 #include "common/pathstuff.h"
93
94 /* When == 1, print basic high level tracing messages.
95    When > 1, be more verbose.
96    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
97 static unsigned int dwarf_read_debug = 0;
98
99 /* When non-zero, dump DIEs after they are read in.  */
100 static unsigned int dwarf_die_debug = 0;
101
102 /* When non-zero, dump line number entries as they are read in.  */
103 static unsigned int dwarf_line_debug = 0;
104
105 /* When non-zero, cross-check physname against demangler.  */
106 static int check_physname = 0;
107
108 /* When non-zero, do not reject deprecated .gdb_index sections.  */
109 static int use_deprecated_index_sections = 0;
110
111 static const struct objfile_data *dwarf2_objfile_data_key;
112
113 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
114
115 static int dwarf2_locexpr_index;
116 static int dwarf2_loclist_index;
117 static int dwarf2_locexpr_block_index;
118 static int dwarf2_loclist_block_index;
119
120 /* An index into a (C++) symbol name component in a symbol name as
121    recorded in the mapped_index's symbol table.  For each C++ symbol
122    in the symbol table, we record one entry for the start of each
123    component in the symbol in a table of name components, and then
124    sort the table, in order to be able to binary search symbol names,
125    ignoring leading namespaces, both completion and regular look up.
126    For example, for symbol "A::B::C", we'll have an entry that points
127    to "A::B::C", another that points to "B::C", and another for "C".
128    Note that function symbols in GDB index have no parameter
129    information, just the function/method names.  You can convert a
130    name_component to a "const char *" using the
131    'mapped_index::symbol_name_at(offset_type)' method.  */
132
133 struct name_component
134 {
135   /* Offset in the symbol name where the component starts.  Stored as
136      a (32-bit) offset instead of a pointer to save memory and improve
137      locality on 64-bit architectures.  */
138   offset_type name_offset;
139
140   /* The symbol's index in the symbol and constant pool tables of a
141      mapped_index.  */
142   offset_type idx;
143 };
144
145 /* Base class containing bits shared by both .gdb_index and
146    .debug_name indexes.  */
147
148 struct mapped_index_base
149 {
150   mapped_index_base () = default;
151   DISABLE_COPY_AND_ASSIGN (mapped_index_base);
152
153   /* The name_component table (a sorted vector).  See name_component's
154      description above.  */
155   std::vector<name_component> name_components;
156
157   /* How NAME_COMPONENTS is sorted.  */
158   enum case_sensitivity name_components_casing;
159
160   /* Return the number of names in the symbol table.  */
161   virtual size_t symbol_name_count () const = 0;
162
163   /* Get the name of the symbol at IDX in the symbol table.  */
164   virtual const char *symbol_name_at (offset_type idx) const = 0;
165
166   /* Return whether the name at IDX in the symbol table should be
167      ignored.  */
168   virtual bool symbol_name_slot_invalid (offset_type idx) const
169   {
170     return false;
171   }
172
173   /* Build the symbol name component sorted vector, if we haven't
174      yet.  */
175   void build_name_components ();
176
177   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
178      possible matches for LN_NO_PARAMS in the name component
179      vector.  */
180   std::pair<std::vector<name_component>::const_iterator,
181             std::vector<name_component>::const_iterator>
182     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
183
184   /* Prevent deleting/destroying via a base class pointer.  */
185 protected:
186   ~mapped_index_base() = default;
187 };
188
189 /* A description of the mapped index.  The file format is described in
190    a comment by the code that writes the index.  */
191 struct mapped_index final : public mapped_index_base
192 {
193   /* A slot/bucket in the symbol table hash.  */
194   struct symbol_table_slot
195   {
196     const offset_type name;
197     const offset_type vec;
198   };
199
200   /* Index data format version.  */
201   int version = 0;
202
203   /* The address table data.  */
204   gdb::array_view<const gdb_byte> address_table;
205
206   /* The symbol table, implemented as a hash table.  */
207   gdb::array_view<symbol_table_slot> symbol_table;
208
209   /* A pointer to the constant pool.  */
210   const char *constant_pool = nullptr;
211
212   bool symbol_name_slot_invalid (offset_type idx) const override
213   {
214     const auto &bucket = this->symbol_table[idx];
215     return bucket.name == 0 && bucket.vec;
216   }
217
218   /* Convenience method to get at the name of the symbol at IDX in the
219      symbol table.  */
220   const char *symbol_name_at (offset_type idx) const override
221   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx].name); }
222
223   size_t symbol_name_count () const override
224   { return this->symbol_table.size (); }
225 };
226
227 /* A description of the mapped .debug_names.
228    Uninitialized map has CU_COUNT 0.  */
229 struct mapped_debug_names final : public mapped_index_base
230 {
231   mapped_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile_)
232   : dwarf2_per_objfile (dwarf2_per_objfile_)
233   {}
234
235   struct dwarf2_per_objfile *dwarf2_per_objfile;
236   bfd_endian dwarf5_byte_order;
237   bool dwarf5_is_dwarf64;
238   bool augmentation_is_gdb;
239   uint8_t offset_size;
240   uint32_t cu_count = 0;
241   uint32_t tu_count, bucket_count, name_count;
242   const gdb_byte *cu_table_reordered, *tu_table_reordered;
243   const uint32_t *bucket_table_reordered, *hash_table_reordered;
244   const gdb_byte *name_table_string_offs_reordered;
245   const gdb_byte *name_table_entry_offs_reordered;
246   const gdb_byte *entry_pool;
247
248   struct index_val
249   {
250     ULONGEST dwarf_tag;
251     struct attr
252     {
253       /* Attribute name DW_IDX_*.  */
254       ULONGEST dw_idx;
255
256       /* Attribute form DW_FORM_*.  */
257       ULONGEST form;
258
259       /* Value if FORM is DW_FORM_implicit_const.  */
260       LONGEST implicit_const;
261     };
262     std::vector<attr> attr_vec;
263   };
264
265   std::unordered_map<ULONGEST, index_val> abbrev_map;
266
267   const char *namei_to_name (uint32_t namei) const;
268
269   /* Implementation of the mapped_index_base virtual interface, for
270      the name_components cache.  */
271
272   const char *symbol_name_at (offset_type idx) const override
273   { return namei_to_name (idx); }
274
275   size_t symbol_name_count () const override
276   { return this->name_count; }
277 };
278
279 /* See dwarf2read.h.  */
280
281 dwarf2_per_objfile *
282 get_dwarf2_per_objfile (struct objfile *objfile)
283 {
284   return ((struct dwarf2_per_objfile *)
285           objfile_data (objfile, dwarf2_objfile_data_key));
286 }
287
288 /* Set the dwarf2_per_objfile associated to OBJFILE.  */
289
290 void
291 set_dwarf2_per_objfile (struct objfile *objfile,
292                         struct dwarf2_per_objfile *dwarf2_per_objfile)
293 {
294   gdb_assert (get_dwarf2_per_objfile (objfile) == NULL);
295   set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
296 }
297
298 /* Default names of the debugging sections.  */
299
300 /* Note that if the debugging section has been compressed, it might
301    have a name like .zdebug_info.  */
302
303 static const struct dwarf2_debug_sections dwarf2_elf_names =
304 {
305   { ".debug_info", ".zdebug_info" },
306   { ".debug_abbrev", ".zdebug_abbrev" },
307   { ".debug_line", ".zdebug_line" },
308   { ".debug_loc", ".zdebug_loc" },
309   { ".debug_loclists", ".zdebug_loclists" },
310   { ".debug_macinfo", ".zdebug_macinfo" },
311   { ".debug_macro", ".zdebug_macro" },
312   { ".debug_str", ".zdebug_str" },
313   { ".debug_line_str", ".zdebug_line_str" },
314   { ".debug_ranges", ".zdebug_ranges" },
315   { ".debug_rnglists", ".zdebug_rnglists" },
316   { ".debug_types", ".zdebug_types" },
317   { ".debug_addr", ".zdebug_addr" },
318   { ".debug_frame", ".zdebug_frame" },
319   { ".eh_frame", NULL },
320   { ".gdb_index", ".zgdb_index" },
321   { ".debug_names", ".zdebug_names" },
322   { ".debug_aranges", ".zdebug_aranges" },
323   23
324 };
325
326 /* List of DWO/DWP sections.  */
327
328 static const struct dwop_section_names
329 {
330   struct dwarf2_section_names abbrev_dwo;
331   struct dwarf2_section_names info_dwo;
332   struct dwarf2_section_names line_dwo;
333   struct dwarf2_section_names loc_dwo;
334   struct dwarf2_section_names loclists_dwo;
335   struct dwarf2_section_names macinfo_dwo;
336   struct dwarf2_section_names macro_dwo;
337   struct dwarf2_section_names str_dwo;
338   struct dwarf2_section_names str_offsets_dwo;
339   struct dwarf2_section_names types_dwo;
340   struct dwarf2_section_names cu_index;
341   struct dwarf2_section_names tu_index;
342 }
343 dwop_section_names =
344 {
345   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
346   { ".debug_info.dwo", ".zdebug_info.dwo" },
347   { ".debug_line.dwo", ".zdebug_line.dwo" },
348   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
349   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
350   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
351   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
352   { ".debug_str.dwo", ".zdebug_str.dwo" },
353   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
354   { ".debug_types.dwo", ".zdebug_types.dwo" },
355   { ".debug_cu_index", ".zdebug_cu_index" },
356   { ".debug_tu_index", ".zdebug_tu_index" },
357 };
358
359 /* local data types */
360
361 /* The data in a compilation unit header, after target2host
362    translation, looks like this.  */
363 struct comp_unit_head
364 {
365   unsigned int length;
366   short version;
367   unsigned char addr_size;
368   unsigned char signed_addr_p;
369   sect_offset abbrev_sect_off;
370
371   /* Size of file offsets; either 4 or 8.  */
372   unsigned int offset_size;
373
374   /* Size of the length field; either 4 or 12.  */
375   unsigned int initial_length_size;
376
377   enum dwarf_unit_type unit_type;
378
379   /* Offset to the first byte of this compilation unit header in the
380      .debug_info section, for resolving relative reference dies.  */
381   sect_offset sect_off;
382
383   /* Offset to first die in this cu from the start of the cu.
384      This will be the first byte following the compilation unit header.  */
385   cu_offset first_die_cu_offset;
386
387   /* 64-bit signature of this type unit - it is valid only for
388      UNIT_TYPE DW_UT_type.  */
389   ULONGEST signature;
390
391   /* For types, offset in the type's DIE of the type defined by this TU.  */
392   cu_offset type_cu_offset_in_tu;
393 };
394
395 /* Type used for delaying computation of method physnames.
396    See comments for compute_delayed_physnames.  */
397 struct delayed_method_info
398 {
399   /* The type to which the method is attached, i.e., its parent class.  */
400   struct type *type;
401
402   /* The index of the method in the type's function fieldlists.  */
403   int fnfield_index;
404
405   /* The index of the method in the fieldlist.  */
406   int index;
407
408   /* The name of the DIE.  */
409   const char *name;
410
411   /*  The DIE associated with this method.  */
412   struct die_info *die;
413 };
414
415 /* Internal state when decoding a particular compilation unit.  */
416 struct dwarf2_cu
417 {
418   explicit dwarf2_cu (struct dwarf2_per_cu_data *per_cu);
419   ~dwarf2_cu ();
420
421   DISABLE_COPY_AND_ASSIGN (dwarf2_cu);
422
423   /* The header of the compilation unit.  */
424   struct comp_unit_head header {};
425
426   /* Base address of this compilation unit.  */
427   CORE_ADDR base_address = 0;
428
429   /* Non-zero if base_address has been set.  */
430   int base_known = 0;
431
432   /* The language we are debugging.  */
433   enum language language = language_unknown;
434   const struct language_defn *language_defn = nullptr;
435
436   const char *producer = nullptr;
437
438   /* The generic symbol table building routines have separate lists for
439      file scope symbols and all all other scopes (local scopes).  So
440      we need to select the right one to pass to add_symbol_to_list().
441      We do it by keeping a pointer to the correct list in list_in_scope.
442
443      FIXME: The original dwarf code just treated the file scope as the
444      first local scope, and all other local scopes as nested local
445      scopes, and worked fine.  Check to see if we really need to
446      distinguish these in buildsym.c.  */
447   struct pending **list_in_scope = nullptr;
448
449   /* Hash table holding all the loaded partial DIEs
450      with partial_die->offset.SECT_OFF as hash.  */
451   htab_t partial_dies = nullptr;
452
453   /* Storage for things with the same lifetime as this read-in compilation
454      unit, including partial DIEs.  */
455   auto_obstack comp_unit_obstack;
456
457   /* When multiple dwarf2_cu structures are living in memory, this field
458      chains them all together, so that they can be released efficiently.
459      We will probably also want a generation counter so that most-recently-used
460      compilation units are cached...  */
461   struct dwarf2_per_cu_data *read_in_chain = nullptr;
462
463   /* Backlink to our per_cu entry.  */
464   struct dwarf2_per_cu_data *per_cu;
465
466   /* How many compilation units ago was this CU last referenced?  */
467   int last_used = 0;
468
469   /* A hash table of DIE cu_offset for following references with
470      die_info->offset.sect_off as hash.  */
471   htab_t die_hash = nullptr;
472
473   /* Full DIEs if read in.  */
474   struct die_info *dies = nullptr;
475
476   /* A set of pointers to dwarf2_per_cu_data objects for compilation
477      units referenced by this one.  Only set during full symbol processing;
478      partial symbol tables do not have dependencies.  */
479   htab_t dependencies = nullptr;
480
481   /* Header data from the line table, during full symbol processing.  */
482   struct line_header *line_header = nullptr;
483   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
484      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
485      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
486      to the line header as long as this DIE is being processed.  See
487      process_die_scope.  */
488   die_info *line_header_die_owner = nullptr;
489
490   /* A list of methods which need to have physnames computed
491      after all type information has been read.  */
492   std::vector<delayed_method_info> method_list;
493
494   /* To be copied to symtab->call_site_htab.  */
495   htab_t call_site_htab = nullptr;
496
497   /* Non-NULL if this CU came from a DWO file.
498      There is an invariant here that is important to remember:
499      Except for attributes copied from the top level DIE in the "main"
500      (or "stub") file in preparation for reading the DWO file
501      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
502      Either there isn't a DWO file (in which case this is NULL and the point
503      is moot), or there is and either we're not going to read it (in which
504      case this is NULL) or there is and we are reading it (in which case this
505      is non-NULL).  */
506   struct dwo_unit *dwo_unit = nullptr;
507
508   /* The DW_AT_addr_base attribute if present, zero otherwise
509      (zero is a valid value though).
510      Note this value comes from the Fission stub CU/TU's DIE.  */
511   ULONGEST addr_base = 0;
512
513   /* The DW_AT_ranges_base attribute if present, zero otherwise
514      (zero is a valid value though).
515      Note this value comes from the Fission stub CU/TU's DIE.
516      Also note that the value is zero in the non-DWO case so this value can
517      be used without needing to know whether DWO files are in use or not.
518      N.B. This does not apply to DW_AT_ranges appearing in
519      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
520      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
521      DW_AT_ranges_base *would* have to be applied, and we'd have to care
522      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
523   ULONGEST ranges_base = 0;
524
525   /* When reading debug info generated by older versions of rustc, we
526      have to rewrite some union types to be struct types with a
527      variant part.  This rewriting must be done after the CU is fully
528      read in, because otherwise at the point of rewriting some struct
529      type might not have been fully processed.  So, we keep a list of
530      all such types here and process them after expansion.  */
531   std::vector<struct type *> rust_unions;
532
533   /* Mark used when releasing cached dies.  */
534   unsigned int mark : 1;
535
536   /* This CU references .debug_loc.  See the symtab->locations_valid field.
537      This test is imperfect as there may exist optimized debug code not using
538      any location list and still facing inlining issues if handled as
539      unoptimized code.  For a future better test see GCC PR other/32998.  */
540   unsigned int has_loclist : 1;
541
542   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
543      if all the producer_is_* fields are valid.  This information is cached
544      because profiling CU expansion showed excessive time spent in
545      producer_is_gxx_lt_4_6.  */
546   unsigned int checked_producer : 1;
547   unsigned int producer_is_gxx_lt_4_6 : 1;
548   unsigned int producer_is_gcc_lt_4_3 : 1;
549   unsigned int producer_is_icc_lt_14 : 1;
550
551   /* When set, the file that we're processing is known to have
552      debugging info for C++ namespaces.  GCC 3.3.x did not produce
553      this information, but later versions do.  */
554
555   unsigned int processing_has_namespace_info : 1;
556
557   struct partial_die_info *find_partial_die (sect_offset sect_off);
558 };
559
560 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
561    This includes type_unit_group and quick_file_names.  */
562
563 struct stmt_list_hash
564 {
565   /* The DWO unit this table is from or NULL if there is none.  */
566   struct dwo_unit *dwo_unit;
567
568   /* Offset in .debug_line or .debug_line.dwo.  */
569   sect_offset line_sect_off;
570 };
571
572 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
573    an object of this type.  */
574
575 struct type_unit_group
576 {
577   /* dwarf2read.c's main "handle" on a TU symtab.
578      To simplify things we create an artificial CU that "includes" all the
579      type units using this stmt_list so that the rest of the code still has
580      a "per_cu" handle on the symtab.
581      This PER_CU is recognized by having no section.  */
582 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
583   struct dwarf2_per_cu_data per_cu;
584
585   /* The TUs that share this DW_AT_stmt_list entry.
586      This is added to while parsing type units to build partial symtabs,
587      and is deleted afterwards and not used again.  */
588   VEC (sig_type_ptr) *tus;
589
590   /* The compunit symtab.
591      Type units in a group needn't all be defined in the same source file,
592      so we create an essentially anonymous symtab as the compunit symtab.  */
593   struct compunit_symtab *compunit_symtab;
594
595   /* The data used to construct the hash key.  */
596   struct stmt_list_hash hash;
597
598   /* The number of symtabs from the line header.
599      The value here must match line_header.num_file_names.  */
600   unsigned int num_symtabs;
601
602   /* The symbol tables for this TU (obtained from the files listed in
603      DW_AT_stmt_list).
604      WARNING: The order of entries here must match the order of entries
605      in the line header.  After the first TU using this type_unit_group, the
606      line header for the subsequent TUs is recreated from this.  This is done
607      because we need to use the same symtabs for each TU using the same
608      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
609      there's no guarantee the line header doesn't have duplicate entries.  */
610   struct symtab **symtabs;
611 };
612
613 /* These sections are what may appear in a (real or virtual) DWO file.  */
614
615 struct dwo_sections
616 {
617   struct dwarf2_section_info abbrev;
618   struct dwarf2_section_info line;
619   struct dwarf2_section_info loc;
620   struct dwarf2_section_info loclists;
621   struct dwarf2_section_info macinfo;
622   struct dwarf2_section_info macro;
623   struct dwarf2_section_info str;
624   struct dwarf2_section_info str_offsets;
625   /* In the case of a virtual DWO file, these two are unused.  */
626   struct dwarf2_section_info info;
627   VEC (dwarf2_section_info_def) *types;
628 };
629
630 /* CUs/TUs in DWP/DWO files.  */
631
632 struct dwo_unit
633 {
634   /* Backlink to the containing struct dwo_file.  */
635   struct dwo_file *dwo_file;
636
637   /* The "id" that distinguishes this CU/TU.
638      .debug_info calls this "dwo_id", .debug_types calls this "signature".
639      Since signatures came first, we stick with it for consistency.  */
640   ULONGEST signature;
641
642   /* The section this CU/TU lives in, in the DWO file.  */
643   struct dwarf2_section_info *section;
644
645   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
646   sect_offset sect_off;
647   unsigned int length;
648
649   /* For types, offset in the type's DIE of the type defined by this TU.  */
650   cu_offset type_offset_in_tu;
651 };
652
653 /* include/dwarf2.h defines the DWP section codes.
654    It defines a max value but it doesn't define a min value, which we
655    use for error checking, so provide one.  */
656
657 enum dwp_v2_section_ids
658 {
659   DW_SECT_MIN = 1
660 };
661
662 /* Data for one DWO file.
663
664    This includes virtual DWO files (a virtual DWO file is a DWO file as it
665    appears in a DWP file).  DWP files don't really have DWO files per se -
666    comdat folding of types "loses" the DWO file they came from, and from
667    a high level view DWP files appear to contain a mass of random types.
668    However, to maintain consistency with the non-DWP case we pretend DWP
669    files contain virtual DWO files, and we assign each TU with one virtual
670    DWO file (generally based on the line and abbrev section offsets -
671    a heuristic that seems to work in practice).  */
672
673 struct dwo_file
674 {
675   /* The DW_AT_GNU_dwo_name attribute.
676      For virtual DWO files the name is constructed from the section offsets
677      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
678      from related CU+TUs.  */
679   const char *dwo_name;
680
681   /* The DW_AT_comp_dir attribute.  */
682   const char *comp_dir;
683
684   /* The bfd, when the file is open.  Otherwise this is NULL.
685      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
686   bfd *dbfd;
687
688   /* The sections that make up this DWO file.
689      Remember that for virtual DWO files in DWP V2, these are virtual
690      sections (for lack of a better name).  */
691   struct dwo_sections sections;
692
693   /* The CUs in the file.
694      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
695      an extension to handle LLVM's Link Time Optimization output (where
696      multiple source files may be compiled into a single object/dwo pair). */
697   htab_t cus;
698
699   /* Table of TUs in the file.
700      Each element is a struct dwo_unit.  */
701   htab_t tus;
702 };
703
704 /* These sections are what may appear in a DWP file.  */
705
706 struct dwp_sections
707 {
708   /* These are used by both DWP version 1 and 2.  */
709   struct dwarf2_section_info str;
710   struct dwarf2_section_info cu_index;
711   struct dwarf2_section_info tu_index;
712
713   /* These are only used by DWP version 2 files.
714      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
715      sections are referenced by section number, and are not recorded here.
716      In DWP version 2 there is at most one copy of all these sections, each
717      section being (effectively) comprised of the concatenation of all of the
718      individual sections that exist in the version 1 format.
719      To keep the code simple we treat each of these concatenated pieces as a
720      section itself (a virtual section?).  */
721   struct dwarf2_section_info abbrev;
722   struct dwarf2_section_info info;
723   struct dwarf2_section_info line;
724   struct dwarf2_section_info loc;
725   struct dwarf2_section_info macinfo;
726   struct dwarf2_section_info macro;
727   struct dwarf2_section_info str_offsets;
728   struct dwarf2_section_info types;
729 };
730
731 /* These sections are what may appear in a virtual DWO file in DWP version 1.
732    A virtual DWO file is a DWO file as it appears in a DWP file.  */
733
734 struct virtual_v1_dwo_sections
735 {
736   struct dwarf2_section_info abbrev;
737   struct dwarf2_section_info line;
738   struct dwarf2_section_info loc;
739   struct dwarf2_section_info macinfo;
740   struct dwarf2_section_info macro;
741   struct dwarf2_section_info str_offsets;
742   /* Each DWP hash table entry records one CU or one TU.
743      That is recorded here, and copied to dwo_unit.section.  */
744   struct dwarf2_section_info info_or_types;
745 };
746
747 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
748    In version 2, the sections of the DWO files are concatenated together
749    and stored in one section of that name.  Thus each ELF section contains
750    several "virtual" sections.  */
751
752 struct virtual_v2_dwo_sections
753 {
754   bfd_size_type abbrev_offset;
755   bfd_size_type abbrev_size;
756
757   bfd_size_type line_offset;
758   bfd_size_type line_size;
759
760   bfd_size_type loc_offset;
761   bfd_size_type loc_size;
762
763   bfd_size_type macinfo_offset;
764   bfd_size_type macinfo_size;
765
766   bfd_size_type macro_offset;
767   bfd_size_type macro_size;
768
769   bfd_size_type str_offsets_offset;
770   bfd_size_type str_offsets_size;
771
772   /* Each DWP hash table entry records one CU or one TU.
773      That is recorded here, and copied to dwo_unit.section.  */
774   bfd_size_type info_or_types_offset;
775   bfd_size_type info_or_types_size;
776 };
777
778 /* Contents of DWP hash tables.  */
779
780 struct dwp_hash_table
781 {
782   uint32_t version, nr_columns;
783   uint32_t nr_units, nr_slots;
784   const gdb_byte *hash_table, *unit_table;
785   union
786   {
787     struct
788     {
789       const gdb_byte *indices;
790     } v1;
791     struct
792     {
793       /* This is indexed by column number and gives the id of the section
794          in that column.  */
795 #define MAX_NR_V2_DWO_SECTIONS \
796   (1 /* .debug_info or .debug_types */ \
797    + 1 /* .debug_abbrev */ \
798    + 1 /* .debug_line */ \
799    + 1 /* .debug_loc */ \
800    + 1 /* .debug_str_offsets */ \
801    + 1 /* .debug_macro or .debug_macinfo */)
802       int section_ids[MAX_NR_V2_DWO_SECTIONS];
803       const gdb_byte *offsets;
804       const gdb_byte *sizes;
805     } v2;
806   } section_pool;
807 };
808
809 /* Data for one DWP file.  */
810
811 struct dwp_file
812 {
813   dwp_file (const char *name_, gdb_bfd_ref_ptr &&abfd)
814     : name (name_),
815       dbfd (std::move (abfd))
816   {
817   }
818
819   /* Name of the file.  */
820   const char *name;
821
822   /* File format version.  */
823   int version = 0;
824
825   /* The bfd.  */
826   gdb_bfd_ref_ptr dbfd;
827
828   /* Section info for this file.  */
829   struct dwp_sections sections {};
830
831   /* Table of CUs in the file.  */
832   const struct dwp_hash_table *cus = nullptr;
833
834   /* Table of TUs in the file.  */
835   const struct dwp_hash_table *tus = nullptr;
836
837   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
838   htab_t loaded_cus {};
839   htab_t loaded_tus {};
840
841   /* Table to map ELF section numbers to their sections.
842      This is only needed for the DWP V1 file format.  */
843   unsigned int num_sections = 0;
844   asection **elf_sections = nullptr;
845 };
846
847 /* This represents a '.dwz' file.  */
848
849 struct dwz_file
850 {
851   dwz_file (gdb_bfd_ref_ptr &&bfd)
852     : dwz_bfd (std::move (bfd))
853   {
854   }
855
856   /* A dwz file can only contain a few sections.  */
857   struct dwarf2_section_info abbrev {};
858   struct dwarf2_section_info info {};
859   struct dwarf2_section_info str {};
860   struct dwarf2_section_info line {};
861   struct dwarf2_section_info macro {};
862   struct dwarf2_section_info gdb_index {};
863   struct dwarf2_section_info debug_names {};
864
865   /* The dwz's BFD.  */
866   gdb_bfd_ref_ptr dwz_bfd;
867 };
868
869 /* Struct used to pass misc. parameters to read_die_and_children, et
870    al.  which are used for both .debug_info and .debug_types dies.
871    All parameters here are unchanging for the life of the call.  This
872    struct exists to abstract away the constant parameters of die reading.  */
873
874 struct die_reader_specs
875 {
876   /* The bfd of die_section.  */
877   bfd* abfd;
878
879   /* The CU of the DIE we are parsing.  */
880   struct dwarf2_cu *cu;
881
882   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
883   struct dwo_file *dwo_file;
884
885   /* The section the die comes from.
886      This is either .debug_info or .debug_types, or the .dwo variants.  */
887   struct dwarf2_section_info *die_section;
888
889   /* die_section->buffer.  */
890   const gdb_byte *buffer;
891
892   /* The end of the buffer.  */
893   const gdb_byte *buffer_end;
894
895   /* The value of the DW_AT_comp_dir attribute.  */
896   const char *comp_dir;
897
898   /* The abbreviation table to use when reading the DIEs.  */
899   struct abbrev_table *abbrev_table;
900 };
901
902 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
903 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
904                                       const gdb_byte *info_ptr,
905                                       struct die_info *comp_unit_die,
906                                       int has_children,
907                                       void *data);
908
909 /* A 1-based directory index.  This is a strong typedef to prevent
910    accidentally using a directory index as a 0-based index into an
911    array/vector.  */
912 enum class dir_index : unsigned int {};
913
914 /* Likewise, a 1-based file name index.  */
915 enum class file_name_index : unsigned int {};
916
917 struct file_entry
918 {
919   file_entry () = default;
920
921   file_entry (const char *name_, dir_index d_index_,
922               unsigned int mod_time_, unsigned int length_)
923     : name (name_),
924       d_index (d_index_),
925       mod_time (mod_time_),
926       length (length_)
927   {}
928
929   /* Return the include directory at D_INDEX stored in LH.  Returns
930      NULL if D_INDEX is out of bounds.  */
931   const char *include_dir (const line_header *lh) const;
932
933   /* The file name.  Note this is an observing pointer.  The memory is
934      owned by debug_line_buffer.  */
935   const char *name {};
936
937   /* The directory index (1-based).  */
938   dir_index d_index {};
939
940   unsigned int mod_time {};
941
942   unsigned int length {};
943
944   /* True if referenced by the Line Number Program.  */
945   bool included_p {};
946
947   /* The associated symbol table, if any.  */
948   struct symtab *symtab {};
949 };
950
951 /* The line number information for a compilation unit (found in the
952    .debug_line section) begins with a "statement program header",
953    which contains the following information.  */
954 struct line_header
955 {
956   line_header ()
957     : offset_in_dwz {}
958   {}
959
960   /* Add an entry to the include directory table.  */
961   void add_include_dir (const char *include_dir);
962
963   /* Add an entry to the file name table.  */
964   void add_file_name (const char *name, dir_index d_index,
965                       unsigned int mod_time, unsigned int length);
966
967   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
968      is out of bounds.  */
969   const char *include_dir_at (dir_index index) const
970   {
971     /* Convert directory index number (1-based) to vector index
972        (0-based).  */
973     size_t vec_index = to_underlying (index) - 1;
974
975     if (vec_index >= include_dirs.size ())
976       return NULL;
977     return include_dirs[vec_index];
978   }
979
980   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
981      is out of bounds.  */
982   file_entry *file_name_at (file_name_index index)
983   {
984     /* Convert file name index number (1-based) to vector index
985        (0-based).  */
986     size_t vec_index = to_underlying (index) - 1;
987
988     if (vec_index >= file_names.size ())
989       return NULL;
990     return &file_names[vec_index];
991   }
992
993   /* Const version of the above.  */
994   const file_entry *file_name_at (unsigned int index) const
995   {
996     if (index >= file_names.size ())
997       return NULL;
998     return &file_names[index];
999   }
1000
1001   /* Offset of line number information in .debug_line section.  */
1002   sect_offset sect_off {};
1003
1004   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1005   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1006
1007   unsigned int total_length {};
1008   unsigned short version {};
1009   unsigned int header_length {};
1010   unsigned char minimum_instruction_length {};
1011   unsigned char maximum_ops_per_instruction {};
1012   unsigned char default_is_stmt {};
1013   int line_base {};
1014   unsigned char line_range {};
1015   unsigned char opcode_base {};
1016
1017   /* standard_opcode_lengths[i] is the number of operands for the
1018      standard opcode whose value is i.  This means that
1019      standard_opcode_lengths[0] is unused, and the last meaningful
1020      element is standard_opcode_lengths[opcode_base - 1].  */
1021   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1022
1023   /* The include_directories table.  Note these are observing
1024      pointers.  The memory is owned by debug_line_buffer.  */
1025   std::vector<const char *> include_dirs;
1026
1027   /* The file_names table.  */
1028   std::vector<file_entry> file_names;
1029
1030   /* The start and end of the statement program following this
1031      header.  These point into dwarf2_per_objfile->line_buffer.  */
1032   const gdb_byte *statement_program_start {}, *statement_program_end {};
1033 };
1034
1035 typedef std::unique_ptr<line_header> line_header_up;
1036
1037 const char *
1038 file_entry::include_dir (const line_header *lh) const
1039 {
1040   return lh->include_dir_at (d_index);
1041 }
1042
1043 /* When we construct a partial symbol table entry we only
1044    need this much information.  */
1045 struct partial_die_info : public allocate_on_obstack
1046   {
1047     partial_die_info (sect_offset sect_off, struct abbrev_info *abbrev);
1048
1049     /* Disable assign but still keep copy ctor, which is needed
1050        load_partial_dies.   */
1051     partial_die_info& operator=(const partial_die_info& rhs) = delete;
1052
1053     /* Adjust the partial die before generating a symbol for it.  This
1054        function may set the is_external flag or change the DIE's
1055        name.  */
1056     void fixup (struct dwarf2_cu *cu);
1057
1058     /* Read a minimal amount of information into the minimal die
1059        structure.  */
1060     const gdb_byte *read (const struct die_reader_specs *reader,
1061                           const struct abbrev_info &abbrev,
1062                           const gdb_byte *info_ptr);
1063
1064     /* Offset of this DIE.  */
1065     const sect_offset sect_off;
1066
1067     /* DWARF-2 tag for this DIE.  */
1068     const ENUM_BITFIELD(dwarf_tag) tag : 16;
1069
1070     /* Assorted flags describing the data found in this DIE.  */
1071     const unsigned int has_children : 1;
1072
1073     unsigned int is_external : 1;
1074     unsigned int is_declaration : 1;
1075     unsigned int has_type : 1;
1076     unsigned int has_specification : 1;
1077     unsigned int has_pc_info : 1;
1078     unsigned int may_be_inlined : 1;
1079
1080     /* This DIE has been marked DW_AT_main_subprogram.  */
1081     unsigned int main_subprogram : 1;
1082
1083     /* Flag set if the SCOPE field of this structure has been
1084        computed.  */
1085     unsigned int scope_set : 1;
1086
1087     /* Flag set if the DIE has a byte_size attribute.  */
1088     unsigned int has_byte_size : 1;
1089
1090     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1091     unsigned int has_const_value : 1;
1092
1093     /* Flag set if any of the DIE's children are template arguments.  */
1094     unsigned int has_template_arguments : 1;
1095
1096     /* Flag set if fixup has been called on this die.  */
1097     unsigned int fixup_called : 1;
1098
1099     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1100     unsigned int is_dwz : 1;
1101
1102     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1103     unsigned int spec_is_dwz : 1;
1104
1105     /* The name of this DIE.  Normally the value of DW_AT_name, but
1106        sometimes a default name for unnamed DIEs.  */
1107     const char *name = nullptr;
1108
1109     /* The linkage name, if present.  */
1110     const char *linkage_name = nullptr;
1111
1112     /* The scope to prepend to our children.  This is generally
1113        allocated on the comp_unit_obstack, so will disappear
1114        when this compilation unit leaves the cache.  */
1115     const char *scope = nullptr;
1116
1117     /* Some data associated with the partial DIE.  The tag determines
1118        which field is live.  */
1119     union
1120     {
1121       /* The location description associated with this DIE, if any.  */
1122       struct dwarf_block *locdesc;
1123       /* The offset of an import, for DW_TAG_imported_unit.  */
1124       sect_offset sect_off;
1125     } d {};
1126
1127     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1128     CORE_ADDR lowpc = 0;
1129     CORE_ADDR highpc = 0;
1130
1131     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1132        DW_AT_sibling, if any.  */
1133     /* NOTE: This member isn't strictly necessary, partial_die_info::read
1134        could return DW_AT_sibling values to its caller load_partial_dies.  */
1135     const gdb_byte *sibling = nullptr;
1136
1137     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1138        DW_AT_specification (or DW_AT_abstract_origin or
1139        DW_AT_extension).  */
1140     sect_offset spec_offset {};
1141
1142     /* Pointers to this DIE's parent, first child, and next sibling,
1143        if any.  */
1144     struct partial_die_info *die_parent = nullptr;
1145     struct partial_die_info *die_child = nullptr;
1146     struct partial_die_info *die_sibling = nullptr;
1147
1148     friend struct partial_die_info *
1149     dwarf2_cu::find_partial_die (sect_offset sect_off);
1150
1151   private:
1152     /* Only need to do look up in dwarf2_cu::find_partial_die.  */
1153     partial_die_info (sect_offset sect_off)
1154       : partial_die_info (sect_off, DW_TAG_padding, 0)
1155     {
1156     }
1157
1158     partial_die_info (sect_offset sect_off_, enum dwarf_tag tag_,
1159                       int has_children_)
1160       : sect_off (sect_off_), tag (tag_), has_children (has_children_)
1161     {
1162       is_external = 0;
1163       is_declaration = 0;
1164       has_type = 0;
1165       has_specification = 0;
1166       has_pc_info = 0;
1167       may_be_inlined = 0;
1168       main_subprogram = 0;
1169       scope_set = 0;
1170       has_byte_size = 0;
1171       has_const_value = 0;
1172       has_template_arguments = 0;
1173       fixup_called = 0;
1174       is_dwz = 0;
1175       spec_is_dwz = 0;
1176     }
1177   };
1178
1179 /* This data structure holds the information of an abbrev.  */
1180 struct abbrev_info
1181   {
1182     unsigned int number;        /* number identifying abbrev */
1183     enum dwarf_tag tag;         /* dwarf tag */
1184     unsigned short has_children;                /* boolean */
1185     unsigned short num_attrs;   /* number of attributes */
1186     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1187     struct abbrev_info *next;   /* next in chain */
1188   };
1189
1190 struct attr_abbrev
1191   {
1192     ENUM_BITFIELD(dwarf_attribute) name : 16;
1193     ENUM_BITFIELD(dwarf_form) form : 16;
1194
1195     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1196     LONGEST implicit_const;
1197   };
1198
1199 /* Size of abbrev_table.abbrev_hash_table.  */
1200 #define ABBREV_HASH_SIZE 121
1201
1202 /* Top level data structure to contain an abbreviation table.  */
1203
1204 struct abbrev_table
1205 {
1206   explicit abbrev_table (sect_offset off)
1207     : sect_off (off)
1208   {
1209     m_abbrevs =
1210       XOBNEWVEC (&abbrev_obstack, struct abbrev_info *, ABBREV_HASH_SIZE);
1211     memset (m_abbrevs, 0, ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
1212   }
1213
1214   DISABLE_COPY_AND_ASSIGN (abbrev_table);
1215
1216   /* Allocate space for a struct abbrev_info object in
1217      ABBREV_TABLE.  */
1218   struct abbrev_info *alloc_abbrev ();
1219
1220   /* Add an abbreviation to the table.  */
1221   void add_abbrev (unsigned int abbrev_number, struct abbrev_info *abbrev);
1222
1223   /* Look up an abbrev in the table.
1224      Returns NULL if the abbrev is not found.  */
1225
1226   struct abbrev_info *lookup_abbrev (unsigned int abbrev_number);
1227
1228
1229   /* Where the abbrev table came from.
1230      This is used as a sanity check when the table is used.  */
1231   const sect_offset sect_off;
1232
1233   /* Storage for the abbrev table.  */
1234   auto_obstack abbrev_obstack;
1235
1236 private:
1237
1238   /* Hash table of abbrevs.
1239      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1240      It could be statically allocated, but the previous code didn't so we
1241      don't either.  */
1242   struct abbrev_info **m_abbrevs;
1243 };
1244
1245 typedef std::unique_ptr<struct abbrev_table> abbrev_table_up;
1246
1247 /* Attributes have a name and a value.  */
1248 struct attribute
1249   {
1250     ENUM_BITFIELD(dwarf_attribute) name : 16;
1251     ENUM_BITFIELD(dwarf_form) form : 15;
1252
1253     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1254        field should be in u.str (existing only for DW_STRING) but it is kept
1255        here for better struct attribute alignment.  */
1256     unsigned int string_is_canonical : 1;
1257
1258     union
1259       {
1260         const char *str;
1261         struct dwarf_block *blk;
1262         ULONGEST unsnd;
1263         LONGEST snd;
1264         CORE_ADDR addr;
1265         ULONGEST signature;
1266       }
1267     u;
1268   };
1269
1270 /* This data structure holds a complete die structure.  */
1271 struct die_info
1272   {
1273     /* DWARF-2 tag for this DIE.  */
1274     ENUM_BITFIELD(dwarf_tag) tag : 16;
1275
1276     /* Number of attributes */
1277     unsigned char num_attrs;
1278
1279     /* True if we're presently building the full type name for the
1280        type derived from this DIE.  */
1281     unsigned char building_fullname : 1;
1282
1283     /* True if this die is in process.  PR 16581.  */
1284     unsigned char in_process : 1;
1285
1286     /* Abbrev number */
1287     unsigned int abbrev;
1288
1289     /* Offset in .debug_info or .debug_types section.  */
1290     sect_offset sect_off;
1291
1292     /* The dies in a compilation unit form an n-ary tree.  PARENT
1293        points to this die's parent; CHILD points to the first child of
1294        this node; and all the children of a given node are chained
1295        together via their SIBLING fields.  */
1296     struct die_info *child;     /* Its first child, if any.  */
1297     struct die_info *sibling;   /* Its next sibling, if any.  */
1298     struct die_info *parent;    /* Its parent, if any.  */
1299
1300     /* An array of attributes, with NUM_ATTRS elements.  There may be
1301        zero, but it's not common and zero-sized arrays are not
1302        sufficiently portable C.  */
1303     struct attribute attrs[1];
1304   };
1305
1306 /* Get at parts of an attribute structure.  */
1307
1308 #define DW_STRING(attr)    ((attr)->u.str)
1309 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1310 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1311 #define DW_BLOCK(attr)     ((attr)->u.blk)
1312 #define DW_SND(attr)       ((attr)->u.snd)
1313 #define DW_ADDR(attr)      ((attr)->u.addr)
1314 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1315
1316 /* Blocks are a bunch of untyped bytes.  */
1317 struct dwarf_block
1318   {
1319     size_t size;
1320
1321     /* Valid only if SIZE is not zero.  */
1322     const gdb_byte *data;
1323   };
1324
1325 #ifndef ATTR_ALLOC_CHUNK
1326 #define ATTR_ALLOC_CHUNK 4
1327 #endif
1328
1329 /* Allocate fields for structs, unions and enums in this size.  */
1330 #ifndef DW_FIELD_ALLOC_CHUNK
1331 #define DW_FIELD_ALLOC_CHUNK 4
1332 #endif
1333
1334 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1335    but this would require a corresponding change in unpack_field_as_long
1336    and friends.  */
1337 static int bits_per_byte = 8;
1338
1339 /* When reading a variant or variant part, we track a bit more
1340    information about the field, and store it in an object of this
1341    type.  */
1342
1343 struct variant_field
1344 {
1345   /* If we see a DW_TAG_variant, then this will be the discriminant
1346      value.  */
1347   ULONGEST discriminant_value;
1348   /* If we see a DW_TAG_variant, then this will be set if this is the
1349      default branch.  */
1350   bool default_branch;
1351   /* While reading a DW_TAG_variant_part, this will be set if this
1352      field is the discriminant.  */
1353   bool is_discriminant;
1354 };
1355
1356 struct nextfield
1357 {
1358   int accessibility = 0;
1359   int virtuality = 0;
1360   /* Extra information to describe a variant or variant part.  */
1361   struct variant_field variant {};
1362   struct field field {};
1363 };
1364
1365 struct fnfieldlist
1366 {
1367   const char *name = nullptr;
1368   std::vector<struct fn_field> fnfields;
1369 };
1370
1371 /* The routines that read and process dies for a C struct or C++ class
1372    pass lists of data member fields and lists of member function fields
1373    in an instance of a field_info structure, as defined below.  */
1374 struct field_info
1375   {
1376     /* List of data member and baseclasses fields.  */
1377     std::vector<struct nextfield> fields;
1378     std::vector<struct nextfield> baseclasses;
1379
1380     /* Number of fields (including baseclasses).  */
1381     int nfields = 0;
1382
1383     /* Set if the accesibility of one of the fields is not public.  */
1384     int non_public_fields = 0;
1385
1386     /* Member function fieldlist array, contains name of possibly overloaded
1387        member function, number of overloaded member functions and a pointer
1388        to the head of the member function field chain.  */
1389     std::vector<struct fnfieldlist> fnfieldlists;
1390
1391     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1392        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1393     std::vector<struct decl_field> typedef_field_list;
1394
1395     /* Nested types defined by this class and the number of elements in this
1396        list.  */
1397     std::vector<struct decl_field> nested_types_list;
1398   };
1399
1400 /* One item on the queue of compilation units to read in full symbols
1401    for.  */
1402 struct dwarf2_queue_item
1403 {
1404   struct dwarf2_per_cu_data *per_cu;
1405   enum language pretend_language;
1406   struct dwarf2_queue_item *next;
1407 };
1408
1409 /* The current queue.  */
1410 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1411
1412 /* Loaded secondary compilation units are kept in memory until they
1413    have not been referenced for the processing of this many
1414    compilation units.  Set this to zero to disable caching.  Cache
1415    sizes of up to at least twenty will improve startup time for
1416    typical inter-CU-reference binaries, at an obvious memory cost.  */
1417 static int dwarf_max_cache_age = 5;
1418 static void
1419 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1420                           struct cmd_list_element *c, const char *value)
1421 {
1422   fprintf_filtered (file, _("The upper bound on the age of cached "
1423                             "DWARF compilation units is %s.\n"),
1424                     value);
1425 }
1426 \f
1427 /* local function prototypes */
1428
1429 static const char *get_section_name (const struct dwarf2_section_info *);
1430
1431 static const char *get_section_file_name (const struct dwarf2_section_info *);
1432
1433 static void dwarf2_find_base_address (struct die_info *die,
1434                                       struct dwarf2_cu *cu);
1435
1436 static struct partial_symtab *create_partial_symtab
1437   (struct dwarf2_per_cu_data *per_cu, const char *name);
1438
1439 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1440                                         const gdb_byte *info_ptr,
1441                                         struct die_info *type_unit_die,
1442                                         int has_children, void *data);
1443
1444 static void dwarf2_build_psymtabs_hard
1445   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1446
1447 static void scan_partial_symbols (struct partial_die_info *,
1448                                   CORE_ADDR *, CORE_ADDR *,
1449                                   int, struct dwarf2_cu *);
1450
1451 static void add_partial_symbol (struct partial_die_info *,
1452                                 struct dwarf2_cu *);
1453
1454 static void add_partial_namespace (struct partial_die_info *pdi,
1455                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1456                                    int set_addrmap, struct dwarf2_cu *cu);
1457
1458 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1459                                 CORE_ADDR *highpc, int set_addrmap,
1460                                 struct dwarf2_cu *cu);
1461
1462 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1463                                      struct dwarf2_cu *cu);
1464
1465 static void add_partial_subprogram (struct partial_die_info *pdi,
1466                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1467                                     int need_pc, struct dwarf2_cu *cu);
1468
1469 static void dwarf2_read_symtab (struct partial_symtab *,
1470                                 struct objfile *);
1471
1472 static void psymtab_to_symtab_1 (struct partial_symtab *);
1473
1474 static abbrev_table_up abbrev_table_read_table
1475   (struct dwarf2_per_objfile *dwarf2_per_objfile, struct dwarf2_section_info *,
1476    sect_offset);
1477
1478 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1479
1480 static struct partial_die_info *load_partial_dies
1481   (const struct die_reader_specs *, const gdb_byte *, int);
1482
1483 static struct partial_die_info *find_partial_die (sect_offset, int,
1484                                                   struct dwarf2_cu *);
1485
1486 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1487                                        struct attribute *, struct attr_abbrev *,
1488                                        const gdb_byte *);
1489
1490 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1491
1492 static int read_1_signed_byte (bfd *, const gdb_byte *);
1493
1494 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1495
1496 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1497
1498 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1499
1500 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1501                                unsigned int *);
1502
1503 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1504
1505 static LONGEST read_checked_initial_length_and_offset
1506   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1507    unsigned int *, unsigned int *);
1508
1509 static LONGEST read_offset (bfd *, const gdb_byte *,
1510                             const struct comp_unit_head *,
1511                             unsigned int *);
1512
1513 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1514
1515 static sect_offset read_abbrev_offset
1516   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1517    struct dwarf2_section_info *, sect_offset);
1518
1519 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1520
1521 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1522
1523 static const char *read_indirect_string
1524   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1525    const struct comp_unit_head *, unsigned int *);
1526
1527 static const char *read_indirect_line_string
1528   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *, const gdb_byte *,
1529    const struct comp_unit_head *, unsigned int *);
1530
1531 static const char *read_indirect_string_at_offset
1532   (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
1533    LONGEST str_offset);
1534
1535 static const char *read_indirect_string_from_dwz
1536   (struct objfile *objfile, struct dwz_file *, LONGEST);
1537
1538 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1539
1540 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1541                                               const gdb_byte *,
1542                                               unsigned int *);
1543
1544 static const char *read_str_index (const struct die_reader_specs *reader,
1545                                    ULONGEST str_index);
1546
1547 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1548
1549 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1550                                       struct dwarf2_cu *);
1551
1552 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1553                                                 unsigned int);
1554
1555 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1556                                        struct dwarf2_cu *cu);
1557
1558 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1559                                struct dwarf2_cu *cu);
1560
1561 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1562
1563 static struct die_info *die_specification (struct die_info *die,
1564                                            struct dwarf2_cu **);
1565
1566 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1567                                                 struct dwarf2_cu *cu);
1568
1569 static void dwarf_decode_lines (struct line_header *, const char *,
1570                                 struct dwarf2_cu *, struct partial_symtab *,
1571                                 CORE_ADDR, int decode_mapping);
1572
1573 static void dwarf2_start_subfile (const char *, const char *);
1574
1575 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1576                                                     const char *, const char *,
1577                                                     CORE_ADDR);
1578
1579 static struct symbol *new_symbol (struct die_info *, struct type *,
1580                                   struct dwarf2_cu *, struct symbol * = NULL);
1581
1582 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1583                                 struct dwarf2_cu *);
1584
1585 static void dwarf2_const_value_attr (const struct attribute *attr,
1586                                      struct type *type,
1587                                      const char *name,
1588                                      struct obstack *obstack,
1589                                      struct dwarf2_cu *cu, LONGEST *value,
1590                                      const gdb_byte **bytes,
1591                                      struct dwarf2_locexpr_baton **baton);
1592
1593 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1594
1595 static int need_gnat_info (struct dwarf2_cu *);
1596
1597 static struct type *die_descriptive_type (struct die_info *,
1598                                           struct dwarf2_cu *);
1599
1600 static void set_descriptive_type (struct type *, struct die_info *,
1601                                   struct dwarf2_cu *);
1602
1603 static struct type *die_containing_type (struct die_info *,
1604                                          struct dwarf2_cu *);
1605
1606 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1607                                      struct dwarf2_cu *);
1608
1609 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1610
1611 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1612
1613 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1614
1615 static char *typename_concat (struct obstack *obs, const char *prefix,
1616                               const char *suffix, int physname,
1617                               struct dwarf2_cu *cu);
1618
1619 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1620
1621 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1622
1623 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1624
1625 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1626
1627 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1628
1629 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1630
1631 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1632                                struct dwarf2_cu *, struct partial_symtab *);
1633
1634 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1635    values.  Keep the items ordered with increasing constraints compliance.  */
1636 enum pc_bounds_kind
1637 {
1638   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1639   PC_BOUNDS_NOT_PRESENT,
1640
1641   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1642      were present but they do not form a valid range of PC addresses.  */
1643   PC_BOUNDS_INVALID,
1644
1645   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1646   PC_BOUNDS_RANGES,
1647
1648   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1649   PC_BOUNDS_HIGH_LOW,
1650 };
1651
1652 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1653                                                  CORE_ADDR *, CORE_ADDR *,
1654                                                  struct dwarf2_cu *,
1655                                                  struct partial_symtab *);
1656
1657 static void get_scope_pc_bounds (struct die_info *,
1658                                  CORE_ADDR *, CORE_ADDR *,
1659                                  struct dwarf2_cu *);
1660
1661 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1662                                         CORE_ADDR, struct dwarf2_cu *);
1663
1664 static void dwarf2_add_field (struct field_info *, struct die_info *,
1665                               struct dwarf2_cu *);
1666
1667 static void dwarf2_attach_fields_to_type (struct field_info *,
1668                                           struct type *, struct dwarf2_cu *);
1669
1670 static void dwarf2_add_member_fn (struct field_info *,
1671                                   struct die_info *, struct type *,
1672                                   struct dwarf2_cu *);
1673
1674 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1675                                              struct type *,
1676                                              struct dwarf2_cu *);
1677
1678 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1679
1680 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1681
1682 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1683
1684 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1685
1686 static struct using_direct **using_directives (enum language);
1687
1688 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1689
1690 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1691
1692 static struct type *read_module_type (struct die_info *die,
1693                                       struct dwarf2_cu *cu);
1694
1695 static const char *namespace_name (struct die_info *die,
1696                                    int *is_anonymous, struct dwarf2_cu *);
1697
1698 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1699
1700 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1701
1702 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1703                                                        struct dwarf2_cu *);
1704
1705 static struct die_info *read_die_and_siblings_1
1706   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1707    struct die_info *);
1708
1709 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1710                                                const gdb_byte *info_ptr,
1711                                                const gdb_byte **new_info_ptr,
1712                                                struct die_info *parent);
1713
1714 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1715                                         struct die_info **, const gdb_byte *,
1716                                         int *, int);
1717
1718 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1719                                       struct die_info **, const gdb_byte *,
1720                                       int *);
1721
1722 static void process_die (struct die_info *, struct dwarf2_cu *);
1723
1724 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1725                                              struct obstack *);
1726
1727 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1728
1729 static const char *dwarf2_full_name (const char *name,
1730                                      struct die_info *die,
1731                                      struct dwarf2_cu *cu);
1732
1733 static const char *dwarf2_physname (const char *name, struct die_info *die,
1734                                     struct dwarf2_cu *cu);
1735
1736 static struct die_info *dwarf2_extension (struct die_info *die,
1737                                           struct dwarf2_cu **);
1738
1739 static const char *dwarf_tag_name (unsigned int);
1740
1741 static const char *dwarf_attr_name (unsigned int);
1742
1743 static const char *dwarf_form_name (unsigned int);
1744
1745 static const char *dwarf_bool_name (unsigned int);
1746
1747 static const char *dwarf_type_encoding_name (unsigned int);
1748
1749 static struct die_info *sibling_die (struct die_info *);
1750
1751 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1752
1753 static void dump_die_for_error (struct die_info *);
1754
1755 static void dump_die_1 (struct ui_file *, int level, int max_level,
1756                         struct die_info *);
1757
1758 /*static*/ void dump_die (struct die_info *, int max_level);
1759
1760 static void store_in_ref_table (struct die_info *,
1761                                 struct dwarf2_cu *);
1762
1763 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1764
1765 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1766
1767 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1768                                                const struct attribute *,
1769                                                struct dwarf2_cu **);
1770
1771 static struct die_info *follow_die_ref (struct die_info *,
1772                                         const struct attribute *,
1773                                         struct dwarf2_cu **);
1774
1775 static struct die_info *follow_die_sig (struct die_info *,
1776                                         const struct attribute *,
1777                                         struct dwarf2_cu **);
1778
1779 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1780                                          struct dwarf2_cu *);
1781
1782 static struct type *get_DW_AT_signature_type (struct die_info *,
1783                                               const struct attribute *,
1784                                               struct dwarf2_cu *);
1785
1786 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1787
1788 static void read_signatured_type (struct signatured_type *);
1789
1790 static int attr_to_dynamic_prop (const struct attribute *attr,
1791                                  struct die_info *die, struct dwarf2_cu *cu,
1792                                  struct dynamic_prop *prop);
1793
1794 /* memory allocation interface */
1795
1796 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1797
1798 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1799
1800 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1801
1802 static int attr_form_is_block (const struct attribute *);
1803
1804 static int attr_form_is_section_offset (const struct attribute *);
1805
1806 static int attr_form_is_constant (const struct attribute *);
1807
1808 static int attr_form_is_ref (const struct attribute *);
1809
1810 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1811                                    struct dwarf2_loclist_baton *baton,
1812                                    const struct attribute *attr);
1813
1814 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1815                                          struct symbol *sym,
1816                                          struct dwarf2_cu *cu,
1817                                          int is_block);
1818
1819 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1820                                      const gdb_byte *info_ptr,
1821                                      struct abbrev_info *abbrev);
1822
1823 static hashval_t partial_die_hash (const void *item);
1824
1825 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1826
1827 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1828   (sect_offset sect_off, unsigned int offset_in_dwz,
1829    struct dwarf2_per_objfile *dwarf2_per_objfile);
1830
1831 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1832                                    struct die_info *comp_unit_die,
1833                                    enum language pretend_language);
1834
1835 static void age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1836
1837 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1838
1839 static struct type *set_die_type (struct die_info *, struct type *,
1840                                   struct dwarf2_cu *);
1841
1842 static void create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1843
1844 static int create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile);
1845
1846 static void load_full_comp_unit (struct dwarf2_per_cu_data *, bool,
1847                                  enum language);
1848
1849 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1850                                     enum language);
1851
1852 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1853                                     enum language);
1854
1855 static void dwarf2_add_dependence (struct dwarf2_cu *,
1856                                    struct dwarf2_per_cu_data *);
1857
1858 static void dwarf2_mark (struct dwarf2_cu *);
1859
1860 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1861
1862 static struct type *get_die_type_at_offset (sect_offset,
1863                                             struct dwarf2_per_cu_data *);
1864
1865 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1866
1867 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1868                              enum language pretend_language);
1869
1870 static void process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile);
1871
1872 /* Class, the destructor of which frees all allocated queue entries.  This
1873    will only have work to do if an error was thrown while processing the
1874    dwarf.  If no error was thrown then the queue entries should have all
1875    been processed, and freed, as we went along.  */
1876
1877 class dwarf2_queue_guard
1878 {
1879 public:
1880   dwarf2_queue_guard () = default;
1881
1882   /* Free any entries remaining on the queue.  There should only be
1883      entries left if we hit an error while processing the dwarf.  */
1884   ~dwarf2_queue_guard ()
1885   {
1886     struct dwarf2_queue_item *item, *last;
1887
1888     item = dwarf2_queue;
1889     while (item)
1890       {
1891         /* Anything still marked queued is likely to be in an
1892            inconsistent state, so discard it.  */
1893         if (item->per_cu->queued)
1894           {
1895             if (item->per_cu->cu != NULL)
1896               free_one_cached_comp_unit (item->per_cu);
1897             item->per_cu->queued = 0;
1898           }
1899
1900         last = item;
1901         item = item->next;
1902         xfree (last);
1903       }
1904
1905     dwarf2_queue = dwarf2_queue_tail = NULL;
1906   }
1907 };
1908
1909 /* The return type of find_file_and_directory.  Note, the enclosed
1910    string pointers are only valid while this object is valid.  */
1911
1912 struct file_and_directory
1913 {
1914   /* The filename.  This is never NULL.  */
1915   const char *name;
1916
1917   /* The compilation directory.  NULL if not known.  If we needed to
1918      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
1919      points directly to the DW_AT_comp_dir string attribute owned by
1920      the obstack that owns the DIE.  */
1921   const char *comp_dir;
1922
1923   /* If we needed to build a new string for comp_dir, this is what
1924      owns the storage.  */
1925   std::string comp_dir_storage;
1926 };
1927
1928 static file_and_directory find_file_and_directory (struct die_info *die,
1929                                                    struct dwarf2_cu *cu);
1930
1931 static char *file_full_name (int file, struct line_header *lh,
1932                              const char *comp_dir);
1933
1934 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
1935 enum class rcuh_kind { COMPILE, TYPE };
1936
1937 static const gdb_byte *read_and_check_comp_unit_head
1938   (struct dwarf2_per_objfile* dwarf2_per_objfile,
1939    struct comp_unit_head *header,
1940    struct dwarf2_section_info *section,
1941    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
1942    rcuh_kind section_kind);
1943
1944 static void init_cutu_and_read_dies
1945   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
1946    int use_existing_cu, int keep, bool skip_partial,
1947    die_reader_func_ftype *die_reader_func, void *data);
1948
1949 static void init_cutu_and_read_dies_simple
1950   (struct dwarf2_per_cu_data *this_cu,
1951    die_reader_func_ftype *die_reader_func, void *data);
1952
1953 static htab_t allocate_signatured_type_table (struct objfile *objfile);
1954
1955 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
1956
1957 static struct dwo_unit *lookup_dwo_unit_in_dwp
1958   (struct dwarf2_per_objfile *dwarf2_per_objfile,
1959    struct dwp_file *dwp_file, const char *comp_dir,
1960    ULONGEST signature, int is_debug_types);
1961
1962 static struct dwp_file *get_dwp_file
1963   (struct dwarf2_per_objfile *dwarf2_per_objfile);
1964
1965 static struct dwo_unit *lookup_dwo_comp_unit
1966   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
1967
1968 static struct dwo_unit *lookup_dwo_type_unit
1969   (struct signatured_type *, const char *, const char *);
1970
1971 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
1972
1973 static void free_dwo_file (struct dwo_file *);
1974
1975 /* A unique_ptr helper to free a dwo_file.  */
1976
1977 struct dwo_file_deleter
1978 {
1979   void operator() (struct dwo_file *df) const
1980   {
1981     free_dwo_file (df);
1982   }
1983 };
1984
1985 /* A unique pointer to a dwo_file.  */
1986
1987 typedef std::unique_ptr<struct dwo_file, dwo_file_deleter> dwo_file_up;
1988
1989 static void process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile);
1990
1991 static void check_producer (struct dwarf2_cu *cu);
1992
1993 static void free_line_header_voidp (void *arg);
1994 \f
1995 /* Various complaints about symbol reading that don't abort the process.  */
1996
1997 static void
1998 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
1999 {
2000   complaint (_("statement list doesn't fit in .debug_line section"));
2001 }
2002
2003 static void
2004 dwarf2_debug_line_missing_file_complaint (void)
2005 {
2006   complaint (_(".debug_line section has line data without a file"));
2007 }
2008
2009 static void
2010 dwarf2_debug_line_missing_end_sequence_complaint (void)
2011 {
2012   complaint (_(".debug_line section has line "
2013                "program sequence without an end"));
2014 }
2015
2016 static void
2017 dwarf2_complex_location_expr_complaint (void)
2018 {
2019   complaint (_("location expression too complex"));
2020 }
2021
2022 static void
2023 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2024                                               int arg3)
2025 {
2026   complaint (_("const value length mismatch for '%s', got %d, expected %d"),
2027              arg1, arg2, arg3);
2028 }
2029
2030 static void
2031 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2032 {
2033   complaint (_("debug info runs off end of %s section"
2034                " [in module %s]"),
2035              get_section_name (section),
2036              get_section_file_name (section));
2037 }
2038
2039 static void
2040 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2041 {
2042   complaint (_("macro debug info contains a "
2043                "malformed macro definition:\n`%s'"),
2044              arg1);
2045 }
2046
2047 static void
2048 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2049 {
2050   complaint (_("invalid attribute class or form for '%s' in '%s'"),
2051              arg1, arg2);
2052 }
2053
2054 /* Hash function for line_header_hash.  */
2055
2056 static hashval_t
2057 line_header_hash (const struct line_header *ofs)
2058 {
2059   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2060 }
2061
2062 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2063
2064 static hashval_t
2065 line_header_hash_voidp (const void *item)
2066 {
2067   const struct line_header *ofs = (const struct line_header *) item;
2068
2069   return line_header_hash (ofs);
2070 }
2071
2072 /* Equality function for line_header_hash.  */
2073
2074 static int
2075 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2076 {
2077   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2078   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2079
2080   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2081           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2082 }
2083
2084 \f
2085
2086 /* Read the given attribute value as an address, taking the attribute's
2087    form into account.  */
2088
2089 static CORE_ADDR
2090 attr_value_as_address (struct attribute *attr)
2091 {
2092   CORE_ADDR addr;
2093
2094   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2095     {
2096       /* Aside from a few clearly defined exceptions, attributes that
2097          contain an address must always be in DW_FORM_addr form.
2098          Unfortunately, some compilers happen to be violating this
2099          requirement by encoding addresses using other forms, such
2100          as DW_FORM_data4 for example.  For those broken compilers,
2101          we try to do our best, without any guarantee of success,
2102          to interpret the address correctly.  It would also be nice
2103          to generate a complaint, but that would require us to maintain
2104          a list of legitimate cases where a non-address form is allowed,
2105          as well as update callers to pass in at least the CU's DWARF
2106          version.  This is more overhead than what we're willing to
2107          expand for a pretty rare case.  */
2108       addr = DW_UNSND (attr);
2109     }
2110   else
2111     addr = DW_ADDR (attr);
2112
2113   return addr;
2114 }
2115
2116 /* See declaration.  */
2117
2118 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2119                                         const dwarf2_debug_sections *names)
2120   : objfile (objfile_)
2121 {
2122   if (names == NULL)
2123     names = &dwarf2_elf_names;
2124
2125   bfd *obfd = objfile->obfd;
2126
2127   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2128     locate_sections (obfd, sec, *names);
2129 }
2130
2131 static void free_dwo_files (htab_t dwo_files, struct objfile *objfile);
2132
2133 dwarf2_per_objfile::~dwarf2_per_objfile ()
2134 {
2135   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2136   free_cached_comp_units ();
2137
2138   if (quick_file_names_table)
2139     htab_delete (quick_file_names_table);
2140
2141   if (line_header_hash)
2142     htab_delete (line_header_hash);
2143
2144   for (dwarf2_per_cu_data *per_cu : all_comp_units)
2145     VEC_free (dwarf2_per_cu_ptr, per_cu->imported_symtabs);
2146
2147   for (signatured_type *sig_type : all_type_units)
2148     VEC_free (dwarf2_per_cu_ptr, sig_type->per_cu.imported_symtabs);
2149
2150   VEC_free (dwarf2_section_info_def, types);
2151
2152   if (dwo_files != NULL)
2153     free_dwo_files (dwo_files, objfile);
2154
2155   /* Everything else should be on the objfile obstack.  */
2156 }
2157
2158 /* See declaration.  */
2159
2160 void
2161 dwarf2_per_objfile::free_cached_comp_units ()
2162 {
2163   dwarf2_per_cu_data *per_cu = read_in_chain;
2164   dwarf2_per_cu_data **last_chain = &read_in_chain;
2165   while (per_cu != NULL)
2166     {
2167       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2168
2169       delete per_cu->cu;
2170       *last_chain = next_cu;
2171       per_cu = next_cu;
2172     }
2173 }
2174
2175 /* A helper class that calls free_cached_comp_units on
2176    destruction.  */
2177
2178 class free_cached_comp_units
2179 {
2180 public:
2181
2182   explicit free_cached_comp_units (dwarf2_per_objfile *per_objfile)
2183     : m_per_objfile (per_objfile)
2184   {
2185   }
2186
2187   ~free_cached_comp_units ()
2188   {
2189     m_per_objfile->free_cached_comp_units ();
2190   }
2191
2192   DISABLE_COPY_AND_ASSIGN (free_cached_comp_units);
2193
2194 private:
2195
2196   dwarf2_per_objfile *m_per_objfile;
2197 };
2198
2199 /* Try to locate the sections we need for DWARF 2 debugging
2200    information and return true if we have enough to do something.
2201    NAMES points to the dwarf2 section names, or is NULL if the standard
2202    ELF names are used.  */
2203
2204 int
2205 dwarf2_has_info (struct objfile *objfile,
2206                  const struct dwarf2_debug_sections *names)
2207 {
2208   if (objfile->flags & OBJF_READNEVER)
2209     return 0;
2210
2211   struct dwarf2_per_objfile *dwarf2_per_objfile
2212     = get_dwarf2_per_objfile (objfile);
2213
2214   if (dwarf2_per_objfile == NULL)
2215     {
2216       /* Initialize per-objfile state.  */
2217       dwarf2_per_objfile
2218         = new (&objfile->objfile_obstack) struct dwarf2_per_objfile (objfile,
2219                                                                      names);
2220       set_dwarf2_per_objfile (objfile, dwarf2_per_objfile);
2221     }
2222   return (!dwarf2_per_objfile->info.is_virtual
2223           && dwarf2_per_objfile->info.s.section != NULL
2224           && !dwarf2_per_objfile->abbrev.is_virtual
2225           && dwarf2_per_objfile->abbrev.s.section != NULL);
2226 }
2227
2228 /* Return the containing section of virtual section SECTION.  */
2229
2230 static struct dwarf2_section_info *
2231 get_containing_section (const struct dwarf2_section_info *section)
2232 {
2233   gdb_assert (section->is_virtual);
2234   return section->s.containing_section;
2235 }
2236
2237 /* Return the bfd owner of SECTION.  */
2238
2239 static struct bfd *
2240 get_section_bfd_owner (const struct dwarf2_section_info *section)
2241 {
2242   if (section->is_virtual)
2243     {
2244       section = get_containing_section (section);
2245       gdb_assert (!section->is_virtual);
2246     }
2247   return section->s.section->owner;
2248 }
2249
2250 /* Return the bfd section of SECTION.
2251    Returns NULL if the section is not present.  */
2252
2253 static asection *
2254 get_section_bfd_section (const struct dwarf2_section_info *section)
2255 {
2256   if (section->is_virtual)
2257     {
2258       section = get_containing_section (section);
2259       gdb_assert (!section->is_virtual);
2260     }
2261   return section->s.section;
2262 }
2263
2264 /* Return the name of SECTION.  */
2265
2266 static const char *
2267 get_section_name (const struct dwarf2_section_info *section)
2268 {
2269   asection *sectp = get_section_bfd_section (section);
2270
2271   gdb_assert (sectp != NULL);
2272   return bfd_section_name (get_section_bfd_owner (section), sectp);
2273 }
2274
2275 /* Return the name of the file SECTION is in.  */
2276
2277 static const char *
2278 get_section_file_name (const struct dwarf2_section_info *section)
2279 {
2280   bfd *abfd = get_section_bfd_owner (section);
2281
2282   return bfd_get_filename (abfd);
2283 }
2284
2285 /* Return the id of SECTION.
2286    Returns 0 if SECTION doesn't exist.  */
2287
2288 static int
2289 get_section_id (const struct dwarf2_section_info *section)
2290 {
2291   asection *sectp = get_section_bfd_section (section);
2292
2293   if (sectp == NULL)
2294     return 0;
2295   return sectp->id;
2296 }
2297
2298 /* Return the flags of SECTION.
2299    SECTION (or containing section if this is a virtual section) must exist.  */
2300
2301 static int
2302 get_section_flags (const struct dwarf2_section_info *section)
2303 {
2304   asection *sectp = get_section_bfd_section (section);
2305
2306   gdb_assert (sectp != NULL);
2307   return bfd_get_section_flags (sectp->owner, sectp);
2308 }
2309
2310 /* When loading sections, we look either for uncompressed section or for
2311    compressed section names.  */
2312
2313 static int
2314 section_is_p (const char *section_name,
2315               const struct dwarf2_section_names *names)
2316 {
2317   if (names->normal != NULL
2318       && strcmp (section_name, names->normal) == 0)
2319     return 1;
2320   if (names->compressed != NULL
2321       && strcmp (section_name, names->compressed) == 0)
2322     return 1;
2323   return 0;
2324 }
2325
2326 /* See declaration.  */
2327
2328 void
2329 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2330                                      const dwarf2_debug_sections &names)
2331 {
2332   flagword aflag = bfd_get_section_flags (abfd, sectp);
2333
2334   if ((aflag & SEC_HAS_CONTENTS) == 0)
2335     {
2336     }
2337   else if (section_is_p (sectp->name, &names.info))
2338     {
2339       this->info.s.section = sectp;
2340       this->info.size = bfd_get_section_size (sectp);
2341     }
2342   else if (section_is_p (sectp->name, &names.abbrev))
2343     {
2344       this->abbrev.s.section = sectp;
2345       this->abbrev.size = bfd_get_section_size (sectp);
2346     }
2347   else if (section_is_p (sectp->name, &names.line))
2348     {
2349       this->line.s.section = sectp;
2350       this->line.size = bfd_get_section_size (sectp);
2351     }
2352   else if (section_is_p (sectp->name, &names.loc))
2353     {
2354       this->loc.s.section = sectp;
2355       this->loc.size = bfd_get_section_size (sectp);
2356     }
2357   else if (section_is_p (sectp->name, &names.loclists))
2358     {
2359       this->loclists.s.section = sectp;
2360       this->loclists.size = bfd_get_section_size (sectp);
2361     }
2362   else if (section_is_p (sectp->name, &names.macinfo))
2363     {
2364       this->macinfo.s.section = sectp;
2365       this->macinfo.size = bfd_get_section_size (sectp);
2366     }
2367   else if (section_is_p (sectp->name, &names.macro))
2368     {
2369       this->macro.s.section = sectp;
2370       this->macro.size = bfd_get_section_size (sectp);
2371     }
2372   else if (section_is_p (sectp->name, &names.str))
2373     {
2374       this->str.s.section = sectp;
2375       this->str.size = bfd_get_section_size (sectp);
2376     }
2377   else if (section_is_p (sectp->name, &names.line_str))
2378     {
2379       this->line_str.s.section = sectp;
2380       this->line_str.size = bfd_get_section_size (sectp);
2381     }
2382   else if (section_is_p (sectp->name, &names.addr))
2383     {
2384       this->addr.s.section = sectp;
2385       this->addr.size = bfd_get_section_size (sectp);
2386     }
2387   else if (section_is_p (sectp->name, &names.frame))
2388     {
2389       this->frame.s.section = sectp;
2390       this->frame.size = bfd_get_section_size (sectp);
2391     }
2392   else if (section_is_p (sectp->name, &names.eh_frame))
2393     {
2394       this->eh_frame.s.section = sectp;
2395       this->eh_frame.size = bfd_get_section_size (sectp);
2396     }
2397   else if (section_is_p (sectp->name, &names.ranges))
2398     {
2399       this->ranges.s.section = sectp;
2400       this->ranges.size = bfd_get_section_size (sectp);
2401     }
2402   else if (section_is_p (sectp->name, &names.rnglists))
2403     {
2404       this->rnglists.s.section = sectp;
2405       this->rnglists.size = bfd_get_section_size (sectp);
2406     }
2407   else if (section_is_p (sectp->name, &names.types))
2408     {
2409       struct dwarf2_section_info type_section;
2410
2411       memset (&type_section, 0, sizeof (type_section));
2412       type_section.s.section = sectp;
2413       type_section.size = bfd_get_section_size (sectp);
2414
2415       VEC_safe_push (dwarf2_section_info_def, this->types,
2416                      &type_section);
2417     }
2418   else if (section_is_p (sectp->name, &names.gdb_index))
2419     {
2420       this->gdb_index.s.section = sectp;
2421       this->gdb_index.size = bfd_get_section_size (sectp);
2422     }
2423   else if (section_is_p (sectp->name, &names.debug_names))
2424     {
2425       this->debug_names.s.section = sectp;
2426       this->debug_names.size = bfd_get_section_size (sectp);
2427     }
2428   else if (section_is_p (sectp->name, &names.debug_aranges))
2429     {
2430       this->debug_aranges.s.section = sectp;
2431       this->debug_aranges.size = bfd_get_section_size (sectp);
2432     }
2433
2434   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2435       && bfd_section_vma (abfd, sectp) == 0)
2436     this->has_section_at_zero = true;
2437 }
2438
2439 /* A helper function that decides whether a section is empty,
2440    or not present.  */
2441
2442 static int
2443 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2444 {
2445   if (section->is_virtual)
2446     return section->size == 0;
2447   return section->s.section == NULL || section->size == 0;
2448 }
2449
2450 /* See dwarf2read.h.  */
2451
2452 void
2453 dwarf2_read_section (struct objfile *objfile, dwarf2_section_info *info)
2454 {
2455   asection *sectp;
2456   bfd *abfd;
2457   gdb_byte *buf, *retbuf;
2458
2459   if (info->readin)
2460     return;
2461   info->buffer = NULL;
2462   info->readin = 1;
2463
2464   if (dwarf2_section_empty_p (info))
2465     return;
2466
2467   sectp = get_section_bfd_section (info);
2468
2469   /* If this is a virtual section we need to read in the real one first.  */
2470   if (info->is_virtual)
2471     {
2472       struct dwarf2_section_info *containing_section =
2473         get_containing_section (info);
2474
2475       gdb_assert (sectp != NULL);
2476       if ((sectp->flags & SEC_RELOC) != 0)
2477         {
2478           error (_("Dwarf Error: DWP format V2 with relocations is not"
2479                    " supported in section %s [in module %s]"),
2480                  get_section_name (info), get_section_file_name (info));
2481         }
2482       dwarf2_read_section (objfile, containing_section);
2483       /* Other code should have already caught virtual sections that don't
2484          fit.  */
2485       gdb_assert (info->virtual_offset + info->size
2486                   <= containing_section->size);
2487       /* If the real section is empty or there was a problem reading the
2488          section we shouldn't get here.  */
2489       gdb_assert (containing_section->buffer != NULL);
2490       info->buffer = containing_section->buffer + info->virtual_offset;
2491       return;
2492     }
2493
2494   /* If the section has relocations, we must read it ourselves.
2495      Otherwise we attach it to the BFD.  */
2496   if ((sectp->flags & SEC_RELOC) == 0)
2497     {
2498       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2499       return;
2500     }
2501
2502   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2503   info->buffer = buf;
2504
2505   /* When debugging .o files, we may need to apply relocations; see
2506      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2507      We never compress sections in .o files, so we only need to
2508      try this when the section is not compressed.  */
2509   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2510   if (retbuf != NULL)
2511     {
2512       info->buffer = retbuf;
2513       return;
2514     }
2515
2516   abfd = get_section_bfd_owner (info);
2517   gdb_assert (abfd != NULL);
2518
2519   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2520       || bfd_bread (buf, info->size, abfd) != info->size)
2521     {
2522       error (_("Dwarf Error: Can't read DWARF data"
2523                " in section %s [in module %s]"),
2524              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2525     }
2526 }
2527
2528 /* A helper function that returns the size of a section in a safe way.
2529    If you are positive that the section has been read before using the
2530    size, then it is safe to refer to the dwarf2_section_info object's
2531    "size" field directly.  In other cases, you must call this
2532    function, because for compressed sections the size field is not set
2533    correctly until the section has been read.  */
2534
2535 static bfd_size_type
2536 dwarf2_section_size (struct objfile *objfile,
2537                      struct dwarf2_section_info *info)
2538 {
2539   if (!info->readin)
2540     dwarf2_read_section (objfile, info);
2541   return info->size;
2542 }
2543
2544 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2545    SECTION_NAME.  */
2546
2547 void
2548 dwarf2_get_section_info (struct objfile *objfile,
2549                          enum dwarf2_section_enum sect,
2550                          asection **sectp, const gdb_byte **bufp,
2551                          bfd_size_type *sizep)
2552 {
2553   struct dwarf2_per_objfile *data
2554     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2555                                                   dwarf2_objfile_data_key);
2556   struct dwarf2_section_info *info;
2557
2558   /* We may see an objfile without any DWARF, in which case we just
2559      return nothing.  */
2560   if (data == NULL)
2561     {
2562       *sectp = NULL;
2563       *bufp = NULL;
2564       *sizep = 0;
2565       return;
2566     }
2567   switch (sect)
2568     {
2569     case DWARF2_DEBUG_FRAME:
2570       info = &data->frame;
2571       break;
2572     case DWARF2_EH_FRAME:
2573       info = &data->eh_frame;
2574       break;
2575     default:
2576       gdb_assert_not_reached ("unexpected section");
2577     }
2578
2579   dwarf2_read_section (objfile, info);
2580
2581   *sectp = get_section_bfd_section (info);
2582   *bufp = info->buffer;
2583   *sizep = info->size;
2584 }
2585
2586 /* A helper function to find the sections for a .dwz file.  */
2587
2588 static void
2589 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2590 {
2591   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2592
2593   /* Note that we only support the standard ELF names, because .dwz
2594      is ELF-only (at the time of writing).  */
2595   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2596     {
2597       dwz_file->abbrev.s.section = sectp;
2598       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2599     }
2600   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2601     {
2602       dwz_file->info.s.section = sectp;
2603       dwz_file->info.size = bfd_get_section_size (sectp);
2604     }
2605   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2606     {
2607       dwz_file->str.s.section = sectp;
2608       dwz_file->str.size = bfd_get_section_size (sectp);
2609     }
2610   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2611     {
2612       dwz_file->line.s.section = sectp;
2613       dwz_file->line.size = bfd_get_section_size (sectp);
2614     }
2615   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2616     {
2617       dwz_file->macro.s.section = sectp;
2618       dwz_file->macro.size = bfd_get_section_size (sectp);
2619     }
2620   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2621     {
2622       dwz_file->gdb_index.s.section = sectp;
2623       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2624     }
2625   else if (section_is_p (sectp->name, &dwarf2_elf_names.debug_names))
2626     {
2627       dwz_file->debug_names.s.section = sectp;
2628       dwz_file->debug_names.size = bfd_get_section_size (sectp);
2629     }
2630 }
2631
2632 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2633    there is no .gnu_debugaltlink section in the file.  Error if there
2634    is such a section but the file cannot be found.  */
2635
2636 static struct dwz_file *
2637 dwarf2_get_dwz_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
2638 {
2639   const char *filename;
2640   bfd_size_type buildid_len_arg;
2641   size_t buildid_len;
2642   bfd_byte *buildid;
2643
2644   if (dwarf2_per_objfile->dwz_file != NULL)
2645     return dwarf2_per_objfile->dwz_file.get ();
2646
2647   bfd_set_error (bfd_error_no_error);
2648   gdb::unique_xmalloc_ptr<char> data
2649     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2650                                   &buildid_len_arg, &buildid));
2651   if (data == NULL)
2652     {
2653       if (bfd_get_error () == bfd_error_no_error)
2654         return NULL;
2655       error (_("could not read '.gnu_debugaltlink' section: %s"),
2656              bfd_errmsg (bfd_get_error ()));
2657     }
2658
2659   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2660
2661   buildid_len = (size_t) buildid_len_arg;
2662
2663   filename = data.get ();
2664
2665   std::string abs_storage;
2666   if (!IS_ABSOLUTE_PATH (filename))
2667     {
2668       gdb::unique_xmalloc_ptr<char> abs
2669         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2670
2671       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2672       filename = abs_storage.c_str ();
2673     }
2674
2675   /* First try the file name given in the section.  If that doesn't
2676      work, try to use the build-id instead.  */
2677   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2678   if (dwz_bfd != NULL)
2679     {
2680       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2681         dwz_bfd.release ();
2682     }
2683
2684   if (dwz_bfd == NULL)
2685     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2686
2687   if (dwz_bfd == NULL)
2688     error (_("could not find '.gnu_debugaltlink' file for %s"),
2689            objfile_name (dwarf2_per_objfile->objfile));
2690
2691   std::unique_ptr<struct dwz_file> result
2692     (new struct dwz_file (std::move (dwz_bfd)));
2693
2694   bfd_map_over_sections (result->dwz_bfd.get (), locate_dwz_sections,
2695                          result.get ());
2696
2697   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd,
2698                             result->dwz_bfd.get ());
2699   dwarf2_per_objfile->dwz_file = std::move (result);
2700   return dwarf2_per_objfile->dwz_file.get ();
2701 }
2702 \f
2703 /* DWARF quick_symbols_functions support.  */
2704
2705 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2706    unique line tables, so we maintain a separate table of all .debug_line
2707    derived entries to support the sharing.
2708    All the quick functions need is the list of file names.  We discard the
2709    line_header when we're done and don't need to record it here.  */
2710 struct quick_file_names
2711 {
2712   /* The data used to construct the hash key.  */
2713   struct stmt_list_hash hash;
2714
2715   /* The number of entries in file_names, real_names.  */
2716   unsigned int num_file_names;
2717
2718   /* The file names from the line table, after being run through
2719      file_full_name.  */
2720   const char **file_names;
2721
2722   /* The file names from the line table after being run through
2723      gdb_realpath.  These are computed lazily.  */
2724   const char **real_names;
2725 };
2726
2727 /* When using the index (and thus not using psymtabs), each CU has an
2728    object of this type.  This is used to hold information needed by
2729    the various "quick" methods.  */
2730 struct dwarf2_per_cu_quick_data
2731 {
2732   /* The file table.  This can be NULL if there was no file table
2733      or it's currently not read in.
2734      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2735   struct quick_file_names *file_names;
2736
2737   /* The corresponding symbol table.  This is NULL if symbols for this
2738      CU have not yet been read.  */
2739   struct compunit_symtab *compunit_symtab;
2740
2741   /* A temporary mark bit used when iterating over all CUs in
2742      expand_symtabs_matching.  */
2743   unsigned int mark : 1;
2744
2745   /* True if we've tried to read the file table and found there isn't one.
2746      There will be no point in trying to read it again next time.  */
2747   unsigned int no_file_data : 1;
2748 };
2749
2750 /* Utility hash function for a stmt_list_hash.  */
2751
2752 static hashval_t
2753 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2754 {
2755   hashval_t v = 0;
2756
2757   if (stmt_list_hash->dwo_unit != NULL)
2758     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2759   v += to_underlying (stmt_list_hash->line_sect_off);
2760   return v;
2761 }
2762
2763 /* Utility equality function for a stmt_list_hash.  */
2764
2765 static int
2766 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2767                     const struct stmt_list_hash *rhs)
2768 {
2769   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2770     return 0;
2771   if (lhs->dwo_unit != NULL
2772       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2773     return 0;
2774
2775   return lhs->line_sect_off == rhs->line_sect_off;
2776 }
2777
2778 /* Hash function for a quick_file_names.  */
2779
2780 static hashval_t
2781 hash_file_name_entry (const void *e)
2782 {
2783   const struct quick_file_names *file_data
2784     = (const struct quick_file_names *) e;
2785
2786   return hash_stmt_list_entry (&file_data->hash);
2787 }
2788
2789 /* Equality function for a quick_file_names.  */
2790
2791 static int
2792 eq_file_name_entry (const void *a, const void *b)
2793 {
2794   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2795   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2796
2797   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2798 }
2799
2800 /* Delete function for a quick_file_names.  */
2801
2802 static void
2803 delete_file_name_entry (void *e)
2804 {
2805   struct quick_file_names *file_data = (struct quick_file_names *) e;
2806   int i;
2807
2808   for (i = 0; i < file_data->num_file_names; ++i)
2809     {
2810       xfree ((void*) file_data->file_names[i]);
2811       if (file_data->real_names)
2812         xfree ((void*) file_data->real_names[i]);
2813     }
2814
2815   /* The space for the struct itself lives on objfile_obstack,
2816      so we don't free it here.  */
2817 }
2818
2819 /* Create a quick_file_names hash table.  */
2820
2821 static htab_t
2822 create_quick_file_names_table (unsigned int nr_initial_entries)
2823 {
2824   return htab_create_alloc (nr_initial_entries,
2825                             hash_file_name_entry, eq_file_name_entry,
2826                             delete_file_name_entry, xcalloc, xfree);
2827 }
2828
2829 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2830    have to be created afterwards.  You should call age_cached_comp_units after
2831    processing PER_CU->CU.  dw2_setup must have been already called.  */
2832
2833 static void
2834 load_cu (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2835 {
2836   if (per_cu->is_debug_types)
2837     load_full_type_unit (per_cu);
2838   else
2839     load_full_comp_unit (per_cu, skip_partial, language_minimal);
2840
2841   if (per_cu->cu == NULL)
2842     return;  /* Dummy CU.  */
2843
2844   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2845 }
2846
2847 /* Read in the symbols for PER_CU.  */
2848
2849 static void
2850 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2851 {
2852   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2853
2854   /* Skip type_unit_groups, reading the type units they contain
2855      is handled elsewhere.  */
2856   if (IS_TYPE_UNIT_GROUP (per_cu))
2857     return;
2858
2859   /* The destructor of dwarf2_queue_guard frees any entries left on
2860      the queue.  After this point we're guaranteed to leave this function
2861      with the dwarf queue empty.  */
2862   dwarf2_queue_guard q_guard;
2863
2864   if (dwarf2_per_objfile->using_index
2865       ? per_cu->v.quick->compunit_symtab == NULL
2866       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2867     {
2868       queue_comp_unit (per_cu, language_minimal);
2869       load_cu (per_cu, skip_partial);
2870
2871       /* If we just loaded a CU from a DWO, and we're working with an index
2872          that may badly handle TUs, load all the TUs in that DWO as well.
2873          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2874       if (!per_cu->is_debug_types
2875           && per_cu->cu != NULL
2876           && per_cu->cu->dwo_unit != NULL
2877           && dwarf2_per_objfile->index_table != NULL
2878           && dwarf2_per_objfile->index_table->version <= 7
2879           /* DWP files aren't supported yet.  */
2880           && get_dwp_file (dwarf2_per_objfile) == NULL)
2881         queue_and_load_all_dwo_tus (per_cu);
2882     }
2883
2884   process_queue (dwarf2_per_objfile);
2885
2886   /* Age the cache, releasing compilation units that have not
2887      been used recently.  */
2888   age_cached_comp_units (dwarf2_per_objfile);
2889 }
2890
2891 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2892    the objfile from which this CU came.  Returns the resulting symbol
2893    table.  */
2894
2895 static struct compunit_symtab *
2896 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu, bool skip_partial)
2897 {
2898   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
2899
2900   gdb_assert (dwarf2_per_objfile->using_index);
2901   if (!per_cu->v.quick->compunit_symtab)
2902     {
2903       free_cached_comp_units freer (dwarf2_per_objfile);
2904       scoped_restore decrementer = increment_reading_symtab ();
2905       dw2_do_instantiate_symtab (per_cu, skip_partial);
2906       process_cu_includes (dwarf2_per_objfile);
2907     }
2908
2909   return per_cu->v.quick->compunit_symtab;
2910 }
2911
2912 /* See declaration.  */
2913
2914 dwarf2_per_cu_data *
2915 dwarf2_per_objfile::get_cutu (int index)
2916 {
2917   if (index >= this->all_comp_units.size ())
2918     {
2919       index -= this->all_comp_units.size ();
2920       gdb_assert (index < this->all_type_units.size ());
2921       return &this->all_type_units[index]->per_cu;
2922     }
2923
2924   return this->all_comp_units[index];
2925 }
2926
2927 /* See declaration.  */
2928
2929 dwarf2_per_cu_data *
2930 dwarf2_per_objfile::get_cu (int index)
2931 {
2932   gdb_assert (index >= 0 && index < this->all_comp_units.size ());
2933
2934   return this->all_comp_units[index];
2935 }
2936
2937 /* See declaration.  */
2938
2939 signatured_type *
2940 dwarf2_per_objfile::get_tu (int index)
2941 {
2942   gdb_assert (index >= 0 && index < this->all_type_units.size ());
2943
2944   return this->all_type_units[index];
2945 }
2946
2947 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
2948    objfile_obstack, and constructed with the specified field
2949    values.  */
2950
2951 static dwarf2_per_cu_data *
2952 create_cu_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2953                           struct dwarf2_section_info *section,
2954                           int is_dwz,
2955                           sect_offset sect_off, ULONGEST length)
2956 {
2957   struct objfile *objfile = dwarf2_per_objfile->objfile;
2958   dwarf2_per_cu_data *the_cu
2959     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2960                      struct dwarf2_per_cu_data);
2961   the_cu->sect_off = sect_off;
2962   the_cu->length = length;
2963   the_cu->dwarf2_per_objfile = dwarf2_per_objfile;
2964   the_cu->section = section;
2965   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
2966                                    struct dwarf2_per_cu_quick_data);
2967   the_cu->is_dwz = is_dwz;
2968   return the_cu;
2969 }
2970
2971 /* A helper for create_cus_from_index that handles a given list of
2972    CUs.  */
2973
2974 static void
2975 create_cus_from_index_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
2976                             const gdb_byte *cu_list, offset_type n_elements,
2977                             struct dwarf2_section_info *section,
2978                             int is_dwz)
2979 {
2980   for (offset_type i = 0; i < n_elements; i += 2)
2981     {
2982       gdb_static_assert (sizeof (ULONGEST) >= 8);
2983
2984       sect_offset sect_off
2985         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
2986       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
2987       cu_list += 2 * 8;
2988
2989       dwarf2_per_cu_data *per_cu
2990         = create_cu_from_index_list (dwarf2_per_objfile, section, is_dwz,
2991                                      sect_off, length);
2992       dwarf2_per_objfile->all_comp_units.push_back (per_cu);
2993     }
2994 }
2995
2996 /* Read the CU list from the mapped index, and use it to create all
2997    the CU objects for this objfile.  */
2998
2999 static void
3000 create_cus_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3001                        const gdb_byte *cu_list, offset_type cu_list_elements,
3002                        const gdb_byte *dwz_list, offset_type dwz_elements)
3003 {
3004   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
3005   dwarf2_per_objfile->all_comp_units.reserve
3006     ((cu_list_elements + dwz_elements) / 2);
3007
3008   create_cus_from_index_list (dwarf2_per_objfile, cu_list, cu_list_elements,
3009                               &dwarf2_per_objfile->info, 0);
3010
3011   if (dwz_elements == 0)
3012     return;
3013
3014   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3015   create_cus_from_index_list (dwarf2_per_objfile, dwz_list, dwz_elements,
3016                               &dwz->info, 1);
3017 }
3018
3019 /* Create the signatured type hash table from the index.  */
3020
3021 static void
3022 create_signatured_type_table_from_index
3023   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3024    struct dwarf2_section_info *section,
3025    const gdb_byte *bytes,
3026    offset_type elements)
3027 {
3028   struct objfile *objfile = dwarf2_per_objfile->objfile;
3029
3030   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3031   dwarf2_per_objfile->all_type_units.reserve (elements / 3);
3032
3033   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3034
3035   for (offset_type i = 0; i < elements; i += 3)
3036     {
3037       struct signatured_type *sig_type;
3038       ULONGEST signature;
3039       void **slot;
3040       cu_offset type_offset_in_tu;
3041
3042       gdb_static_assert (sizeof (ULONGEST) >= 8);
3043       sect_offset sect_off
3044         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3045       type_offset_in_tu
3046         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3047                                                 BFD_ENDIAN_LITTLE);
3048       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3049       bytes += 3 * 8;
3050
3051       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3052                                  struct signatured_type);
3053       sig_type->signature = signature;
3054       sig_type->type_offset_in_tu = type_offset_in_tu;
3055       sig_type->per_cu.is_debug_types = 1;
3056       sig_type->per_cu.section = section;
3057       sig_type->per_cu.sect_off = sect_off;
3058       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3059       sig_type->per_cu.v.quick
3060         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3061                           struct dwarf2_per_cu_quick_data);
3062
3063       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3064       *slot = sig_type;
3065
3066       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3067     }
3068
3069   dwarf2_per_objfile->signatured_types = sig_types_hash;
3070 }
3071
3072 /* Create the signatured type hash table from .debug_names.  */
3073
3074 static void
3075 create_signatured_type_table_from_debug_names
3076   (struct dwarf2_per_objfile *dwarf2_per_objfile,
3077    const mapped_debug_names &map,
3078    struct dwarf2_section_info *section,
3079    struct dwarf2_section_info *abbrev_section)
3080 {
3081   struct objfile *objfile = dwarf2_per_objfile->objfile;
3082
3083   dwarf2_read_section (objfile, section);
3084   dwarf2_read_section (objfile, abbrev_section);
3085
3086   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
3087   dwarf2_per_objfile->all_type_units.reserve (map.tu_count);
3088
3089   htab_t sig_types_hash = allocate_signatured_type_table (objfile);
3090
3091   for (uint32_t i = 0; i < map.tu_count; ++i)
3092     {
3093       struct signatured_type *sig_type;
3094       void **slot;
3095
3096       sect_offset sect_off
3097         = (sect_offset) (extract_unsigned_integer
3098                          (map.tu_table_reordered + i * map.offset_size,
3099                           map.offset_size,
3100                           map.dwarf5_byte_order));
3101
3102       comp_unit_head cu_header;
3103       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
3104                                      abbrev_section,
3105                                      section->buffer + to_underlying (sect_off),
3106                                      rcuh_kind::TYPE);
3107
3108       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3109                                  struct signatured_type);
3110       sig_type->signature = cu_header.signature;
3111       sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
3112       sig_type->per_cu.is_debug_types = 1;
3113       sig_type->per_cu.section = section;
3114       sig_type->per_cu.sect_off = sect_off;
3115       sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
3116       sig_type->per_cu.v.quick
3117         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3118                           struct dwarf2_per_cu_quick_data);
3119
3120       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3121       *slot = sig_type;
3122
3123       dwarf2_per_objfile->all_type_units.push_back (sig_type);
3124     }
3125
3126   dwarf2_per_objfile->signatured_types = sig_types_hash;
3127 }
3128
3129 /* Read the address map data from the mapped index, and use it to
3130    populate the objfile's psymtabs_addrmap.  */
3131
3132 static void
3133 create_addrmap_from_index (struct dwarf2_per_objfile *dwarf2_per_objfile,
3134                            struct mapped_index *index)
3135 {
3136   struct objfile *objfile = dwarf2_per_objfile->objfile;
3137   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3138   const gdb_byte *iter, *end;
3139   struct addrmap *mutable_map;
3140   CORE_ADDR baseaddr;
3141
3142   auto_obstack temp_obstack;
3143
3144   mutable_map = addrmap_create_mutable (&temp_obstack);
3145
3146   iter = index->address_table.data ();
3147   end = iter + index->address_table.size ();
3148
3149   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3150
3151   while (iter < end)
3152     {
3153       ULONGEST hi, lo, cu_index;
3154       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3155       iter += 8;
3156       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3157       iter += 8;
3158       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3159       iter += 4;
3160
3161       if (lo > hi)
3162         {
3163           complaint (_(".gdb_index address table has invalid range (%s - %s)"),
3164                      hex_string (lo), hex_string (hi));
3165           continue;
3166         }
3167
3168       if (cu_index >= dwarf2_per_objfile->all_comp_units.size ())
3169         {
3170           complaint (_(".gdb_index address table has invalid CU number %u"),
3171                      (unsigned) cu_index);
3172           continue;
3173         }
3174
3175       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3176       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3177       addrmap_set_empty (mutable_map, lo, hi - 1,
3178                          dwarf2_per_objfile->get_cu (cu_index));
3179     }
3180
3181   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3182                                                     &objfile->objfile_obstack);
3183 }
3184
3185 /* Read the address map data from DWARF-5 .debug_aranges, and use it to
3186    populate the objfile's psymtabs_addrmap.  */
3187
3188 static void
3189 create_addrmap_from_aranges (struct dwarf2_per_objfile *dwarf2_per_objfile,
3190                              struct dwarf2_section_info *section)
3191 {
3192   struct objfile *objfile = dwarf2_per_objfile->objfile;
3193   bfd *abfd = objfile->obfd;
3194   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3195   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
3196                                        SECT_OFF_TEXT (objfile));
3197
3198   auto_obstack temp_obstack;
3199   addrmap *mutable_map = addrmap_create_mutable (&temp_obstack);
3200
3201   std::unordered_map<sect_offset,
3202                      dwarf2_per_cu_data *,
3203                      gdb::hash_enum<sect_offset>>
3204     debug_info_offset_to_per_cu;
3205   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3206     {
3207       const auto insertpair
3208         = debug_info_offset_to_per_cu.emplace (per_cu->sect_off, per_cu);
3209       if (!insertpair.second)
3210         {
3211           warning (_("Section .debug_aranges in %s has duplicate "
3212                      "debug_info_offset %s, ignoring .debug_aranges."),
3213                    objfile_name (objfile), sect_offset_str (per_cu->sect_off));
3214           return;
3215         }
3216     }
3217
3218   dwarf2_read_section (objfile, section);
3219
3220   const bfd_endian dwarf5_byte_order = gdbarch_byte_order (gdbarch);
3221
3222   const gdb_byte *addr = section->buffer;
3223
3224   while (addr < section->buffer + section->size)
3225     {
3226       const gdb_byte *const entry_addr = addr;
3227       unsigned int bytes_read;
3228
3229       const LONGEST entry_length = read_initial_length (abfd, addr,
3230                                                         &bytes_read);
3231       addr += bytes_read;
3232
3233       const gdb_byte *const entry_end = addr + entry_length;
3234       const bool dwarf5_is_dwarf64 = bytes_read != 4;
3235       const uint8_t offset_size = dwarf5_is_dwarf64 ? 8 : 4;
3236       if (addr + entry_length > section->buffer + section->size)
3237         {
3238           warning (_("Section .debug_aranges in %s entry at offset %zu "
3239                      "length %s exceeds section length %s, "
3240                      "ignoring .debug_aranges."),
3241                    objfile_name (objfile), entry_addr - section->buffer,
3242                    plongest (bytes_read + entry_length),
3243                    pulongest (section->size));
3244           return;
3245         }
3246
3247       /* The version number.  */
3248       const uint16_t version = read_2_bytes (abfd, addr);
3249       addr += 2;
3250       if (version != 2)
3251         {
3252           warning (_("Section .debug_aranges in %s entry at offset %zu "
3253                      "has unsupported version %d, ignoring .debug_aranges."),
3254                    objfile_name (objfile), entry_addr - section->buffer,
3255                    version);
3256           return;
3257         }
3258
3259       const uint64_t debug_info_offset
3260         = extract_unsigned_integer (addr, offset_size, dwarf5_byte_order);
3261       addr += offset_size;
3262       const auto per_cu_it
3263         = debug_info_offset_to_per_cu.find (sect_offset (debug_info_offset));
3264       if (per_cu_it == debug_info_offset_to_per_cu.cend ())
3265         {
3266           warning (_("Section .debug_aranges in %s entry at offset %zu "
3267                      "debug_info_offset %s does not exists, "
3268                      "ignoring .debug_aranges."),
3269                    objfile_name (objfile), entry_addr - section->buffer,
3270                    pulongest (debug_info_offset));
3271           return;
3272         }
3273       dwarf2_per_cu_data *const per_cu = per_cu_it->second;
3274
3275       const uint8_t address_size = *addr++;
3276       if (address_size < 1 || address_size > 8)
3277         {
3278           warning (_("Section .debug_aranges in %s entry at offset %zu "
3279                      "address_size %u is invalid, ignoring .debug_aranges."),
3280                    objfile_name (objfile), entry_addr - section->buffer,
3281                    address_size);
3282           return;
3283         }
3284
3285       const uint8_t segment_selector_size = *addr++;
3286       if (segment_selector_size != 0)
3287         {
3288           warning (_("Section .debug_aranges in %s entry at offset %zu "
3289                      "segment_selector_size %u is not supported, "
3290                      "ignoring .debug_aranges."),
3291                    objfile_name (objfile), entry_addr - section->buffer,
3292                    segment_selector_size);
3293           return;
3294         }
3295
3296       /* Must pad to an alignment boundary that is twice the address
3297          size.  It is undocumented by the DWARF standard but GCC does
3298          use it.  */
3299       for (size_t padding = ((-(addr - section->buffer))
3300                              & (2 * address_size - 1));
3301            padding > 0; padding--)
3302         if (*addr++ != 0)
3303           {
3304             warning (_("Section .debug_aranges in %s entry at offset %zu "
3305                        "padding is not zero, ignoring .debug_aranges."),
3306                      objfile_name (objfile), entry_addr - section->buffer);
3307             return;
3308           }
3309
3310       for (;;)
3311         {
3312           if (addr + 2 * address_size > entry_end)
3313             {
3314               warning (_("Section .debug_aranges in %s entry at offset %zu "
3315                          "address list is not properly terminated, "
3316                          "ignoring .debug_aranges."),
3317                        objfile_name (objfile), entry_addr - section->buffer);
3318               return;
3319             }
3320           ULONGEST start = extract_unsigned_integer (addr, address_size,
3321                                                      dwarf5_byte_order);
3322           addr += address_size;
3323           ULONGEST length = extract_unsigned_integer (addr, address_size,
3324                                                       dwarf5_byte_order);
3325           addr += address_size;
3326           if (start == 0 && length == 0)
3327             break;
3328           if (start == 0 && !dwarf2_per_objfile->has_section_at_zero)
3329             {
3330               /* Symbol was eliminated due to a COMDAT group.  */
3331               continue;
3332             }
3333           ULONGEST end = start + length;
3334           start = gdbarch_adjust_dwarf2_addr (gdbarch, start + baseaddr);
3335           end = gdbarch_adjust_dwarf2_addr (gdbarch, end + baseaddr);
3336           addrmap_set_empty (mutable_map, start, end - 1, per_cu);
3337         }
3338     }
3339
3340   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3341                                                     &objfile->objfile_obstack);
3342 }
3343
3344 /* Find a slot in the mapped index INDEX for the object named NAME.
3345    If NAME is found, set *VEC_OUT to point to the CU vector in the
3346    constant pool and return true.  If NAME cannot be found, return
3347    false.  */
3348
3349 static bool
3350 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3351                           offset_type **vec_out)
3352 {
3353   offset_type hash;
3354   offset_type slot, step;
3355   int (*cmp) (const char *, const char *);
3356
3357   gdb::unique_xmalloc_ptr<char> without_params;
3358   if (current_language->la_language == language_cplus
3359       || current_language->la_language == language_fortran
3360       || current_language->la_language == language_d)
3361     {
3362       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3363          not contain any.  */
3364
3365       if (strchr (name, '(') != NULL)
3366         {
3367           without_params = cp_remove_params (name);
3368
3369           if (without_params != NULL)
3370             name = without_params.get ();
3371         }
3372     }
3373
3374   /* Index version 4 did not support case insensitive searches.  But the
3375      indices for case insensitive languages are built in lowercase, therefore
3376      simulate our NAME being searched is also lowercased.  */
3377   hash = mapped_index_string_hash ((index->version == 4
3378                                     && case_sensitivity == case_sensitive_off
3379                                     ? 5 : index->version),
3380                                    name);
3381
3382   slot = hash & (index->symbol_table.size () - 1);
3383   step = ((hash * 17) & (index->symbol_table.size () - 1)) | 1;
3384   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3385
3386   for (;;)
3387     {
3388       const char *str;
3389
3390       const auto &bucket = index->symbol_table[slot];
3391       if (bucket.name == 0 && bucket.vec == 0)
3392         return false;
3393
3394       str = index->constant_pool + MAYBE_SWAP (bucket.name);
3395       if (!cmp (name, str))
3396         {
3397           *vec_out = (offset_type *) (index->constant_pool
3398                                       + MAYBE_SWAP (bucket.vec));
3399           return true;
3400         }
3401
3402       slot = (slot + step) & (index->symbol_table.size () - 1);
3403     }
3404 }
3405
3406 /* A helper function that reads the .gdb_index from SECTION and fills
3407    in MAP.  FILENAME is the name of the file containing the section;
3408    it is used for error reporting.  DEPRECATED_OK is true if it is
3409    ok to use deprecated sections.
3410
3411    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3412    out parameters that are filled in with information about the CU and
3413    TU lists in the section.
3414
3415    Returns 1 if all went well, 0 otherwise.  */
3416
3417 static bool
3418 read_gdb_index_from_section (struct objfile *objfile,
3419                              const char *filename,
3420                              bool deprecated_ok,
3421                              struct dwarf2_section_info *section,
3422                              struct mapped_index *map,
3423                              const gdb_byte **cu_list,
3424                              offset_type *cu_list_elements,
3425                              const gdb_byte **types_list,
3426                              offset_type *types_list_elements)
3427 {
3428   const gdb_byte *addr;
3429   offset_type version;
3430   offset_type *metadata;
3431   int i;
3432
3433   if (dwarf2_section_empty_p (section))
3434     return 0;
3435
3436   /* Older elfutils strip versions could keep the section in the main
3437      executable while splitting it for the separate debug info file.  */
3438   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3439     return 0;
3440
3441   dwarf2_read_section (objfile, section);
3442
3443   addr = section->buffer;
3444   /* Version check.  */
3445   version = MAYBE_SWAP (*(offset_type *) addr);
3446   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3447      causes the index to behave very poorly for certain requests.  Version 3
3448      contained incomplete addrmap.  So, it seems better to just ignore such
3449      indices.  */
3450   if (version < 4)
3451     {
3452       static int warning_printed = 0;
3453       if (!warning_printed)
3454         {
3455           warning (_("Skipping obsolete .gdb_index section in %s."),
3456                    filename);
3457           warning_printed = 1;
3458         }
3459       return 0;
3460     }
3461   /* Index version 4 uses a different hash function than index version
3462      5 and later.
3463
3464      Versions earlier than 6 did not emit psymbols for inlined
3465      functions.  Using these files will cause GDB not to be able to
3466      set breakpoints on inlined functions by name, so we ignore these
3467      indices unless the user has done
3468      "set use-deprecated-index-sections on".  */
3469   if (version < 6 && !deprecated_ok)
3470     {
3471       static int warning_printed = 0;
3472       if (!warning_printed)
3473         {
3474           warning (_("\
3475 Skipping deprecated .gdb_index section in %s.\n\
3476 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3477 to use the section anyway."),
3478                    filename);
3479           warning_printed = 1;
3480         }
3481       return 0;
3482     }
3483   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3484      of the TU (for symbols coming from TUs),
3485      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3486      Plus gold-generated indices can have duplicate entries for global symbols,
3487      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3488      These are just performance bugs, and we can't distinguish gdb-generated
3489      indices from gold-generated ones, so issue no warning here.  */
3490
3491   /* Indexes with higher version than the one supported by GDB may be no
3492      longer backward compatible.  */
3493   if (version > 8)
3494     return 0;
3495
3496   map->version = version;
3497
3498   metadata = (offset_type *) (addr + sizeof (offset_type));
3499
3500   i = 0;
3501   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3502   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3503                        / 8);
3504   ++i;
3505
3506   *types_list = addr + MAYBE_SWAP (metadata[i]);
3507   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3508                            - MAYBE_SWAP (metadata[i]))
3509                           / 8);
3510   ++i;
3511
3512   const gdb_byte *address_table = addr + MAYBE_SWAP (metadata[i]);
3513   const gdb_byte *address_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3514   map->address_table
3515     = gdb::array_view<const gdb_byte> (address_table, address_table_end);
3516   ++i;
3517
3518   const gdb_byte *symbol_table = addr + MAYBE_SWAP (metadata[i]);
3519   const gdb_byte *symbol_table_end = addr + MAYBE_SWAP (metadata[i + 1]);
3520   map->symbol_table
3521     = gdb::array_view<mapped_index::symbol_table_slot>
3522        ((mapped_index::symbol_table_slot *) symbol_table,
3523         (mapped_index::symbol_table_slot *) symbol_table_end);
3524
3525   ++i;
3526   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3527
3528   return 1;
3529 }
3530
3531 /* Read .gdb_index.  If everything went ok, initialize the "quick"
3532    elements of all the CUs and return 1.  Otherwise, return 0.  */
3533
3534 static int
3535 dwarf2_read_gdb_index (struct dwarf2_per_objfile *dwarf2_per_objfile)
3536 {
3537   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3538   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3539   struct dwz_file *dwz;
3540   struct objfile *objfile = dwarf2_per_objfile->objfile;
3541
3542   std::unique_ptr<struct mapped_index> map (new struct mapped_index);
3543   if (!read_gdb_index_from_section (objfile, objfile_name (objfile),
3544                                     use_deprecated_index_sections,
3545                                     &dwarf2_per_objfile->gdb_index, map.get (),
3546                                     &cu_list, &cu_list_elements,
3547                                     &types_list, &types_list_elements))
3548     return 0;
3549
3550   /* Don't use the index if it's empty.  */
3551   if (map->symbol_table.empty ())
3552     return 0;
3553
3554   /* If there is a .dwz file, read it so we can get its CU list as
3555      well.  */
3556   dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
3557   if (dwz != NULL)
3558     {
3559       struct mapped_index dwz_map;
3560       const gdb_byte *dwz_types_ignore;
3561       offset_type dwz_types_elements_ignore;
3562
3563       if (!read_gdb_index_from_section (objfile,
3564                                         bfd_get_filename (dwz->dwz_bfd), 1,
3565                                         &dwz->gdb_index, &dwz_map,
3566                                         &dwz_list, &dwz_list_elements,
3567                                         &dwz_types_ignore,
3568                                         &dwz_types_elements_ignore))
3569         {
3570           warning (_("could not read '.gdb_index' section from %s; skipping"),
3571                    bfd_get_filename (dwz->dwz_bfd));
3572           return 0;
3573         }
3574     }
3575
3576   create_cus_from_index (dwarf2_per_objfile, cu_list, cu_list_elements,
3577                          dwz_list, dwz_list_elements);
3578
3579   if (types_list_elements)
3580     {
3581       struct dwarf2_section_info *section;
3582
3583       /* We can only handle a single .debug_types when we have an
3584          index.  */
3585       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3586         return 0;
3587
3588       section = VEC_index (dwarf2_section_info_def,
3589                            dwarf2_per_objfile->types, 0);
3590
3591       create_signatured_type_table_from_index (dwarf2_per_objfile, section,
3592                                                types_list, types_list_elements);
3593     }
3594
3595   create_addrmap_from_index (dwarf2_per_objfile, map.get ());
3596
3597   dwarf2_per_objfile->index_table = std::move (map);
3598   dwarf2_per_objfile->using_index = 1;
3599   dwarf2_per_objfile->quick_file_names_table =
3600     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
3601
3602   return 1;
3603 }
3604
3605 /* die_reader_func for dw2_get_file_names.  */
3606
3607 static void
3608 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3609                            const gdb_byte *info_ptr,
3610                            struct die_info *comp_unit_die,
3611                            int has_children,
3612                            void *data)
3613 {
3614   struct dwarf2_cu *cu = reader->cu;
3615   struct dwarf2_per_cu_data *this_cu = cu->per_cu;
3616   struct dwarf2_per_objfile *dwarf2_per_objfile
3617     = cu->per_cu->dwarf2_per_objfile;
3618   struct objfile *objfile = dwarf2_per_objfile->objfile;
3619   struct dwarf2_per_cu_data *lh_cu;
3620   struct attribute *attr;
3621   int i;
3622   void **slot;
3623   struct quick_file_names *qfn;
3624
3625   gdb_assert (! this_cu->is_debug_types);
3626
3627   /* Our callers never want to match partial units -- instead they
3628      will match the enclosing full CU.  */
3629   if (comp_unit_die->tag == DW_TAG_partial_unit)
3630     {
3631       this_cu->v.quick->no_file_data = 1;
3632       return;
3633     }
3634
3635   lh_cu = this_cu;
3636   slot = NULL;
3637
3638   line_header_up lh;
3639   sect_offset line_offset {};
3640
3641   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3642   if (attr)
3643     {
3644       struct quick_file_names find_entry;
3645
3646       line_offset = (sect_offset) DW_UNSND (attr);
3647
3648       /* We may have already read in this line header (TU line header sharing).
3649          If we have we're done.  */
3650       find_entry.hash.dwo_unit = cu->dwo_unit;
3651       find_entry.hash.line_sect_off = line_offset;
3652       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3653                              &find_entry, INSERT);
3654       if (*slot != NULL)
3655         {
3656           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3657           return;
3658         }
3659
3660       lh = dwarf_decode_line_header (line_offset, cu);
3661     }
3662   if (lh == NULL)
3663     {
3664       lh_cu->v.quick->no_file_data = 1;
3665       return;
3666     }
3667
3668   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3669   qfn->hash.dwo_unit = cu->dwo_unit;
3670   qfn->hash.line_sect_off = line_offset;
3671   gdb_assert (slot != NULL);
3672   *slot = qfn;
3673
3674   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3675
3676   qfn->num_file_names = lh->file_names.size ();
3677   qfn->file_names =
3678     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3679   for (i = 0; i < lh->file_names.size (); ++i)
3680     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3681   qfn->real_names = NULL;
3682
3683   lh_cu->v.quick->file_names = qfn;
3684 }
3685
3686 /* A helper for the "quick" functions which attempts to read the line
3687    table for THIS_CU.  */
3688
3689 static struct quick_file_names *
3690 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3691 {
3692   /* This should never be called for TUs.  */
3693   gdb_assert (! this_cu->is_debug_types);
3694   /* Nor type unit groups.  */
3695   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3696
3697   if (this_cu->v.quick->file_names != NULL)
3698     return this_cu->v.quick->file_names;
3699   /* If we know there is no line data, no point in looking again.  */
3700   if (this_cu->v.quick->no_file_data)
3701     return NULL;
3702
3703   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3704
3705   if (this_cu->v.quick->no_file_data)
3706     return NULL;
3707   return this_cu->v.quick->file_names;
3708 }
3709
3710 /* A helper for the "quick" functions which computes and caches the
3711    real path for a given file name from the line table.  */
3712
3713 static const char *
3714 dw2_get_real_path (struct objfile *objfile,
3715                    struct quick_file_names *qfn, int index)
3716 {
3717   if (qfn->real_names == NULL)
3718     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3719                                       qfn->num_file_names, const char *);
3720
3721   if (qfn->real_names[index] == NULL)
3722     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3723
3724   return qfn->real_names[index];
3725 }
3726
3727 static struct symtab *
3728 dw2_find_last_source_symtab (struct objfile *objfile)
3729 {
3730   struct dwarf2_per_objfile *dwarf2_per_objfile
3731     = get_dwarf2_per_objfile (objfile);
3732   dwarf2_per_cu_data *dwarf_cu = dwarf2_per_objfile->all_comp_units.back ();
3733   compunit_symtab *cust = dw2_instantiate_symtab (dwarf_cu, false);
3734
3735   if (cust == NULL)
3736     return NULL;
3737
3738   return compunit_primary_filetab (cust);
3739 }
3740
3741 /* Traversal function for dw2_forget_cached_source_info.  */
3742
3743 static int
3744 dw2_free_cached_file_names (void **slot, void *info)
3745 {
3746   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3747
3748   if (file_data->real_names)
3749     {
3750       int i;
3751
3752       for (i = 0; i < file_data->num_file_names; ++i)
3753         {
3754           xfree ((void*) file_data->real_names[i]);
3755           file_data->real_names[i] = NULL;
3756         }
3757     }
3758
3759   return 1;
3760 }
3761
3762 static void
3763 dw2_forget_cached_source_info (struct objfile *objfile)
3764 {
3765   struct dwarf2_per_objfile *dwarf2_per_objfile
3766     = get_dwarf2_per_objfile (objfile);
3767
3768   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3769                           dw2_free_cached_file_names, NULL);
3770 }
3771
3772 /* Helper function for dw2_map_symtabs_matching_filename that expands
3773    the symtabs and calls the iterator.  */
3774
3775 static int
3776 dw2_map_expand_apply (struct objfile *objfile,
3777                       struct dwarf2_per_cu_data *per_cu,
3778                       const char *name, const char *real_path,
3779                       gdb::function_view<bool (symtab *)> callback)
3780 {
3781   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3782
3783   /* Don't visit already-expanded CUs.  */
3784   if (per_cu->v.quick->compunit_symtab)
3785     return 0;
3786
3787   /* This may expand more than one symtab, and we want to iterate over
3788      all of them.  */
3789   dw2_instantiate_symtab (per_cu, false);
3790
3791   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3792                                     last_made, callback);
3793 }
3794
3795 /* Implementation of the map_symtabs_matching_filename method.  */
3796
3797 static bool
3798 dw2_map_symtabs_matching_filename
3799   (struct objfile *objfile, const char *name, const char *real_path,
3800    gdb::function_view<bool (symtab *)> callback)
3801 {
3802   const char *name_basename = lbasename (name);
3803   struct dwarf2_per_objfile *dwarf2_per_objfile
3804     = get_dwarf2_per_objfile (objfile);
3805
3806   /* The rule is CUs specify all the files, including those used by
3807      any TU, so there's no need to scan TUs here.  */
3808
3809   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
3810     {
3811       /* We only need to look at symtabs not already expanded.  */
3812       if (per_cu->v.quick->compunit_symtab)
3813         continue;
3814
3815       quick_file_names *file_data = dw2_get_file_names (per_cu);
3816       if (file_data == NULL)
3817         continue;
3818
3819       for (int j = 0; j < file_data->num_file_names; ++j)
3820         {
3821           const char *this_name = file_data->file_names[j];
3822           const char *this_real_name;
3823
3824           if (compare_filenames_for_search (this_name, name))
3825             {
3826               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3827                                         callback))
3828                 return true;
3829               continue;
3830             }
3831
3832           /* Before we invoke realpath, which can get expensive when many
3833              files are involved, do a quick comparison of the basenames.  */
3834           if (! basenames_may_differ
3835               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3836             continue;
3837
3838           this_real_name = dw2_get_real_path (objfile, file_data, j);
3839           if (compare_filenames_for_search (this_real_name, name))
3840             {
3841               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3842                                         callback))
3843                 return true;
3844               continue;
3845             }
3846
3847           if (real_path != NULL)
3848             {
3849               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3850               gdb_assert (IS_ABSOLUTE_PATH (name));
3851               if (this_real_name != NULL
3852                   && FILENAME_CMP (real_path, this_real_name) == 0)
3853                 {
3854                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3855                                             callback))
3856                     return true;
3857                   continue;
3858                 }
3859             }
3860         }
3861     }
3862
3863   return false;
3864 }
3865
3866 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3867
3868 struct dw2_symtab_iterator
3869 {
3870   /* The dwarf2_per_objfile owning the CUs we are iterating on.  */
3871   struct dwarf2_per_objfile *dwarf2_per_objfile;
3872   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3873   int want_specific_block;
3874   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3875      Unused if !WANT_SPECIFIC_BLOCK.  */
3876   int block_index;
3877   /* The kind of symbol we're looking for.  */
3878   domain_enum domain;
3879   /* The list of CUs from the index entry of the symbol,
3880      or NULL if not found.  */
3881   offset_type *vec;
3882   /* The next element in VEC to look at.  */
3883   int next;
3884   /* The number of elements in VEC, or zero if there is no match.  */
3885   int length;
3886   /* Have we seen a global version of the symbol?
3887      If so we can ignore all further global instances.
3888      This is to work around gold/15646, inefficient gold-generated
3889      indices.  */
3890   int global_seen;
3891 };
3892
3893 /* Initialize the index symtab iterator ITER.
3894    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3895    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3896
3897 static void
3898 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3899                       struct dwarf2_per_objfile *dwarf2_per_objfile,
3900                       int want_specific_block,
3901                       int block_index,
3902                       domain_enum domain,
3903                       const char *name)
3904 {
3905   iter->dwarf2_per_objfile = dwarf2_per_objfile;
3906   iter->want_specific_block = want_specific_block;
3907   iter->block_index = block_index;
3908   iter->domain = domain;
3909   iter->next = 0;
3910   iter->global_seen = 0;
3911
3912   mapped_index *index = dwarf2_per_objfile->index_table.get ();
3913
3914   /* index is NULL if OBJF_READNOW.  */
3915   if (index != NULL && find_slot_in_mapped_hash (index, name, &iter->vec))
3916     iter->length = MAYBE_SWAP (*iter->vec);
3917   else
3918     {
3919       iter->vec = NULL;
3920       iter->length = 0;
3921     }
3922 }
3923
3924 /* Return the next matching CU or NULL if there are no more.  */
3925
3926 static struct dwarf2_per_cu_data *
3927 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3928 {
3929   struct dwarf2_per_objfile *dwarf2_per_objfile = iter->dwarf2_per_objfile;
3930
3931   for ( ; iter->next < iter->length; ++iter->next)
3932     {
3933       offset_type cu_index_and_attrs =
3934         MAYBE_SWAP (iter->vec[iter->next + 1]);
3935       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3936       int want_static = iter->block_index != GLOBAL_BLOCK;
3937       /* This value is only valid for index versions >= 7.  */
3938       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3939       gdb_index_symbol_kind symbol_kind =
3940         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3941       /* Only check the symbol attributes if they're present.
3942          Indices prior to version 7 don't record them,
3943          and indices >= 7 may elide them for certain symbols
3944          (gold does this).  */
3945       int attrs_valid =
3946         (dwarf2_per_objfile->index_table->version >= 7
3947          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3948
3949       /* Don't crash on bad data.  */
3950       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
3951                        + dwarf2_per_objfile->all_type_units.size ()))
3952         {
3953           complaint (_(".gdb_index entry has bad CU index"
3954                        " [in module %s]"),
3955                      objfile_name (dwarf2_per_objfile->objfile));
3956           continue;
3957         }
3958
3959       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
3960
3961       /* Skip if already read in.  */
3962       if (per_cu->v.quick->compunit_symtab)
3963         continue;
3964
3965       /* Check static vs global.  */
3966       if (attrs_valid)
3967         {
3968           if (iter->want_specific_block
3969               && want_static != is_static)
3970             continue;
3971           /* Work around gold/15646.  */
3972           if (!is_static && iter->global_seen)
3973             continue;
3974           if (!is_static)
3975             iter->global_seen = 1;
3976         }
3977
3978       /* Only check the symbol's kind if it has one.  */
3979       if (attrs_valid)
3980         {
3981           switch (iter->domain)
3982             {
3983             case VAR_DOMAIN:
3984               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3985                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3986                   /* Some types are also in VAR_DOMAIN.  */
3987                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3988                 continue;
3989               break;
3990             case STRUCT_DOMAIN:
3991               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3992                 continue;
3993               break;
3994             case LABEL_DOMAIN:
3995               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3996                 continue;
3997               break;
3998             default:
3999               break;
4000             }
4001         }
4002
4003       ++iter->next;
4004       return per_cu;
4005     }
4006
4007   return NULL;
4008 }
4009
4010 static struct compunit_symtab *
4011 dw2_lookup_symbol (struct objfile *objfile, int block_index,
4012                    const char *name, domain_enum domain)
4013 {
4014   struct compunit_symtab *stab_best = NULL;
4015   struct dwarf2_per_objfile *dwarf2_per_objfile
4016     = get_dwarf2_per_objfile (objfile);
4017
4018   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
4019
4020   struct dw2_symtab_iterator iter;
4021   struct dwarf2_per_cu_data *per_cu;
4022
4023   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 1, block_index, domain, name);
4024
4025   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4026     {
4027       struct symbol *sym, *with_opaque = NULL;
4028       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
4029       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
4030       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
4031
4032       sym = block_find_symbol (block, name, domain,
4033                                block_find_non_opaque_type_preferred,
4034                                &with_opaque);
4035
4036       /* Some caution must be observed with overloaded functions
4037          and methods, since the index will not contain any overload
4038          information (but NAME might contain it).  */
4039
4040       if (sym != NULL
4041           && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
4042         return stab;
4043       if (with_opaque != NULL
4044           && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
4045         stab_best = stab;
4046
4047       /* Keep looking through other CUs.  */
4048     }
4049
4050   return stab_best;
4051 }
4052
4053 static void
4054 dw2_print_stats (struct objfile *objfile)
4055 {
4056   struct dwarf2_per_objfile *dwarf2_per_objfile
4057     = get_dwarf2_per_objfile (objfile);
4058   int total = (dwarf2_per_objfile->all_comp_units.size ()
4059                + dwarf2_per_objfile->all_type_units.size ());
4060   int count = 0;
4061
4062   for (int i = 0; i < total; ++i)
4063     {
4064       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4065
4066       if (!per_cu->v.quick->compunit_symtab)
4067         ++count;
4068     }
4069   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4070   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4071 }
4072
4073 /* This dumps minimal information about the index.
4074    It is called via "mt print objfiles".
4075    One use is to verify .gdb_index has been loaded by the
4076    gdb.dwarf2/gdb-index.exp testcase.  */
4077
4078 static void
4079 dw2_dump (struct objfile *objfile)
4080 {
4081   struct dwarf2_per_objfile *dwarf2_per_objfile
4082     = get_dwarf2_per_objfile (objfile);
4083
4084   gdb_assert (dwarf2_per_objfile->using_index);
4085   printf_filtered (".gdb_index:");
4086   if (dwarf2_per_objfile->index_table != NULL)
4087     {
4088       printf_filtered (" version %d\n",
4089                        dwarf2_per_objfile->index_table->version);
4090     }
4091   else
4092     printf_filtered (" faked for \"readnow\"\n");
4093   printf_filtered ("\n");
4094 }
4095
4096 static void
4097 dw2_relocate (struct objfile *objfile,
4098               const struct section_offsets *new_offsets,
4099               const struct section_offsets *delta)
4100 {
4101   /* There's nothing to relocate here.  */
4102 }
4103
4104 static void
4105 dw2_expand_symtabs_for_function (struct objfile *objfile,
4106                                  const char *func_name)
4107 {
4108   struct dwarf2_per_objfile *dwarf2_per_objfile
4109     = get_dwarf2_per_objfile (objfile);
4110
4111   struct dw2_symtab_iterator iter;
4112   struct dwarf2_per_cu_data *per_cu;
4113
4114   /* Note: It doesn't matter what we pass for block_index here.  */
4115   dw2_symtab_iter_init (&iter, dwarf2_per_objfile, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4116                         func_name);
4117
4118   while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4119     dw2_instantiate_symtab (per_cu, false);
4120
4121 }
4122
4123 static void
4124 dw2_expand_all_symtabs (struct objfile *objfile)
4125 {
4126   struct dwarf2_per_objfile *dwarf2_per_objfile
4127     = get_dwarf2_per_objfile (objfile);
4128   int total_units = (dwarf2_per_objfile->all_comp_units.size ()
4129                      + dwarf2_per_objfile->all_type_units.size ());
4130
4131   for (int i = 0; i < total_units; ++i)
4132     {
4133       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
4134
4135       /* We don't want to directly expand a partial CU, because if we
4136          read it with the wrong language, then assertion failures can
4137          be triggered later on.  See PR symtab/23010.  So, tell
4138          dw2_instantiate_symtab to skip partial CUs -- any important
4139          partial CU will be read via DW_TAG_imported_unit anyway.  */
4140       dw2_instantiate_symtab (per_cu, true);
4141     }
4142 }
4143
4144 static void
4145 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4146                                   const char *fullname)
4147 {
4148   struct dwarf2_per_objfile *dwarf2_per_objfile
4149     = get_dwarf2_per_objfile (objfile);
4150
4151   /* We don't need to consider type units here.
4152      This is only called for examining code, e.g. expand_line_sal.
4153      There can be an order of magnitude (or more) more type units
4154      than comp units, and we avoid them if we can.  */
4155
4156   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
4157     {
4158       /* We only need to look at symtabs not already expanded.  */
4159       if (per_cu->v.quick->compunit_symtab)
4160         continue;
4161
4162       quick_file_names *file_data = dw2_get_file_names (per_cu);
4163       if (file_data == NULL)
4164         continue;
4165
4166       for (int j = 0; j < file_data->num_file_names; ++j)
4167         {
4168           const char *this_fullname = file_data->file_names[j];
4169
4170           if (filename_cmp (this_fullname, fullname) == 0)
4171             {
4172               dw2_instantiate_symtab (per_cu, false);
4173               break;
4174             }
4175         }
4176     }
4177 }
4178
4179 static void
4180 dw2_map_matching_symbols (struct objfile *objfile,
4181                           const char * name, domain_enum domain,
4182                           int global,
4183                           int (*callback) (struct block *,
4184                                            struct symbol *, void *),
4185                           void *data, symbol_name_match_type match,
4186                           symbol_compare_ftype *ordered_compare)
4187 {
4188   /* Currently unimplemented; used for Ada.  The function can be called if the
4189      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4190      does not look for non-Ada symbols this function should just return.  */
4191 }
4192
4193 /* Symbol name matcher for .gdb_index names.
4194
4195    Symbol names in .gdb_index have a few particularities:
4196
4197    - There's no indication of which is the language of each symbol.
4198
4199      Since each language has its own symbol name matching algorithm,
4200      and we don't know which language is the right one, we must match
4201      each symbol against all languages.  This would be a potential
4202      performance problem if it were not mitigated by the
4203      mapped_index::name_components lookup table, which significantly
4204      reduces the number of times we need to call into this matcher,
4205      making it a non-issue.
4206
4207    - Symbol names in the index have no overload (parameter)
4208      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4209      appear as "foo" in the index, for example.
4210
4211      This means that the lookup names passed to the symbol name
4212      matcher functions must have no parameter information either
4213      because (e.g.) symbol search name "foo" does not match
4214      lookup-name "foo(int)" [while swapping search name for lookup
4215      name would match].
4216 */
4217 class gdb_index_symbol_name_matcher
4218 {
4219 public:
4220   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4221   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4222
4223   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4224      Returns true if any matcher matches.  */
4225   bool matches (const char *symbol_name);
4226
4227 private:
4228   /* A reference to the lookup name we're matching against.  */
4229   const lookup_name_info &m_lookup_name;
4230
4231   /* A vector holding all the different symbol name matchers, for all
4232      languages.  */
4233   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4234 };
4235
4236 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4237   (const lookup_name_info &lookup_name)
4238     : m_lookup_name (lookup_name)
4239 {
4240   /* Prepare the vector of comparison functions upfront, to avoid
4241      doing the same work for each symbol.  Care is taken to avoid
4242      matching with the same matcher more than once if/when multiple
4243      languages use the same matcher function.  */
4244   auto &matchers = m_symbol_name_matcher_funcs;
4245   matchers.reserve (nr_languages);
4246
4247   matchers.push_back (default_symbol_name_matcher);
4248
4249   for (int i = 0; i < nr_languages; i++)
4250     {
4251       const language_defn *lang = language_def ((enum language) i);
4252       symbol_name_matcher_ftype *name_matcher
4253         = get_symbol_name_matcher (lang, m_lookup_name);
4254
4255       /* Don't insert the same comparison routine more than once.
4256          Note that we do this linear walk instead of a seemingly
4257          cheaper sorted insert, or use a std::set or something like
4258          that, because relative order of function addresses is not
4259          stable.  This is not a problem in practice because the number
4260          of supported languages is low, and the cost here is tiny
4261          compared to the number of searches we'll do afterwards using
4262          this object.  */
4263       if (name_matcher != default_symbol_name_matcher
4264           && (std::find (matchers.begin (), matchers.end (), name_matcher)
4265               == matchers.end ()))
4266         matchers.push_back (name_matcher);
4267     }
4268 }
4269
4270 bool
4271 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4272 {
4273   for (auto matches_name : m_symbol_name_matcher_funcs)
4274     if (matches_name (symbol_name, m_lookup_name, NULL))
4275       return true;
4276
4277   return false;
4278 }
4279
4280 /* Starting from a search name, return the string that finds the upper
4281    bound of all strings that start with SEARCH_NAME in a sorted name
4282    list.  Returns the empty string to indicate that the upper bound is
4283    the end of the list.  */
4284
4285 static std::string
4286 make_sort_after_prefix_name (const char *search_name)
4287 {
4288   /* When looking to complete "func", we find the upper bound of all
4289      symbols that start with "func" by looking for where we'd insert
4290      the closest string that would follow "func" in lexicographical
4291      order.  Usually, that's "func"-with-last-character-incremented,
4292      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4293      will be UTF-8 multi-byte sequences, but we can't be certain.
4294      Especially mind the 0xff character, which is a valid character in
4295      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4296      rule out compilers allowing it in identifiers.  Note that
4297      conveniently, strcmp/strcasecmp are specified to compare
4298      characters interpreted as unsigned char.  So what we do is treat
4299      the whole string as a base 256 number composed of a sequence of
4300      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4301      to 0, and carries 1 to the following more-significant position.
4302      If the very first character in SEARCH_NAME ends up incremented
4303      and carries/overflows, then the upper bound is the end of the
4304      list.  The string after the empty string is also the empty
4305      string.
4306
4307      Some examples of this operation:
4308
4309        SEARCH_NAME  => "+1" RESULT
4310
4311        "abc"              => "abd"
4312        "ab\xff"           => "ac"
4313        "\xff" "a" "\xff"  => "\xff" "b"
4314        "\xff"             => ""
4315        "\xff\xff"         => ""
4316        ""                 => ""
4317
4318      Then, with these symbols for example:
4319
4320       func
4321       func1
4322       fund
4323
4324      completing "func" looks for symbols between "func" and
4325      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4326      which finds "func" and "func1", but not "fund".
4327
4328      And with:
4329
4330       funcÿ     (Latin1 'ÿ' [0xff])
4331       funcÿ1
4332       fund
4333
4334      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4335      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4336
4337      And with:
4338
4339       ÿÿ        (Latin1 'ÿ' [0xff])
4340       ÿÿ1
4341
4342      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4343      the end of the list.
4344   */
4345   std::string after = search_name;
4346   while (!after.empty () && (unsigned char) after.back () == 0xff)
4347     after.pop_back ();
4348   if (!after.empty ())
4349     after.back () = (unsigned char) after.back () + 1;
4350   return after;
4351 }
4352
4353 /* See declaration.  */
4354
4355 std::pair<std::vector<name_component>::const_iterator,
4356           std::vector<name_component>::const_iterator>
4357 mapped_index_base::find_name_components_bounds
4358   (const lookup_name_info &lookup_name_without_params) const
4359 {
4360   auto *name_cmp
4361     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4362
4363   const char *cplus
4364     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4365
4366   /* Comparison function object for lower_bound that matches against a
4367      given symbol name.  */
4368   auto lookup_compare_lower = [&] (const name_component &elem,
4369                                    const char *name)
4370     {
4371       const char *elem_qualified = this->symbol_name_at (elem.idx);
4372       const char *elem_name = elem_qualified + elem.name_offset;
4373       return name_cmp (elem_name, name) < 0;
4374     };
4375
4376   /* Comparison function object for upper_bound that matches against a
4377      given symbol name.  */
4378   auto lookup_compare_upper = [&] (const char *name,
4379                                    const name_component &elem)
4380     {
4381       const char *elem_qualified = this->symbol_name_at (elem.idx);
4382       const char *elem_name = elem_qualified + elem.name_offset;
4383       return name_cmp (name, elem_name) < 0;
4384     };
4385
4386   auto begin = this->name_components.begin ();
4387   auto end = this->name_components.end ();
4388
4389   /* Find the lower bound.  */
4390   auto lower = [&] ()
4391     {
4392       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4393         return begin;
4394       else
4395         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4396     } ();
4397
4398   /* Find the upper bound.  */
4399   auto upper = [&] ()
4400     {
4401       if (lookup_name_without_params.completion_mode ())
4402         {
4403           /* In completion mode, we want UPPER to point past all
4404              symbols names that have the same prefix.  I.e., with
4405              these symbols, and completing "func":
4406
4407               function        << lower bound
4408               function1
4409               other_function  << upper bound
4410
4411              We find the upper bound by looking for the insertion
4412              point of "func"-with-last-character-incremented,
4413              i.e. "fund".  */
4414           std::string after = make_sort_after_prefix_name (cplus);
4415           if (after.empty ())
4416             return end;
4417           return std::lower_bound (lower, end, after.c_str (),
4418                                    lookup_compare_lower);
4419         }
4420       else
4421         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4422     } ();
4423
4424   return {lower, upper};
4425 }
4426
4427 /* See declaration.  */
4428
4429 void
4430 mapped_index_base::build_name_components ()
4431 {
4432   if (!this->name_components.empty ())
4433     return;
4434
4435   this->name_components_casing = case_sensitivity;
4436   auto *name_cmp
4437     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4438
4439   /* The code below only knows how to break apart components of C++
4440      symbol names (and other languages that use '::' as
4441      namespace/module separator).  If we add support for wild matching
4442      to some language that uses some other operator (E.g., Ada, Go and
4443      D use '.'), then we'll need to try splitting the symbol name
4444      according to that language too.  Note that Ada does support wild
4445      matching, but doesn't currently support .gdb_index.  */
4446   auto count = this->symbol_name_count ();
4447   for (offset_type idx = 0; idx < count; idx++)
4448     {
4449       if (this->symbol_name_slot_invalid (idx))
4450         continue;
4451
4452       const char *name = this->symbol_name_at (idx);
4453
4454       /* Add each name component to the name component table.  */
4455       unsigned int previous_len = 0;
4456       for (unsigned int current_len = cp_find_first_component (name);
4457            name[current_len] != '\0';
4458            current_len += cp_find_first_component (name + current_len))
4459         {
4460           gdb_assert (name[current_len] == ':');
4461           this->name_components.push_back ({previous_len, idx});
4462           /* Skip the '::'.  */
4463           current_len += 2;
4464           previous_len = current_len;
4465         }
4466       this->name_components.push_back ({previous_len, idx});
4467     }
4468
4469   /* Sort name_components elements by name.  */
4470   auto name_comp_compare = [&] (const name_component &left,
4471                                 const name_component &right)
4472     {
4473       const char *left_qualified = this->symbol_name_at (left.idx);
4474       const char *right_qualified = this->symbol_name_at (right.idx);
4475
4476       const char *left_name = left_qualified + left.name_offset;
4477       const char *right_name = right_qualified + right.name_offset;
4478
4479       return name_cmp (left_name, right_name) < 0;
4480     };
4481
4482   std::sort (this->name_components.begin (),
4483              this->name_components.end (),
4484              name_comp_compare);
4485 }
4486
4487 /* Helper for dw2_expand_symtabs_matching that works with a
4488    mapped_index_base instead of the containing objfile.  This is split
4489    to a separate function in order to be able to unit test the
4490    name_components matching using a mock mapped_index_base.  For each
4491    symbol name that matches, calls MATCH_CALLBACK, passing it the
4492    symbol's index in the mapped_index_base symbol table.  */
4493
4494 static void
4495 dw2_expand_symtabs_matching_symbol
4496   (mapped_index_base &index,
4497    const lookup_name_info &lookup_name_in,
4498    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4499    enum search_domain kind,
4500    gdb::function_view<void (offset_type)> match_callback)
4501 {
4502   lookup_name_info lookup_name_without_params
4503     = lookup_name_in.make_ignore_params ();
4504   gdb_index_symbol_name_matcher lookup_name_matcher
4505     (lookup_name_without_params);
4506
4507   /* Build the symbol name component sorted vector, if we haven't
4508      yet.  */
4509   index.build_name_components ();
4510
4511   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4512
4513   /* Now for each symbol name in range, check to see if we have a name
4514      match, and if so, call the MATCH_CALLBACK callback.  */
4515
4516   /* The same symbol may appear more than once in the range though.
4517      E.g., if we're looking for symbols that complete "w", and we have
4518      a symbol named "w1::w2", we'll find the two name components for
4519      that same symbol in the range.  To be sure we only call the
4520      callback once per symbol, we first collect the symbol name
4521      indexes that matched in a temporary vector and ignore
4522      duplicates.  */
4523   std::vector<offset_type> matches;
4524   matches.reserve (std::distance (bounds.first, bounds.second));
4525
4526   for (; bounds.first != bounds.second; ++bounds.first)
4527     {
4528       const char *qualified = index.symbol_name_at (bounds.first->idx);
4529
4530       if (!lookup_name_matcher.matches (qualified)
4531           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4532         continue;
4533
4534       matches.push_back (bounds.first->idx);
4535     }
4536
4537   std::sort (matches.begin (), matches.end ());
4538
4539   /* Finally call the callback, once per match.  */
4540   ULONGEST prev = -1;
4541   for (offset_type idx : matches)
4542     {
4543       if (prev != idx)
4544         {
4545           match_callback (idx);
4546           prev = idx;
4547         }
4548     }
4549
4550   /* Above we use a type wider than idx's for 'prev', since 0 and
4551      (offset_type)-1 are both possible values.  */
4552   static_assert (sizeof (prev) > sizeof (offset_type), "");
4553 }
4554
4555 #if GDB_SELF_TEST
4556
4557 namespace selftests { namespace dw2_expand_symtabs_matching {
4558
4559 /* A mock .gdb_index/.debug_names-like name index table, enough to
4560    exercise dw2_expand_symtabs_matching_symbol, which works with the
4561    mapped_index_base interface.  Builds an index from the symbol list
4562    passed as parameter to the constructor.  */
4563 class mock_mapped_index : public mapped_index_base
4564 {
4565 public:
4566   mock_mapped_index (gdb::array_view<const char *> symbols)
4567     : m_symbol_table (symbols)
4568   {}
4569
4570   DISABLE_COPY_AND_ASSIGN (mock_mapped_index);
4571
4572   /* Return the number of names in the symbol table.  */
4573   size_t symbol_name_count () const override
4574   {
4575     return m_symbol_table.size ();
4576   }
4577
4578   /* Get the name of the symbol at IDX in the symbol table.  */
4579   const char *symbol_name_at (offset_type idx) const override
4580   {
4581     return m_symbol_table[idx];
4582   }
4583
4584 private:
4585   gdb::array_view<const char *> m_symbol_table;
4586 };
4587
4588 /* Convenience function that converts a NULL pointer to a "<null>"
4589    string, to pass to print routines.  */
4590
4591 static const char *
4592 string_or_null (const char *str)
4593 {
4594   return str != NULL ? str : "<null>";
4595 }
4596
4597 /* Check if a lookup_name_info built from
4598    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4599    index.  EXPECTED_LIST is the list of expected matches, in expected
4600    matching order.  If no match expected, then an empty list is
4601    specified.  Returns true on success.  On failure prints a warning
4602    indicating the file:line that failed, and returns false.  */
4603
4604 static bool
4605 check_match (const char *file, int line,
4606              mock_mapped_index &mock_index,
4607              const char *name, symbol_name_match_type match_type,
4608              bool completion_mode,
4609              std::initializer_list<const char *> expected_list)
4610 {
4611   lookup_name_info lookup_name (name, match_type, completion_mode);
4612
4613   bool matched = true;
4614
4615   auto mismatch = [&] (const char *expected_str,
4616                        const char *got)
4617   {
4618     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4619                "expected=\"%s\", got=\"%s\"\n"),
4620              file, line,
4621              (match_type == symbol_name_match_type::FULL
4622               ? "FULL" : "WILD"),
4623              name, string_or_null (expected_str), string_or_null (got));
4624     matched = false;
4625   };
4626
4627   auto expected_it = expected_list.begin ();
4628   auto expected_end = expected_list.end ();
4629
4630   dw2_expand_symtabs_matching_symbol (mock_index, lookup_name,
4631                                       NULL, ALL_DOMAIN,
4632                                       [&] (offset_type idx)
4633   {
4634     const char *matched_name = mock_index.symbol_name_at (idx);
4635     const char *expected_str
4636       = expected_it == expected_end ? NULL : *expected_it++;
4637
4638     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4639       mismatch (expected_str, matched_name);
4640   });
4641
4642   const char *expected_str
4643   = expected_it == expected_end ? NULL : *expected_it++;
4644   if (expected_str != NULL)
4645     mismatch (expected_str, NULL);
4646
4647   return matched;
4648 }
4649
4650 /* The symbols added to the mock mapped_index for testing (in
4651    canonical form).  */
4652 static const char *test_symbols[] = {
4653   "function",
4654   "std::bar",
4655   "std::zfunction",
4656   "std::zfunction2",
4657   "w1::w2",
4658   "ns::foo<char*>",
4659   "ns::foo<int>",
4660   "ns::foo<long>",
4661   "ns2::tmpl<int>::foo2",
4662   "(anonymous namespace)::A::B::C",
4663
4664   /* These are used to check that the increment-last-char in the
4665      matching algorithm for completion doesn't match "t1_fund" when
4666      completing "t1_func".  */
4667   "t1_func",
4668   "t1_func1",
4669   "t1_fund",
4670   "t1_fund1",
4671
4672   /* A UTF-8 name with multi-byte sequences to make sure that
4673      cp-name-parser understands this as a single identifier ("função"
4674      is "function" in PT).  */
4675   u8"u8função",
4676
4677   /* \377 (0xff) is Latin1 'ÿ'.  */
4678   "yfunc\377",
4679
4680   /* \377 (0xff) is Latin1 'ÿ'.  */
4681   "\377",
4682   "\377\377123",
4683
4684   /* A name with all sorts of complications.  Starts with "z" to make
4685      it easier for the completion tests below.  */
4686 #define Z_SYM_NAME \
4687   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4688     "::tuple<(anonymous namespace)::ui*, " \
4689     "std::default_delete<(anonymous namespace)::ui>, void>"
4690
4691   Z_SYM_NAME
4692 };
4693
4694 /* Returns true if the mapped_index_base::find_name_component_bounds
4695    method finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME,
4696    in completion mode.  */
4697
4698 static bool
4699 check_find_bounds_finds (mapped_index_base &index,
4700                          const char *search_name,
4701                          gdb::array_view<const char *> expected_syms)
4702 {
4703   lookup_name_info lookup_name (search_name,
4704                                 symbol_name_match_type::FULL, true);
4705
4706   auto bounds = index.find_name_components_bounds (lookup_name);
4707
4708   size_t distance = std::distance (bounds.first, bounds.second);
4709   if (distance != expected_syms.size ())
4710     return false;
4711
4712   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4713     {
4714       auto nc_elem = bounds.first + exp_elem;
4715       const char *qualified = index.symbol_name_at (nc_elem->idx);
4716       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4717         return false;
4718     }
4719
4720   return true;
4721 }
4722
4723 /* Test the lower-level mapped_index::find_name_component_bounds
4724    method.  */
4725
4726 static void
4727 test_mapped_index_find_name_component_bounds ()
4728 {
4729   mock_mapped_index mock_index (test_symbols);
4730
4731   mock_index.build_name_components ();
4732
4733   /* Test the lower-level mapped_index::find_name_component_bounds
4734      method in completion mode.  */
4735   {
4736     static const char *expected_syms[] = {
4737       "t1_func",
4738       "t1_func1",
4739     };
4740
4741     SELF_CHECK (check_find_bounds_finds (mock_index,
4742                                          "t1_func", expected_syms));
4743   }
4744
4745   /* Check that the increment-last-char in the name matching algorithm
4746      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4747   {
4748     static const char *expected_syms1[] = {
4749       "\377",
4750       "\377\377123",
4751     };
4752     SELF_CHECK (check_find_bounds_finds (mock_index,
4753                                          "\377", expected_syms1));
4754
4755     static const char *expected_syms2[] = {
4756       "\377\377123",
4757     };
4758     SELF_CHECK (check_find_bounds_finds (mock_index,
4759                                          "\377\377", expected_syms2));
4760   }
4761 }
4762
4763 /* Test dw2_expand_symtabs_matching_symbol.  */
4764
4765 static void
4766 test_dw2_expand_symtabs_matching_symbol ()
4767 {
4768   mock_mapped_index mock_index (test_symbols);
4769
4770   /* We let all tests run until the end even if some fails, for debug
4771      convenience.  */
4772   bool any_mismatch = false;
4773
4774   /* Create the expected symbols list (an initializer_list).  Needed
4775      because lists have commas, and we need to pass them to CHECK,
4776      which is a macro.  */
4777 #define EXPECT(...) { __VA_ARGS__ }
4778
4779   /* Wrapper for check_match that passes down the current
4780      __FILE__/__LINE__.  */
4781 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4782   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4783                                 mock_index,                             \
4784                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4785                                 EXPECTED_LIST)
4786
4787   /* Identity checks.  */
4788   for (const char *sym : test_symbols)
4789     {
4790       /* Should be able to match all existing symbols.  */
4791       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4792                    EXPECT (sym));
4793
4794       /* Should be able to match all existing symbols with
4795          parameters.  */
4796       std::string with_params = std::string (sym) + "(int)";
4797       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4798                    EXPECT (sym));
4799
4800       /* Should be able to match all existing symbols with
4801          parameters and qualifiers.  */
4802       with_params = std::string (sym) + " ( int ) const";
4803       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4804                    EXPECT (sym));
4805
4806       /* This should really find sym, but cp-name-parser.y doesn't
4807          know about lvalue/rvalue qualifiers yet.  */
4808       with_params = std::string (sym) + " ( int ) &&";
4809       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4810                    {});
4811     }
4812
4813   /* Check that the name matching algorithm for completion doesn't get
4814      confused with Latin1 'ÿ' / 0xff.  */
4815   {
4816     static const char str[] = "\377";
4817     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4818                  EXPECT ("\377", "\377\377123"));
4819   }
4820
4821   /* Check that the increment-last-char in the matching algorithm for
4822      completion doesn't match "t1_fund" when completing "t1_func".  */
4823   {
4824     static const char str[] = "t1_func";
4825     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4826                  EXPECT ("t1_func", "t1_func1"));
4827   }
4828
4829   /* Check that completion mode works at each prefix of the expected
4830      symbol name.  */
4831   {
4832     static const char str[] = "function(int)";
4833     size_t len = strlen (str);
4834     std::string lookup;
4835
4836     for (size_t i = 1; i < len; i++)
4837       {
4838         lookup.assign (str, i);
4839         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4840                      EXPECT ("function"));
4841       }
4842   }
4843
4844   /* While "w" is a prefix of both components, the match function
4845      should still only be called once.  */
4846   {
4847     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4848                  EXPECT ("w1::w2"));
4849     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4850                  EXPECT ("w1::w2"));
4851   }
4852
4853   /* Same, with a "complicated" symbol.  */
4854   {
4855     static const char str[] = Z_SYM_NAME;
4856     size_t len = strlen (str);
4857     std::string lookup;
4858
4859     for (size_t i = 1; i < len; i++)
4860       {
4861         lookup.assign (str, i);
4862         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4863                      EXPECT (Z_SYM_NAME));
4864       }
4865   }
4866
4867   /* In FULL mode, an incomplete symbol doesn't match.  */
4868   {
4869     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4870                  {});
4871   }
4872
4873   /* A complete symbol with parameters matches any overload, since the
4874      index has no overload info.  */
4875   {
4876     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4877                  EXPECT ("std::zfunction", "std::zfunction2"));
4878     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4879                  EXPECT ("std::zfunction", "std::zfunction2"));
4880     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4881                  EXPECT ("std::zfunction", "std::zfunction2"));
4882   }
4883
4884   /* Check that whitespace is ignored appropriately.  A symbol with a
4885      template argument list. */
4886   {
4887     static const char expected[] = "ns::foo<int>";
4888     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4889                  EXPECT (expected));
4890     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4891                  EXPECT (expected));
4892   }
4893
4894   /* Check that whitespace is ignored appropriately.  A symbol with a
4895      template argument list that includes a pointer.  */
4896   {
4897     static const char expected[] = "ns::foo<char*>";
4898     /* Try both completion and non-completion modes.  */
4899     static const bool completion_mode[2] = {false, true};
4900     for (size_t i = 0; i < 2; i++)
4901       {
4902         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4903                      completion_mode[i], EXPECT (expected));
4904         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4905                      completion_mode[i], EXPECT (expected));
4906
4907         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4908                      completion_mode[i], EXPECT (expected));
4909         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4910                      completion_mode[i], EXPECT (expected));
4911       }
4912   }
4913
4914   {
4915     /* Check method qualifiers are ignored.  */
4916     static const char expected[] = "ns::foo<char*>";
4917     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4918                  symbol_name_match_type::FULL, true, EXPECT (expected));
4919     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4920                  symbol_name_match_type::FULL, true, EXPECT (expected));
4921     CHECK_MATCH ("foo < char * >  ( int ) const",
4922                  symbol_name_match_type::WILD, true, EXPECT (expected));
4923     CHECK_MATCH ("foo < char * >  ( int ) &&",
4924                  symbol_name_match_type::WILD, true, EXPECT (expected));
4925   }
4926
4927   /* Test lookup names that don't match anything.  */
4928   {
4929     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4930                  {});
4931
4932     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4933                  {});
4934   }
4935
4936   /* Some wild matching tests, exercising "(anonymous namespace)",
4937      which should not be confused with a parameter list.  */
4938   {
4939     static const char *syms[] = {
4940       "A::B::C",
4941       "B::C",
4942       "C",
4943       "A :: B :: C ( int )",
4944       "B :: C ( int )",
4945       "C ( int )",
4946     };
4947
4948     for (const char *s : syms)
4949       {
4950         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4951                      EXPECT ("(anonymous namespace)::A::B::C"));
4952       }
4953   }
4954
4955   {
4956     static const char expected[] = "ns2::tmpl<int>::foo2";
4957     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4958                  EXPECT (expected));
4959     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4960                  EXPECT (expected));
4961   }
4962
4963   SELF_CHECK (!any_mismatch);
4964
4965 #undef EXPECT
4966 #undef CHECK_MATCH
4967 }
4968
4969 static void
4970 run_test ()
4971 {
4972   test_mapped_index_find_name_component_bounds ();
4973   test_dw2_expand_symtabs_matching_symbol ();
4974 }
4975
4976 }} // namespace selftests::dw2_expand_symtabs_matching
4977
4978 #endif /* GDB_SELF_TEST */
4979
4980 /* If FILE_MATCHER is NULL or if PER_CU has
4981    dwarf2_per_cu_quick_data::MARK set (see
4982    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4983    EXPANSION_NOTIFY on it.  */
4984
4985 static void
4986 dw2_expand_symtabs_matching_one
4987   (struct dwarf2_per_cu_data *per_cu,
4988    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4989    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4990 {
4991   if (file_matcher == NULL || per_cu->v.quick->mark)
4992     {
4993       bool symtab_was_null
4994         = (per_cu->v.quick->compunit_symtab == NULL);
4995
4996       dw2_instantiate_symtab (per_cu, false);
4997
4998       if (expansion_notify != NULL
4999           && symtab_was_null
5000           && per_cu->v.quick->compunit_symtab != NULL)
5001         expansion_notify (per_cu->v.quick->compunit_symtab);
5002     }
5003 }
5004
5005 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
5006    matched, to expand corresponding CUs that were marked.  IDX is the
5007    index of the symbol name that matched.  */
5008
5009 static void
5010 dw2_expand_marked_cus
5011   (struct dwarf2_per_objfile *dwarf2_per_objfile, offset_type idx,
5012    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5013    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5014    search_domain kind)
5015 {
5016   offset_type *vec, vec_len, vec_idx;
5017   bool global_seen = false;
5018   mapped_index &index = *dwarf2_per_objfile->index_table;
5019
5020   vec = (offset_type *) (index.constant_pool
5021                          + MAYBE_SWAP (index.symbol_table[idx].vec));
5022   vec_len = MAYBE_SWAP (vec[0]);
5023   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5024     {
5025       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5026       /* This value is only valid for index versions >= 7.  */
5027       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5028       gdb_index_symbol_kind symbol_kind =
5029         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5030       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5031       /* Only check the symbol attributes if they're present.
5032          Indices prior to version 7 don't record them,
5033          and indices >= 7 may elide them for certain symbols
5034          (gold does this).  */
5035       int attrs_valid =
5036         (index.version >= 7
5037          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5038
5039       /* Work around gold/15646.  */
5040       if (attrs_valid)
5041         {
5042           if (!is_static && global_seen)
5043             continue;
5044           if (!is_static)
5045             global_seen = true;
5046         }
5047
5048       /* Only check the symbol's kind if it has one.  */
5049       if (attrs_valid)
5050         {
5051           switch (kind)
5052             {
5053             case VARIABLES_DOMAIN:
5054               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5055                 continue;
5056               break;
5057             case FUNCTIONS_DOMAIN:
5058               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5059                 continue;
5060               break;
5061             case TYPES_DOMAIN:
5062               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5063                 continue;
5064               break;
5065             default:
5066               break;
5067             }
5068         }
5069
5070       /* Don't crash on bad data.  */
5071       if (cu_index >= (dwarf2_per_objfile->all_comp_units.size ()
5072                        + dwarf2_per_objfile->all_type_units.size ()))
5073         {
5074           complaint (_(".gdb_index entry has bad CU index"
5075                        " [in module %s]"),
5076                        objfile_name (dwarf2_per_objfile->objfile));
5077           continue;
5078         }
5079
5080       dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (cu_index);
5081       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5082                                        expansion_notify);
5083     }
5084 }
5085
5086 /* If FILE_MATCHER is non-NULL, set all the
5087    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5088    that match FILE_MATCHER.  */
5089
5090 static void
5091 dw_expand_symtabs_matching_file_matcher
5092   (struct dwarf2_per_objfile *dwarf2_per_objfile,
5093    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5094 {
5095   if (file_matcher == NULL)
5096     return;
5097
5098   objfile *const objfile = dwarf2_per_objfile->objfile;
5099
5100   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5101                                             htab_eq_pointer,
5102                                             NULL, xcalloc, xfree));
5103   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5104                                                 htab_eq_pointer,
5105                                                 NULL, xcalloc, xfree));
5106
5107   /* The rule is CUs specify all the files, including those used by
5108      any TU, so there's no need to scan TUs here.  */
5109
5110   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5111     {
5112       QUIT;
5113
5114       per_cu->v.quick->mark = 0;
5115
5116       /* We only need to look at symtabs not already expanded.  */
5117       if (per_cu->v.quick->compunit_symtab)
5118         continue;
5119
5120       quick_file_names *file_data = dw2_get_file_names (per_cu);
5121       if (file_data == NULL)
5122         continue;
5123
5124       if (htab_find (visited_not_found.get (), file_data) != NULL)
5125         continue;
5126       else if (htab_find (visited_found.get (), file_data) != NULL)
5127         {
5128           per_cu->v.quick->mark = 1;
5129           continue;
5130         }
5131
5132       for (int j = 0; j < file_data->num_file_names; ++j)
5133         {
5134           const char *this_real_name;
5135
5136           if (file_matcher (file_data->file_names[j], false))
5137             {
5138               per_cu->v.quick->mark = 1;
5139               break;
5140             }
5141
5142           /* Before we invoke realpath, which can get expensive when many
5143              files are involved, do a quick comparison of the basenames.  */
5144           if (!basenames_may_differ
5145               && !file_matcher (lbasename (file_data->file_names[j]),
5146                                 true))
5147             continue;
5148
5149           this_real_name = dw2_get_real_path (objfile, file_data, j);
5150           if (file_matcher (this_real_name, false))
5151             {
5152               per_cu->v.quick->mark = 1;
5153               break;
5154             }
5155         }
5156
5157       void **slot = htab_find_slot (per_cu->v.quick->mark
5158                                     ? visited_found.get ()
5159                                     : visited_not_found.get (),
5160                                     file_data, INSERT);
5161       *slot = file_data;
5162     }
5163 }
5164
5165 static void
5166 dw2_expand_symtabs_matching
5167   (struct objfile *objfile,
5168    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5169    const lookup_name_info &lookup_name,
5170    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5171    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5172    enum search_domain kind)
5173 {
5174   struct dwarf2_per_objfile *dwarf2_per_objfile
5175     = get_dwarf2_per_objfile (objfile);
5176
5177   /* index_table is NULL if OBJF_READNOW.  */
5178   if (!dwarf2_per_objfile->index_table)
5179     return;
5180
5181   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
5182
5183   mapped_index &index = *dwarf2_per_objfile->index_table;
5184
5185   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5186                                       symbol_matcher,
5187                                       kind, [&] (offset_type idx)
5188     {
5189       dw2_expand_marked_cus (dwarf2_per_objfile, idx, file_matcher,
5190                              expansion_notify, kind);
5191     });
5192 }
5193
5194 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5195    symtab.  */
5196
5197 static struct compunit_symtab *
5198 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5199                                           CORE_ADDR pc)
5200 {
5201   int i;
5202
5203   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5204       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5205     return cust;
5206
5207   if (cust->includes == NULL)
5208     return NULL;
5209
5210   for (i = 0; cust->includes[i]; ++i)
5211     {
5212       struct compunit_symtab *s = cust->includes[i];
5213
5214       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5215       if (s != NULL)
5216         return s;
5217     }
5218
5219   return NULL;
5220 }
5221
5222 static struct compunit_symtab *
5223 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5224                                   struct bound_minimal_symbol msymbol,
5225                                   CORE_ADDR pc,
5226                                   struct obj_section *section,
5227                                   int warn_if_readin)
5228 {
5229   struct dwarf2_per_cu_data *data;
5230   struct compunit_symtab *result;
5231
5232   if (!objfile->psymtabs_addrmap)
5233     return NULL;
5234
5235   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5236                                                      pc);
5237   if (!data)
5238     return NULL;
5239
5240   if (warn_if_readin && data->v.quick->compunit_symtab)
5241     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5242              paddress (get_objfile_arch (objfile), pc));
5243
5244   result
5245     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data,
5246                                                                         false),
5247                                                 pc);
5248   gdb_assert (result != NULL);
5249   return result;
5250 }
5251
5252 static void
5253 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5254                           void *data, int need_fullname)
5255 {
5256   struct dwarf2_per_objfile *dwarf2_per_objfile
5257     = get_dwarf2_per_objfile (objfile);
5258
5259   if (!dwarf2_per_objfile->filenames_cache)
5260     {
5261       dwarf2_per_objfile->filenames_cache.emplace ();
5262
5263       htab_up visited (htab_create_alloc (10,
5264                                           htab_hash_pointer, htab_eq_pointer,
5265                                           NULL, xcalloc, xfree));
5266
5267       /* The rule is CUs specify all the files, including those used
5268          by any TU, so there's no need to scan TUs here.  We can
5269          ignore file names coming from already-expanded CUs.  */
5270
5271       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5272         {
5273           if (per_cu->v.quick->compunit_symtab)
5274             {
5275               void **slot = htab_find_slot (visited.get (),
5276                                             per_cu->v.quick->file_names,
5277                                             INSERT);
5278
5279               *slot = per_cu->v.quick->file_names;
5280             }
5281         }
5282
5283       for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
5284         {
5285           /* We only need to look at symtabs not already expanded.  */
5286           if (per_cu->v.quick->compunit_symtab)
5287             continue;
5288
5289           quick_file_names *file_data = dw2_get_file_names (per_cu);
5290           if (file_data == NULL)
5291             continue;
5292
5293           void **slot = htab_find_slot (visited.get (), file_data, INSERT);
5294           if (*slot)
5295             {
5296               /* Already visited.  */
5297               continue;
5298             }
5299           *slot = file_data;
5300
5301           for (int j = 0; j < file_data->num_file_names; ++j)
5302             {
5303               const char *filename = file_data->file_names[j];
5304               dwarf2_per_objfile->filenames_cache->seen (filename);
5305             }
5306         }
5307     }
5308
5309   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5310     {
5311       gdb::unique_xmalloc_ptr<char> this_real_name;
5312
5313       if (need_fullname)
5314         this_real_name = gdb_realpath (filename);
5315       (*fun) (filename, this_real_name.get (), data);
5316     });
5317 }
5318
5319 static int
5320 dw2_has_symbols (struct objfile *objfile)
5321 {
5322   return 1;
5323 }
5324
5325 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5326 {
5327   dw2_has_symbols,
5328   dw2_find_last_source_symtab,
5329   dw2_forget_cached_source_info,
5330   dw2_map_symtabs_matching_filename,
5331   dw2_lookup_symbol,
5332   dw2_print_stats,
5333   dw2_dump,
5334   dw2_relocate,
5335   dw2_expand_symtabs_for_function,
5336   dw2_expand_all_symtabs,
5337   dw2_expand_symtabs_with_fullname,
5338   dw2_map_matching_symbols,
5339   dw2_expand_symtabs_matching,
5340   dw2_find_pc_sect_compunit_symtab,
5341   NULL,
5342   dw2_map_symbol_filenames
5343 };
5344
5345 /* DWARF-5 debug_names reader.  */
5346
5347 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
5348 static const gdb_byte dwarf5_augmentation[] = { 'G', 'D', 'B', 0 };
5349
5350 /* A helper function that reads the .debug_names section in SECTION
5351    and fills in MAP.  FILENAME is the name of the file containing the
5352    section; it is used for error reporting.
5353
5354    Returns true if all went well, false otherwise.  */
5355
5356 static bool
5357 read_debug_names_from_section (struct objfile *objfile,
5358                                const char *filename,
5359                                struct dwarf2_section_info *section,
5360                                mapped_debug_names &map)
5361 {
5362   if (dwarf2_section_empty_p (section))
5363     return false;
5364
5365   /* Older elfutils strip versions could keep the section in the main
5366      executable while splitting it for the separate debug info file.  */
5367   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
5368     return false;
5369
5370   dwarf2_read_section (objfile, section);
5371
5372   map.dwarf5_byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
5373
5374   const gdb_byte *addr = section->buffer;
5375
5376   bfd *const abfd = get_section_bfd_owner (section);
5377
5378   unsigned int bytes_read;
5379   LONGEST length = read_initial_length (abfd, addr, &bytes_read);
5380   addr += bytes_read;
5381
5382   map.dwarf5_is_dwarf64 = bytes_read != 4;
5383   map.offset_size = map.dwarf5_is_dwarf64 ? 8 : 4;
5384   if (bytes_read + length != section->size)
5385     {
5386       /* There may be multiple per-CU indices.  */
5387       warning (_("Section .debug_names in %s length %s does not match "
5388                  "section length %s, ignoring .debug_names."),
5389                filename, plongest (bytes_read + length),
5390                pulongest (section->size));
5391       return false;
5392     }
5393
5394   /* The version number.  */
5395   uint16_t version = read_2_bytes (abfd, addr);
5396   addr += 2;
5397   if (version != 5)
5398     {
5399       warning (_("Section .debug_names in %s has unsupported version %d, "
5400                  "ignoring .debug_names."),
5401                filename, version);
5402       return false;
5403     }
5404
5405   /* Padding.  */
5406   uint16_t padding = read_2_bytes (abfd, addr);
5407   addr += 2;
5408   if (padding != 0)
5409     {
5410       warning (_("Section .debug_names in %s has unsupported padding %d, "
5411                  "ignoring .debug_names."),
5412                filename, padding);
5413       return false;
5414     }
5415
5416   /* comp_unit_count - The number of CUs in the CU list.  */
5417   map.cu_count = read_4_bytes (abfd, addr);
5418   addr += 4;
5419
5420   /* local_type_unit_count - The number of TUs in the local TU
5421      list.  */
5422   map.tu_count = read_4_bytes (abfd, addr);
5423   addr += 4;
5424
5425   /* foreign_type_unit_count - The number of TUs in the foreign TU
5426      list.  */
5427   uint32_t foreign_tu_count = read_4_bytes (abfd, addr);
5428   addr += 4;
5429   if (foreign_tu_count != 0)
5430     {
5431       warning (_("Section .debug_names in %s has unsupported %lu foreign TUs, "
5432                  "ignoring .debug_names."),
5433                filename, static_cast<unsigned long> (foreign_tu_count));
5434       return false;
5435     }
5436
5437   /* bucket_count - The number of hash buckets in the hash lookup
5438      table.  */
5439   map.bucket_count = read_4_bytes (abfd, addr);
5440   addr += 4;
5441
5442   /* name_count - The number of unique names in the index.  */
5443   map.name_count = read_4_bytes (abfd, addr);
5444   addr += 4;
5445
5446   /* abbrev_table_size - The size in bytes of the abbreviations
5447      table.  */
5448   uint32_t abbrev_table_size = read_4_bytes (abfd, addr);
5449   addr += 4;
5450
5451   /* augmentation_string_size - The size in bytes of the augmentation
5452      string.  This value is rounded up to a multiple of 4.  */
5453   uint32_t augmentation_string_size = read_4_bytes (abfd, addr);
5454   addr += 4;
5455   map.augmentation_is_gdb = ((augmentation_string_size
5456                               == sizeof (dwarf5_augmentation))
5457                              && memcmp (addr, dwarf5_augmentation,
5458                                         sizeof (dwarf5_augmentation)) == 0);
5459   augmentation_string_size += (-augmentation_string_size) & 3;
5460   addr += augmentation_string_size;
5461
5462   /* List of CUs */
5463   map.cu_table_reordered = addr;
5464   addr += map.cu_count * map.offset_size;
5465
5466   /* List of Local TUs */
5467   map.tu_table_reordered = addr;
5468   addr += map.tu_count * map.offset_size;
5469
5470   /* Hash Lookup Table */
5471   map.bucket_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5472   addr += map.bucket_count * 4;
5473   map.hash_table_reordered = reinterpret_cast<const uint32_t *> (addr);
5474   addr += map.name_count * 4;
5475
5476   /* Name Table */
5477   map.name_table_string_offs_reordered = addr;
5478   addr += map.name_count * map.offset_size;
5479   map.name_table_entry_offs_reordered = addr;
5480   addr += map.name_count * map.offset_size;
5481
5482   const gdb_byte *abbrev_table_start = addr;
5483   for (;;)
5484     {
5485       unsigned int bytes_read;
5486       const ULONGEST index_num = read_unsigned_leb128 (abfd, addr, &bytes_read);
5487       addr += bytes_read;
5488       if (index_num == 0)
5489         break;
5490
5491       const auto insertpair
5492         = map.abbrev_map.emplace (index_num, mapped_debug_names::index_val ());
5493       if (!insertpair.second)
5494         {
5495           warning (_("Section .debug_names in %s has duplicate index %s, "
5496                      "ignoring .debug_names."),
5497                    filename, pulongest (index_num));
5498           return false;
5499         }
5500       mapped_debug_names::index_val &indexval = insertpair.first->second;
5501       indexval.dwarf_tag = read_unsigned_leb128 (abfd, addr, &bytes_read);
5502       addr += bytes_read;
5503
5504       for (;;)
5505         {
5506           mapped_debug_names::index_val::attr attr;
5507           attr.dw_idx = read_unsigned_leb128 (abfd, addr, &bytes_read);
5508           addr += bytes_read;
5509           attr.form = read_unsigned_leb128 (abfd, addr, &bytes_read);
5510           addr += bytes_read;
5511           if (attr.form == DW_FORM_implicit_const)
5512             {
5513               attr.implicit_const = read_signed_leb128 (abfd, addr,
5514                                                         &bytes_read);
5515               addr += bytes_read;
5516             }
5517           if (attr.dw_idx == 0 && attr.form == 0)
5518             break;
5519           indexval.attr_vec.push_back (std::move (attr));
5520         }
5521     }
5522   if (addr != abbrev_table_start + abbrev_table_size)
5523     {
5524       warning (_("Section .debug_names in %s has abbreviation_table "
5525                  "of size %zu vs. written as %u, ignoring .debug_names."),
5526                filename, addr - abbrev_table_start, abbrev_table_size);
5527       return false;
5528     }
5529   map.entry_pool = addr;
5530
5531   return true;
5532 }
5533
5534 /* A helper for create_cus_from_debug_names that handles the MAP's CU
5535    list.  */
5536
5537 static void
5538 create_cus_from_debug_names_list (struct dwarf2_per_objfile *dwarf2_per_objfile,
5539                                   const mapped_debug_names &map,
5540                                   dwarf2_section_info &section,
5541                                   bool is_dwz)
5542 {
5543   sect_offset sect_off_prev;
5544   for (uint32_t i = 0; i <= map.cu_count; ++i)
5545     {
5546       sect_offset sect_off_next;
5547       if (i < map.cu_count)
5548         {
5549           sect_off_next
5550             = (sect_offset) (extract_unsigned_integer
5551                              (map.cu_table_reordered + i * map.offset_size,
5552                               map.offset_size,
5553                               map.dwarf5_byte_order));
5554         }
5555       else
5556         sect_off_next = (sect_offset) section.size;
5557       if (i >= 1)
5558         {
5559           const ULONGEST length = sect_off_next - sect_off_prev;
5560           dwarf2_per_cu_data *per_cu
5561             = create_cu_from_index_list (dwarf2_per_objfile, &section, is_dwz,
5562                                          sect_off_prev, length);
5563           dwarf2_per_objfile->all_comp_units.push_back (per_cu);
5564         }
5565       sect_off_prev = sect_off_next;
5566     }
5567 }
5568
5569 /* Read the CU list from the mapped index, and use it to create all
5570    the CU objects for this dwarf2_per_objfile.  */
5571
5572 static void
5573 create_cus_from_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile,
5574                              const mapped_debug_names &map,
5575                              const mapped_debug_names &dwz_map)
5576 {
5577   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
5578   dwarf2_per_objfile->all_comp_units.reserve (map.cu_count + dwz_map.cu_count);
5579
5580   create_cus_from_debug_names_list (dwarf2_per_objfile, map,
5581                                     dwarf2_per_objfile->info,
5582                                     false /* is_dwz */);
5583
5584   if (dwz_map.cu_count == 0)
5585     return;
5586
5587   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5588   create_cus_from_debug_names_list (dwarf2_per_objfile, dwz_map, dwz->info,
5589                                     true /* is_dwz */);
5590 }
5591
5592 /* Read .debug_names.  If everything went ok, initialize the "quick"
5593    elements of all the CUs and return true.  Otherwise, return false.  */
5594
5595 static bool
5596 dwarf2_read_debug_names (struct dwarf2_per_objfile *dwarf2_per_objfile)
5597 {
5598   std::unique_ptr<mapped_debug_names> map
5599     (new mapped_debug_names (dwarf2_per_objfile));
5600   mapped_debug_names dwz_map (dwarf2_per_objfile);
5601   struct objfile *objfile = dwarf2_per_objfile->objfile;
5602
5603   if (!read_debug_names_from_section (objfile, objfile_name (objfile),
5604                                       &dwarf2_per_objfile->debug_names,
5605                                       *map))
5606     return false;
5607
5608   /* Don't use the index if it's empty.  */
5609   if (map->name_count == 0)
5610     return false;
5611
5612   /* If there is a .dwz file, read it so we can get its CU list as
5613      well.  */
5614   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
5615   if (dwz != NULL)
5616     {
5617       if (!read_debug_names_from_section (objfile,
5618                                           bfd_get_filename (dwz->dwz_bfd),
5619                                           &dwz->debug_names, dwz_map))
5620         {
5621           warning (_("could not read '.debug_names' section from %s; skipping"),
5622                    bfd_get_filename (dwz->dwz_bfd));
5623           return false;
5624         }
5625     }
5626
5627   create_cus_from_debug_names (dwarf2_per_objfile, *map, dwz_map);
5628
5629   if (map->tu_count != 0)
5630     {
5631       /* We can only handle a single .debug_types when we have an
5632          index.  */
5633       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
5634         return false;
5635
5636       dwarf2_section_info *section = VEC_index (dwarf2_section_info_def,
5637                                                 dwarf2_per_objfile->types, 0);
5638
5639       create_signatured_type_table_from_debug_names
5640         (dwarf2_per_objfile, *map, section, &dwarf2_per_objfile->abbrev);
5641     }
5642
5643   create_addrmap_from_aranges (dwarf2_per_objfile,
5644                                &dwarf2_per_objfile->debug_aranges);
5645
5646   dwarf2_per_objfile->debug_names_table = std::move (map);
5647   dwarf2_per_objfile->using_index = 1;
5648   dwarf2_per_objfile->quick_file_names_table =
5649     create_quick_file_names_table (dwarf2_per_objfile->all_comp_units.size ());
5650
5651   return true;
5652 }
5653
5654 /* Type used to manage iterating over all CUs looking for a symbol for
5655    .debug_names.  */
5656
5657 class dw2_debug_names_iterator
5658 {
5659 public:
5660   /* If WANT_SPECIFIC_BLOCK is true, only look for symbols in block
5661      BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
5662   dw2_debug_names_iterator (const mapped_debug_names &map,
5663                             bool want_specific_block,
5664                             block_enum block_index, domain_enum domain,
5665                             const char *name)
5666     : m_map (map), m_want_specific_block (want_specific_block),
5667       m_block_index (block_index), m_domain (domain),
5668       m_addr (find_vec_in_debug_names (map, name))
5669   {}
5670
5671   dw2_debug_names_iterator (const mapped_debug_names &map,
5672                             search_domain search, uint32_t namei)
5673     : m_map (map),
5674       m_search (search),
5675       m_addr (find_vec_in_debug_names (map, namei))
5676   {}
5677
5678   /* Return the next matching CU or NULL if there are no more.  */
5679   dwarf2_per_cu_data *next ();
5680
5681 private:
5682   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5683                                                   const char *name);
5684   static const gdb_byte *find_vec_in_debug_names (const mapped_debug_names &map,
5685                                                   uint32_t namei);
5686
5687   /* The internalized form of .debug_names.  */
5688   const mapped_debug_names &m_map;
5689
5690   /* If true, only look for symbols that match BLOCK_INDEX.  */
5691   const bool m_want_specific_block = false;
5692
5693   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
5694      Unused if !WANT_SPECIFIC_BLOCK - FIRST_LOCAL_BLOCK is an invalid
5695      value.  */
5696   const block_enum m_block_index = FIRST_LOCAL_BLOCK;
5697
5698   /* The kind of symbol we're looking for.  */
5699   const domain_enum m_domain = UNDEF_DOMAIN;
5700   const search_domain m_search = ALL_DOMAIN;
5701
5702   /* The list of CUs from the index entry of the symbol, or NULL if
5703      not found.  */
5704   const gdb_byte *m_addr;
5705 };
5706
5707 const char *
5708 mapped_debug_names::namei_to_name (uint32_t namei) const
5709 {
5710   const ULONGEST namei_string_offs
5711     = extract_unsigned_integer ((name_table_string_offs_reordered
5712                                  + namei * offset_size),
5713                                 offset_size,
5714                                 dwarf5_byte_order);
5715   return read_indirect_string_at_offset
5716     (dwarf2_per_objfile, dwarf2_per_objfile->objfile->obfd, namei_string_offs);
5717 }
5718
5719 /* Find a slot in .debug_names for the object named NAME.  If NAME is
5720    found, return pointer to its pool data.  If NAME cannot be found,
5721    return NULL.  */
5722
5723 const gdb_byte *
5724 dw2_debug_names_iterator::find_vec_in_debug_names
5725   (const mapped_debug_names &map, const char *name)
5726 {
5727   int (*cmp) (const char *, const char *);
5728
5729   if (current_language->la_language == language_cplus
5730       || current_language->la_language == language_fortran
5731       || current_language->la_language == language_d)
5732     {
5733       /* NAME is already canonical.  Drop any qualifiers as
5734          .debug_names does not contain any.  */
5735
5736       if (strchr (name, '(') != NULL)
5737         {
5738           gdb::unique_xmalloc_ptr<char> without_params
5739             = cp_remove_params (name);
5740
5741           if (without_params != NULL)
5742             {
5743               name = without_params.get();
5744             }
5745         }
5746     }
5747
5748   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
5749
5750   const uint32_t full_hash = dwarf5_djb_hash (name);
5751   uint32_t namei
5752     = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5753                                 (map.bucket_table_reordered
5754                                  + (full_hash % map.bucket_count)), 4,
5755                                 map.dwarf5_byte_order);
5756   if (namei == 0)
5757     return NULL;
5758   --namei;
5759   if (namei >= map.name_count)
5760     {
5761       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5762                    "[in module %s]"),
5763                  namei, map.name_count,
5764                  objfile_name (map.dwarf2_per_objfile->objfile));
5765       return NULL;
5766     }
5767
5768   for (;;)
5769     {
5770       const uint32_t namei_full_hash
5771         = extract_unsigned_integer (reinterpret_cast<const gdb_byte *>
5772                                     (map.hash_table_reordered + namei), 4,
5773                                     map.dwarf5_byte_order);
5774       if (full_hash % map.bucket_count != namei_full_hash % map.bucket_count)
5775         return NULL;
5776
5777       if (full_hash == namei_full_hash)
5778         {
5779           const char *const namei_string = map.namei_to_name (namei);
5780
5781 #if 0 /* An expensive sanity check.  */
5782           if (namei_full_hash != dwarf5_djb_hash (namei_string))
5783             {
5784               complaint (_("Wrong .debug_names hash for string at index %u "
5785                            "[in module %s]"),
5786                          namei, objfile_name (dwarf2_per_objfile->objfile));
5787               return NULL;
5788             }
5789 #endif
5790
5791           if (cmp (namei_string, name) == 0)
5792             {
5793               const ULONGEST namei_entry_offs
5794                 = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5795                                              + namei * map.offset_size),
5796                                             map.offset_size, map.dwarf5_byte_order);
5797               return map.entry_pool + namei_entry_offs;
5798             }
5799         }
5800
5801       ++namei;
5802       if (namei >= map.name_count)
5803         return NULL;
5804     }
5805 }
5806
5807 const gdb_byte *
5808 dw2_debug_names_iterator::find_vec_in_debug_names
5809   (const mapped_debug_names &map, uint32_t namei)
5810 {
5811   if (namei >= map.name_count)
5812     {
5813       complaint (_("Wrong .debug_names with name index %u but name_count=%u "
5814                    "[in module %s]"),
5815                  namei, map.name_count,
5816                  objfile_name (map.dwarf2_per_objfile->objfile));
5817       return NULL;
5818     }
5819
5820   const ULONGEST namei_entry_offs
5821     = extract_unsigned_integer ((map.name_table_entry_offs_reordered
5822                                  + namei * map.offset_size),
5823                                 map.offset_size, map.dwarf5_byte_order);
5824   return map.entry_pool + namei_entry_offs;
5825 }
5826
5827 /* See dw2_debug_names_iterator.  */
5828
5829 dwarf2_per_cu_data *
5830 dw2_debug_names_iterator::next ()
5831 {
5832   if (m_addr == NULL)
5833     return NULL;
5834
5835   struct dwarf2_per_objfile *dwarf2_per_objfile = m_map.dwarf2_per_objfile;
5836   struct objfile *objfile = dwarf2_per_objfile->objfile;
5837   bfd *const abfd = objfile->obfd;
5838
5839  again:
5840
5841   unsigned int bytes_read;
5842   const ULONGEST abbrev = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5843   m_addr += bytes_read;
5844   if (abbrev == 0)
5845     return NULL;
5846
5847   const auto indexval_it = m_map.abbrev_map.find (abbrev);
5848   if (indexval_it == m_map.abbrev_map.cend ())
5849     {
5850       complaint (_("Wrong .debug_names undefined abbrev code %s "
5851                    "[in module %s]"),
5852                  pulongest (abbrev), objfile_name (objfile));
5853       return NULL;
5854     }
5855   const mapped_debug_names::index_val &indexval = indexval_it->second;
5856   bool have_is_static = false;
5857   bool is_static;
5858   dwarf2_per_cu_data *per_cu = NULL;
5859   for (const mapped_debug_names::index_val::attr &attr : indexval.attr_vec)
5860     {
5861       ULONGEST ull;
5862       switch (attr.form)
5863         {
5864         case DW_FORM_implicit_const:
5865           ull = attr.implicit_const;
5866           break;
5867         case DW_FORM_flag_present:
5868           ull = 1;
5869           break;
5870         case DW_FORM_udata:
5871           ull = read_unsigned_leb128 (abfd, m_addr, &bytes_read);
5872           m_addr += bytes_read;
5873           break;
5874         default:
5875           complaint (_("Unsupported .debug_names form %s [in module %s]"),
5876                      dwarf_form_name (attr.form),
5877                      objfile_name (objfile));
5878           return NULL;
5879         }
5880       switch (attr.dw_idx)
5881         {
5882         case DW_IDX_compile_unit:
5883           /* Don't crash on bad data.  */
5884           if (ull >= dwarf2_per_objfile->all_comp_units.size ())
5885             {
5886               complaint (_(".debug_names entry has bad CU index %s"
5887                            " [in module %s]"),
5888                          pulongest (ull),
5889                          objfile_name (dwarf2_per_objfile->objfile));
5890               continue;
5891             }
5892           per_cu = dwarf2_per_objfile->get_cutu (ull);
5893           break;
5894         case DW_IDX_type_unit:
5895           /* Don't crash on bad data.  */
5896           if (ull >= dwarf2_per_objfile->all_type_units.size ())
5897             {
5898               complaint (_(".debug_names entry has bad TU index %s"
5899                            " [in module %s]"),
5900                          pulongest (ull),
5901                          objfile_name (dwarf2_per_objfile->objfile));
5902               continue;
5903             }
5904           per_cu = &dwarf2_per_objfile->get_tu (ull)->per_cu;
5905           break;
5906         case DW_IDX_GNU_internal:
5907           if (!m_map.augmentation_is_gdb)
5908             break;
5909           have_is_static = true;
5910           is_static = true;
5911           break;
5912         case DW_IDX_GNU_external:
5913           if (!m_map.augmentation_is_gdb)
5914             break;
5915           have_is_static = true;
5916           is_static = false;
5917           break;
5918         }
5919     }
5920
5921   /* Skip if already read in.  */
5922   if (per_cu->v.quick->compunit_symtab)
5923     goto again;
5924
5925   /* Check static vs global.  */
5926   if (have_is_static)
5927     {
5928       const bool want_static = m_block_index != GLOBAL_BLOCK;
5929       if (m_want_specific_block && want_static != is_static)
5930         goto again;
5931     }
5932
5933   /* Match dw2_symtab_iter_next, symbol_kind
5934      and debug_names::psymbol_tag.  */
5935   switch (m_domain)
5936     {
5937     case VAR_DOMAIN:
5938       switch (indexval.dwarf_tag)
5939         {
5940         case DW_TAG_variable:
5941         case DW_TAG_subprogram:
5942         /* Some types are also in VAR_DOMAIN.  */
5943         case DW_TAG_typedef:
5944         case DW_TAG_structure_type:
5945           break;
5946         default:
5947           goto again;
5948         }
5949       break;
5950     case STRUCT_DOMAIN:
5951       switch (indexval.dwarf_tag)
5952         {
5953         case DW_TAG_typedef:
5954         case DW_TAG_structure_type:
5955           break;
5956         default:
5957           goto again;
5958         }
5959       break;
5960     case LABEL_DOMAIN:
5961       switch (indexval.dwarf_tag)
5962         {
5963         case 0:
5964         case DW_TAG_variable:
5965           break;
5966         default:
5967           goto again;
5968         }
5969       break;
5970     default:
5971       break;
5972     }
5973
5974   /* Match dw2_expand_symtabs_matching, symbol_kind and
5975      debug_names::psymbol_tag.  */
5976   switch (m_search)
5977     {
5978     case VARIABLES_DOMAIN:
5979       switch (indexval.dwarf_tag)
5980         {
5981         case DW_TAG_variable:
5982           break;
5983         default:
5984           goto again;
5985         }
5986       break;
5987     case FUNCTIONS_DOMAIN:
5988       switch (indexval.dwarf_tag)
5989         {
5990         case DW_TAG_subprogram:
5991           break;
5992         default:
5993           goto again;
5994         }
5995       break;
5996     case TYPES_DOMAIN:
5997       switch (indexval.dwarf_tag)
5998         {
5999         case DW_TAG_typedef:
6000         case DW_TAG_structure_type:
6001           break;
6002         default:
6003           goto again;
6004         }
6005       break;
6006     default:
6007       break;
6008     }
6009
6010   return per_cu;
6011 }
6012
6013 static struct compunit_symtab *
6014 dw2_debug_names_lookup_symbol (struct objfile *objfile, int block_index_int,
6015                                const char *name, domain_enum domain)
6016 {
6017   const block_enum block_index = static_cast<block_enum> (block_index_int);
6018   struct dwarf2_per_objfile *dwarf2_per_objfile
6019     = get_dwarf2_per_objfile (objfile);
6020
6021   const auto &mapp = dwarf2_per_objfile->debug_names_table;
6022   if (!mapp)
6023     {
6024       /* index is NULL if OBJF_READNOW.  */
6025       return NULL;
6026     }
6027   const auto &map = *mapp;
6028
6029   dw2_debug_names_iterator iter (map, true /* want_specific_block */,
6030                                  block_index, domain, name);
6031
6032   struct compunit_symtab *stab_best = NULL;
6033   struct dwarf2_per_cu_data *per_cu;
6034   while ((per_cu = iter.next ()) != NULL)
6035     {
6036       struct symbol *sym, *with_opaque = NULL;
6037       struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu, false);
6038       const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
6039       struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
6040
6041       sym = block_find_symbol (block, name, domain,
6042                                block_find_non_opaque_type_preferred,
6043                                &with_opaque);
6044
6045       /* Some caution must be observed with overloaded functions and
6046          methods, since the index will not contain any overload
6047          information (but NAME might contain it).  */
6048
6049       if (sym != NULL
6050           && strcmp_iw (SYMBOL_SEARCH_NAME (sym), name) == 0)
6051         return stab;
6052       if (with_opaque != NULL
6053           && strcmp_iw (SYMBOL_SEARCH_NAME (with_opaque), name) == 0)
6054         stab_best = stab;
6055
6056       /* Keep looking through other CUs.  */
6057     }
6058
6059   return stab_best;
6060 }
6061
6062 /* This dumps minimal information about .debug_names.  It is called
6063    via "mt print objfiles".  The gdb.dwarf2/gdb-index.exp testcase
6064    uses this to verify that .debug_names has been loaded.  */
6065
6066 static void
6067 dw2_debug_names_dump (struct objfile *objfile)
6068 {
6069   struct dwarf2_per_objfile *dwarf2_per_objfile
6070     = get_dwarf2_per_objfile (objfile);
6071
6072   gdb_assert (dwarf2_per_objfile->using_index);
6073   printf_filtered (".debug_names:");
6074   if (dwarf2_per_objfile->debug_names_table)
6075     printf_filtered (" exists\n");
6076   else
6077     printf_filtered (" faked for \"readnow\"\n");
6078   printf_filtered ("\n");
6079 }
6080
6081 static void
6082 dw2_debug_names_expand_symtabs_for_function (struct objfile *objfile,
6083                                              const char *func_name)
6084 {
6085   struct dwarf2_per_objfile *dwarf2_per_objfile
6086     = get_dwarf2_per_objfile (objfile);
6087
6088   /* dwarf2_per_objfile->debug_names_table is NULL if OBJF_READNOW.  */
6089   if (dwarf2_per_objfile->debug_names_table)
6090     {
6091       const mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6092
6093       /* Note: It doesn't matter what we pass for block_index here.  */
6094       dw2_debug_names_iterator iter (map, false /* want_specific_block */,
6095                                      GLOBAL_BLOCK, VAR_DOMAIN, func_name);
6096
6097       struct dwarf2_per_cu_data *per_cu;
6098       while ((per_cu = iter.next ()) != NULL)
6099         dw2_instantiate_symtab (per_cu, false);
6100     }
6101 }
6102
6103 static void
6104 dw2_debug_names_expand_symtabs_matching
6105   (struct objfile *objfile,
6106    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
6107    const lookup_name_info &lookup_name,
6108    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
6109    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
6110    enum search_domain kind)
6111 {
6112   struct dwarf2_per_objfile *dwarf2_per_objfile
6113     = get_dwarf2_per_objfile (objfile);
6114
6115   /* debug_names_table is NULL if OBJF_READNOW.  */
6116   if (!dwarf2_per_objfile->debug_names_table)
6117     return;
6118
6119   dw_expand_symtabs_matching_file_matcher (dwarf2_per_objfile, file_matcher);
6120
6121   mapped_debug_names &map = *dwarf2_per_objfile->debug_names_table;
6122
6123   dw2_expand_symtabs_matching_symbol (map, lookup_name,
6124                                       symbol_matcher,
6125                                       kind, [&] (offset_type namei)
6126     {
6127       /* The name was matched, now expand corresponding CUs that were
6128          marked.  */
6129       dw2_debug_names_iterator iter (map, kind, namei);
6130
6131       struct dwarf2_per_cu_data *per_cu;
6132       while ((per_cu = iter.next ()) != NULL)
6133         dw2_expand_symtabs_matching_one (per_cu, file_matcher,
6134                                          expansion_notify);
6135     });
6136 }
6137
6138 const struct quick_symbol_functions dwarf2_debug_names_functions =
6139 {
6140   dw2_has_symbols,
6141   dw2_find_last_source_symtab,
6142   dw2_forget_cached_source_info,
6143   dw2_map_symtabs_matching_filename,
6144   dw2_debug_names_lookup_symbol,
6145   dw2_print_stats,
6146   dw2_debug_names_dump,
6147   dw2_relocate,
6148   dw2_debug_names_expand_symtabs_for_function,
6149   dw2_expand_all_symtabs,
6150   dw2_expand_symtabs_with_fullname,
6151   dw2_map_matching_symbols,
6152   dw2_debug_names_expand_symtabs_matching,
6153   dw2_find_pc_sect_compunit_symtab,
6154   NULL,
6155   dw2_map_symbol_filenames
6156 };
6157
6158 /* See symfile.h.  */
6159
6160 bool
6161 dwarf2_initialize_objfile (struct objfile *objfile, dw_index_kind *index_kind)
6162 {
6163   struct dwarf2_per_objfile *dwarf2_per_objfile
6164     = get_dwarf2_per_objfile (objfile);
6165
6166   /* If we're about to read full symbols, don't bother with the
6167      indices.  In this case we also don't care if some other debug
6168      format is making psymtabs, because they are all about to be
6169      expanded anyway.  */
6170   if ((objfile->flags & OBJF_READNOW))
6171     {
6172       dwarf2_per_objfile->using_index = 1;
6173       create_all_comp_units (dwarf2_per_objfile);
6174       create_all_type_units (dwarf2_per_objfile);
6175       dwarf2_per_objfile->quick_file_names_table
6176         = create_quick_file_names_table
6177             (dwarf2_per_objfile->all_comp_units.size ());
6178
6179       for (int i = 0; i < (dwarf2_per_objfile->all_comp_units.size ()
6180                            + dwarf2_per_objfile->all_type_units.size ()); ++i)
6181         {
6182           dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->get_cutu (i);
6183
6184           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6185                                             struct dwarf2_per_cu_quick_data);
6186         }
6187
6188       /* Return 1 so that gdb sees the "quick" functions.  However,
6189          these functions will be no-ops because we will have expanded
6190          all symtabs.  */
6191       *index_kind = dw_index_kind::GDB_INDEX;
6192       return true;
6193     }
6194
6195   if (dwarf2_read_debug_names (dwarf2_per_objfile))
6196     {
6197       *index_kind = dw_index_kind::DEBUG_NAMES;
6198       return true;
6199     }
6200
6201   if (dwarf2_read_gdb_index (dwarf2_per_objfile))
6202     {
6203       *index_kind = dw_index_kind::GDB_INDEX;
6204       return true;
6205     }
6206
6207   return false;
6208 }
6209
6210 \f
6211
6212 /* Build a partial symbol table.  */
6213
6214 void
6215 dwarf2_build_psymtabs (struct objfile *objfile)
6216 {
6217   struct dwarf2_per_objfile *dwarf2_per_objfile
6218     = get_dwarf2_per_objfile (objfile);
6219
6220   if (objfile->global_psymbols.capacity () == 0
6221       && objfile->static_psymbols.capacity () == 0)
6222     init_psymbol_list (objfile, 1024);
6223
6224   TRY
6225     {
6226       /* This isn't really ideal: all the data we allocate on the
6227          objfile's obstack is still uselessly kept around.  However,
6228          freeing it seems unsafe.  */
6229       psymtab_discarder psymtabs (objfile);
6230       dwarf2_build_psymtabs_hard (dwarf2_per_objfile);
6231       psymtabs.keep ();
6232     }
6233   CATCH (except, RETURN_MASK_ERROR)
6234     {
6235       exception_print (gdb_stderr, except);
6236     }
6237   END_CATCH
6238 }
6239
6240 /* Return the total length of the CU described by HEADER.  */
6241
6242 static unsigned int
6243 get_cu_length (const struct comp_unit_head *header)
6244 {
6245   return header->initial_length_size + header->length;
6246 }
6247
6248 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
6249
6250 static inline bool
6251 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
6252 {
6253   sect_offset bottom = cu_header->sect_off;
6254   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
6255
6256   return sect_off >= bottom && sect_off < top;
6257 }
6258
6259 /* Find the base address of the compilation unit for range lists and
6260    location lists.  It will normally be specified by DW_AT_low_pc.
6261    In DWARF-3 draft 4, the base address could be overridden by
6262    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
6263    compilation units with discontinuous ranges.  */
6264
6265 static void
6266 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
6267 {
6268   struct attribute *attr;
6269
6270   cu->base_known = 0;
6271   cu->base_address = 0;
6272
6273   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
6274   if (attr)
6275     {
6276       cu->base_address = attr_value_as_address (attr);
6277       cu->base_known = 1;
6278     }
6279   else
6280     {
6281       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
6282       if (attr)
6283         {
6284           cu->base_address = attr_value_as_address (attr);
6285           cu->base_known = 1;
6286         }
6287     }
6288 }
6289
6290 /* Read in the comp unit header information from the debug_info at info_ptr.
6291    Use rcuh_kind::COMPILE as the default type if not known by the caller.
6292    NOTE: This leaves members offset, first_die_offset to be filled in
6293    by the caller.  */
6294
6295 static const gdb_byte *
6296 read_comp_unit_head (struct comp_unit_head *cu_header,
6297                      const gdb_byte *info_ptr,
6298                      struct dwarf2_section_info *section,
6299                      rcuh_kind section_kind)
6300 {
6301   int signed_addr;
6302   unsigned int bytes_read;
6303   const char *filename = get_section_file_name (section);
6304   bfd *abfd = get_section_bfd_owner (section);
6305
6306   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
6307   cu_header->initial_length_size = bytes_read;
6308   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
6309   info_ptr += bytes_read;
6310   cu_header->version = read_2_bytes (abfd, info_ptr);
6311   if (cu_header->version < 2 || cu_header->version > 5)
6312     error (_("Dwarf Error: wrong version in compilation unit header "
6313            "(is %d, should be 2, 3, 4 or 5) [in module %s]"),
6314            cu_header->version, filename);
6315   info_ptr += 2;
6316   if (cu_header->version < 5)
6317     switch (section_kind)
6318       {
6319       case rcuh_kind::COMPILE:
6320         cu_header->unit_type = DW_UT_compile;
6321         break;
6322       case rcuh_kind::TYPE:
6323         cu_header->unit_type = DW_UT_type;
6324         break;
6325       default:
6326         internal_error (__FILE__, __LINE__,
6327                         _("read_comp_unit_head: invalid section_kind"));
6328       }
6329   else
6330     {
6331       cu_header->unit_type = static_cast<enum dwarf_unit_type>
6332                                                  (read_1_byte (abfd, info_ptr));
6333       info_ptr += 1;
6334       switch (cu_header->unit_type)
6335         {
6336         case DW_UT_compile:
6337           if (section_kind != rcuh_kind::COMPILE)
6338             error (_("Dwarf Error: wrong unit_type in compilation unit header "
6339                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
6340                    filename);
6341           break;
6342         case DW_UT_type:
6343           section_kind = rcuh_kind::TYPE;
6344           break;
6345         default:
6346           error (_("Dwarf Error: wrong unit_type in compilation unit header "
6347                  "(is %d, should be %d or %d) [in module %s]"),
6348                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
6349         }
6350
6351       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6352       info_ptr += 1;
6353     }
6354   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
6355                                                           cu_header,
6356                                                           &bytes_read);
6357   info_ptr += bytes_read;
6358   if (cu_header->version < 5)
6359     {
6360       cu_header->addr_size = read_1_byte (abfd, info_ptr);
6361       info_ptr += 1;
6362     }
6363   signed_addr = bfd_get_sign_extend_vma (abfd);
6364   if (signed_addr < 0)
6365     internal_error (__FILE__, __LINE__,
6366                     _("read_comp_unit_head: dwarf from non elf file"));
6367   cu_header->signed_addr_p = signed_addr;
6368
6369   if (section_kind == rcuh_kind::TYPE)
6370     {
6371       LONGEST type_offset;
6372
6373       cu_header->signature = read_8_bytes (abfd, info_ptr);
6374       info_ptr += 8;
6375
6376       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
6377       info_ptr += bytes_read;
6378       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
6379       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
6380         error (_("Dwarf Error: Too big type_offset in compilation unit "
6381                "header (is %s) [in module %s]"), plongest (type_offset),
6382                filename);
6383     }
6384
6385   return info_ptr;
6386 }
6387
6388 /* Helper function that returns the proper abbrev section for
6389    THIS_CU.  */
6390
6391 static struct dwarf2_section_info *
6392 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
6393 {
6394   struct dwarf2_section_info *abbrev;
6395   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
6396
6397   if (this_cu->is_dwz)
6398     abbrev = &dwarf2_get_dwz_file (dwarf2_per_objfile)->abbrev;
6399   else
6400     abbrev = &dwarf2_per_objfile->abbrev;
6401
6402   return abbrev;
6403 }
6404
6405 /* Subroutine of read_and_check_comp_unit_head and
6406    read_and_check_type_unit_head to simplify them.
6407    Perform various error checking on the header.  */
6408
6409 static void
6410 error_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6411                             struct comp_unit_head *header,
6412                             struct dwarf2_section_info *section,
6413                             struct dwarf2_section_info *abbrev_section)
6414 {
6415   const char *filename = get_section_file_name (section);
6416
6417   if (to_underlying (header->abbrev_sect_off)
6418       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
6419     error (_("Dwarf Error: bad offset (%s) in compilation unit header "
6420            "(offset %s + 6) [in module %s]"),
6421            sect_offset_str (header->abbrev_sect_off),
6422            sect_offset_str (header->sect_off),
6423            filename);
6424
6425   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
6426      avoid potential 32-bit overflow.  */
6427   if (((ULONGEST) header->sect_off + get_cu_length (header))
6428       > section->size)
6429     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
6430            "(offset %s + 0) [in module %s]"),
6431            header->length, sect_offset_str (header->sect_off),
6432            filename);
6433 }
6434
6435 /* Read in a CU/TU header and perform some basic error checking.
6436    The contents of the header are stored in HEADER.
6437    The result is a pointer to the start of the first DIE.  */
6438
6439 static const gdb_byte *
6440 read_and_check_comp_unit_head (struct dwarf2_per_objfile *dwarf2_per_objfile,
6441                                struct comp_unit_head *header,
6442                                struct dwarf2_section_info *section,
6443                                struct dwarf2_section_info *abbrev_section,
6444                                const gdb_byte *info_ptr,
6445                                rcuh_kind section_kind)
6446 {
6447   const gdb_byte *beg_of_comp_unit = info_ptr;
6448
6449   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
6450
6451   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
6452
6453   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
6454
6455   error_check_comp_unit_head (dwarf2_per_objfile, header, section,
6456                               abbrev_section);
6457
6458   return info_ptr;
6459 }
6460
6461 /* Fetch the abbreviation table offset from a comp or type unit header.  */
6462
6463 static sect_offset
6464 read_abbrev_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
6465                     struct dwarf2_section_info *section,
6466                     sect_offset sect_off)
6467 {
6468   bfd *abfd = get_section_bfd_owner (section);
6469   const gdb_byte *info_ptr;
6470   unsigned int initial_length_size, offset_size;
6471   uint16_t version;
6472
6473   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
6474   info_ptr = section->buffer + to_underlying (sect_off);
6475   read_initial_length (abfd, info_ptr, &initial_length_size);
6476   offset_size = initial_length_size == 4 ? 4 : 8;
6477   info_ptr += initial_length_size;
6478
6479   version = read_2_bytes (abfd, info_ptr);
6480   info_ptr += 2;
6481   if (version >= 5)
6482     {
6483       /* Skip unit type and address size.  */
6484       info_ptr += 2;
6485     }
6486
6487   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
6488 }
6489
6490 /* Allocate a new partial symtab for file named NAME and mark this new
6491    partial symtab as being an include of PST.  */
6492
6493 static void
6494 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
6495                                struct objfile *objfile)
6496 {
6497   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
6498
6499   if (!IS_ABSOLUTE_PATH (subpst->filename))
6500     {
6501       /* It shares objfile->objfile_obstack.  */
6502       subpst->dirname = pst->dirname;
6503     }
6504
6505   subpst->textlow = 0;
6506   subpst->texthigh = 0;
6507
6508   subpst->dependencies
6509     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
6510   subpst->dependencies[0] = pst;
6511   subpst->number_of_dependencies = 1;
6512
6513   subpst->globals_offset = 0;
6514   subpst->n_global_syms = 0;
6515   subpst->statics_offset = 0;
6516   subpst->n_static_syms = 0;
6517   subpst->compunit_symtab = NULL;
6518   subpst->read_symtab = pst->read_symtab;
6519   subpst->readin = 0;
6520
6521   /* No private part is necessary for include psymtabs.  This property
6522      can be used to differentiate between such include psymtabs and
6523      the regular ones.  */
6524   subpst->read_symtab_private = NULL;
6525 }
6526
6527 /* Read the Line Number Program data and extract the list of files
6528    included by the source file represented by PST.  Build an include
6529    partial symtab for each of these included files.  */
6530
6531 static void
6532 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
6533                                struct die_info *die,
6534                                struct partial_symtab *pst)
6535 {
6536   line_header_up lh;
6537   struct attribute *attr;
6538
6539   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
6540   if (attr)
6541     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
6542   if (lh == NULL)
6543     return;  /* No linetable, so no includes.  */
6544
6545   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
6546   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
6547 }
6548
6549 static hashval_t
6550 hash_signatured_type (const void *item)
6551 {
6552   const struct signatured_type *sig_type
6553     = (const struct signatured_type *) item;
6554
6555   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
6556   return sig_type->signature;
6557 }
6558
6559 static int
6560 eq_signatured_type (const void *item_lhs, const void *item_rhs)
6561 {
6562   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
6563   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
6564
6565   return lhs->signature == rhs->signature;
6566 }
6567
6568 /* Allocate a hash table for signatured types.  */
6569
6570 static htab_t
6571 allocate_signatured_type_table (struct objfile *objfile)
6572 {
6573   return htab_create_alloc_ex (41,
6574                                hash_signatured_type,
6575                                eq_signatured_type,
6576                                NULL,
6577                                &objfile->objfile_obstack,
6578                                hashtab_obstack_allocate,
6579                                dummy_obstack_deallocate);
6580 }
6581
6582 /* A helper function to add a signatured type CU to a table.  */
6583
6584 static int
6585 add_signatured_type_cu_to_table (void **slot, void *datum)
6586 {
6587   struct signatured_type *sigt = (struct signatured_type *) *slot;
6588   std::vector<signatured_type *> *all_type_units
6589     = (std::vector<signatured_type *> *) datum;
6590
6591   all_type_units->push_back (sigt);
6592
6593   return 1;
6594 }
6595
6596 /* A helper for create_debug_types_hash_table.  Read types from SECTION
6597    and fill them into TYPES_HTAB.  It will process only type units,
6598    therefore DW_UT_type.  */
6599
6600 static void
6601 create_debug_type_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6602                               struct dwo_file *dwo_file,
6603                               dwarf2_section_info *section, htab_t &types_htab,
6604                               rcuh_kind section_kind)
6605 {
6606   struct objfile *objfile = dwarf2_per_objfile->objfile;
6607   struct dwarf2_section_info *abbrev_section;
6608   bfd *abfd;
6609   const gdb_byte *info_ptr, *end_ptr;
6610
6611   abbrev_section = (dwo_file != NULL
6612                     ? &dwo_file->sections.abbrev
6613                     : &dwarf2_per_objfile->abbrev);
6614
6615   if (dwarf_read_debug)
6616     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
6617                         get_section_name (section),
6618                         get_section_file_name (abbrev_section));
6619
6620   dwarf2_read_section (objfile, section);
6621   info_ptr = section->buffer;
6622
6623   if (info_ptr == NULL)
6624     return;
6625
6626   /* We can't set abfd until now because the section may be empty or
6627      not present, in which case the bfd is unknown.  */
6628   abfd = get_section_bfd_owner (section);
6629
6630   /* We don't use init_cutu_and_read_dies_simple, or some such, here
6631      because we don't need to read any dies: the signature is in the
6632      header.  */
6633
6634   end_ptr = info_ptr + section->size;
6635   while (info_ptr < end_ptr)
6636     {
6637       struct signatured_type *sig_type;
6638       struct dwo_unit *dwo_tu;
6639       void **slot;
6640       const gdb_byte *ptr = info_ptr;
6641       struct comp_unit_head header;
6642       unsigned int length;
6643
6644       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
6645
6646       /* Initialize it due to a false compiler warning.  */
6647       header.signature = -1;
6648       header.type_cu_offset_in_tu = (cu_offset) -1;
6649
6650       /* We need to read the type's signature in order to build the hash
6651          table, but we don't need anything else just yet.  */
6652
6653       ptr = read_and_check_comp_unit_head (dwarf2_per_objfile, &header, section,
6654                                            abbrev_section, ptr, section_kind);
6655
6656       length = get_cu_length (&header);
6657
6658       /* Skip dummy type units.  */
6659       if (ptr >= info_ptr + length
6660           || peek_abbrev_code (abfd, ptr) == 0
6661           || header.unit_type != DW_UT_type)
6662         {
6663           info_ptr += length;
6664           continue;
6665         }
6666
6667       if (types_htab == NULL)
6668         {
6669           if (dwo_file)
6670             types_htab = allocate_dwo_unit_table (objfile);
6671           else
6672             types_htab = allocate_signatured_type_table (objfile);
6673         }
6674
6675       if (dwo_file)
6676         {
6677           sig_type = NULL;
6678           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6679                                    struct dwo_unit);
6680           dwo_tu->dwo_file = dwo_file;
6681           dwo_tu->signature = header.signature;
6682           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
6683           dwo_tu->section = section;
6684           dwo_tu->sect_off = sect_off;
6685           dwo_tu->length = length;
6686         }
6687       else
6688         {
6689           /* N.B.: type_offset is not usable if this type uses a DWO file.
6690              The real type_offset is in the DWO file.  */
6691           dwo_tu = NULL;
6692           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6693                                      struct signatured_type);
6694           sig_type->signature = header.signature;
6695           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
6696           sig_type->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6697           sig_type->per_cu.is_debug_types = 1;
6698           sig_type->per_cu.section = section;
6699           sig_type->per_cu.sect_off = sect_off;
6700           sig_type->per_cu.length = length;
6701         }
6702
6703       slot = htab_find_slot (types_htab,
6704                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
6705                              INSERT);
6706       gdb_assert (slot != NULL);
6707       if (*slot != NULL)
6708         {
6709           sect_offset dup_sect_off;
6710
6711           if (dwo_file)
6712             {
6713               const struct dwo_unit *dup_tu
6714                 = (const struct dwo_unit *) *slot;
6715
6716               dup_sect_off = dup_tu->sect_off;
6717             }
6718           else
6719             {
6720               const struct signatured_type *dup_tu
6721                 = (const struct signatured_type *) *slot;
6722
6723               dup_sect_off = dup_tu->per_cu.sect_off;
6724             }
6725
6726           complaint (_("debug type entry at offset %s is duplicate to"
6727                        " the entry at offset %s, signature %s"),
6728                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
6729                      hex_string (header.signature));
6730         }
6731       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
6732
6733       if (dwarf_read_debug > 1)
6734         fprintf_unfiltered (gdb_stdlog, "  offset %s, signature %s\n",
6735                             sect_offset_str (sect_off),
6736                             hex_string (header.signature));
6737
6738       info_ptr += length;
6739     }
6740 }
6741
6742 /* Create the hash table of all entries in the .debug_types
6743    (or .debug_types.dwo) section(s).
6744    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
6745    otherwise it is NULL.
6746
6747    The result is a pointer to the hash table or NULL if there are no types.
6748
6749    Note: This function processes DWO files only, not DWP files.  */
6750
6751 static void
6752 create_debug_types_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
6753                                struct dwo_file *dwo_file,
6754                                VEC (dwarf2_section_info_def) *types,
6755                                htab_t &types_htab)
6756 {
6757   int ix;
6758   struct dwarf2_section_info *section;
6759
6760   if (VEC_empty (dwarf2_section_info_def, types))
6761     return;
6762
6763   for (ix = 0;
6764        VEC_iterate (dwarf2_section_info_def, types, ix, section);
6765        ++ix)
6766     create_debug_type_hash_table (dwarf2_per_objfile, dwo_file, section,
6767                                   types_htab, rcuh_kind::TYPE);
6768 }
6769
6770 /* Create the hash table of all entries in the .debug_types section,
6771    and initialize all_type_units.
6772    The result is zero if there is an error (e.g. missing .debug_types section),
6773    otherwise non-zero.  */
6774
6775 static int
6776 create_all_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
6777 {
6778   htab_t types_htab = NULL;
6779
6780   create_debug_type_hash_table (dwarf2_per_objfile, NULL,
6781                                 &dwarf2_per_objfile->info, types_htab,
6782                                 rcuh_kind::COMPILE);
6783   create_debug_types_hash_table (dwarf2_per_objfile, NULL,
6784                                  dwarf2_per_objfile->types, types_htab);
6785   if (types_htab == NULL)
6786     {
6787       dwarf2_per_objfile->signatured_types = NULL;
6788       return 0;
6789     }
6790
6791   dwarf2_per_objfile->signatured_types = types_htab;
6792
6793   gdb_assert (dwarf2_per_objfile->all_type_units.empty ());
6794   dwarf2_per_objfile->all_type_units.reserve (htab_elements (types_htab));
6795
6796   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table,
6797                           &dwarf2_per_objfile->all_type_units);
6798
6799   return 1;
6800 }
6801
6802 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
6803    If SLOT is non-NULL, it is the entry to use in the hash table.
6804    Otherwise we find one.  */
6805
6806 static struct signatured_type *
6807 add_type_unit (struct dwarf2_per_objfile *dwarf2_per_objfile, ULONGEST sig,
6808                void **slot)
6809 {
6810   struct objfile *objfile = dwarf2_per_objfile->objfile;
6811
6812   if (dwarf2_per_objfile->all_type_units.size ()
6813       == dwarf2_per_objfile->all_type_units.capacity ())
6814     ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
6815
6816   signatured_type *sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6817                                               struct signatured_type);
6818
6819   dwarf2_per_objfile->all_type_units.push_back (sig_type);
6820   sig_type->signature = sig;
6821   sig_type->per_cu.is_debug_types = 1;
6822   if (dwarf2_per_objfile->using_index)
6823     {
6824       sig_type->per_cu.v.quick =
6825         OBSTACK_ZALLOC (&objfile->objfile_obstack,
6826                         struct dwarf2_per_cu_quick_data);
6827     }
6828
6829   if (slot == NULL)
6830     {
6831       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6832                              sig_type, INSERT);
6833     }
6834   gdb_assert (*slot == NULL);
6835   *slot = sig_type;
6836   /* The rest of sig_type must be filled in by the caller.  */
6837   return sig_type;
6838 }
6839
6840 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6841    Fill in SIG_ENTRY with DWO_ENTRY.  */
6842
6843 static void
6844 fill_in_sig_entry_from_dwo_entry (struct dwarf2_per_objfile *dwarf2_per_objfile,
6845                                   struct signatured_type *sig_entry,
6846                                   struct dwo_unit *dwo_entry)
6847 {
6848   /* Make sure we're not clobbering something we don't expect to.  */
6849   gdb_assert (! sig_entry->per_cu.queued);
6850   gdb_assert (sig_entry->per_cu.cu == NULL);
6851   if (dwarf2_per_objfile->using_index)
6852     {
6853       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6854       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6855     }
6856   else
6857       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6858   gdb_assert (sig_entry->signature == dwo_entry->signature);
6859   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6860   gdb_assert (sig_entry->type_unit_group == NULL);
6861   gdb_assert (sig_entry->dwo_unit == NULL);
6862
6863   sig_entry->per_cu.section = dwo_entry->section;
6864   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6865   sig_entry->per_cu.length = dwo_entry->length;
6866   sig_entry->per_cu.reading_dwo_directly = 1;
6867   sig_entry->per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
6868   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6869   sig_entry->dwo_unit = dwo_entry;
6870 }
6871
6872 /* Subroutine of lookup_signatured_type.
6873    If we haven't read the TU yet, create the signatured_type data structure
6874    for a TU to be read in directly from a DWO file, bypassing the stub.
6875    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6876    using .gdb_index, then when reading a CU we want to stay in the DWO file
6877    containing that CU.  Otherwise we could end up reading several other DWO
6878    files (due to comdat folding) to process the transitive closure of all the
6879    mentioned TUs, and that can be slow.  The current DWO file will have every
6880    type signature that it needs.
6881    We only do this for .gdb_index because in the psymtab case we already have
6882    to read all the DWOs to build the type unit groups.  */
6883
6884 static struct signatured_type *
6885 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6886 {
6887   struct dwarf2_per_objfile *dwarf2_per_objfile
6888     = cu->per_cu->dwarf2_per_objfile;
6889   struct objfile *objfile = dwarf2_per_objfile->objfile;
6890   struct dwo_file *dwo_file;
6891   struct dwo_unit find_dwo_entry, *dwo_entry;
6892   struct signatured_type find_sig_entry, *sig_entry;
6893   void **slot;
6894
6895   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6896
6897   /* If TU skeletons have been removed then we may not have read in any
6898      TUs yet.  */
6899   if (dwarf2_per_objfile->signatured_types == NULL)
6900     {
6901       dwarf2_per_objfile->signatured_types
6902         = allocate_signatured_type_table (objfile);
6903     }
6904
6905   /* We only ever need to read in one copy of a signatured type.
6906      Use the global signatured_types array to do our own comdat-folding
6907      of types.  If this is the first time we're reading this TU, and
6908      the TU has an entry in .gdb_index, replace the recorded data from
6909      .gdb_index with this TU.  */
6910
6911   find_sig_entry.signature = sig;
6912   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6913                          &find_sig_entry, INSERT);
6914   sig_entry = (struct signatured_type *) *slot;
6915
6916   /* We can get here with the TU already read, *or* in the process of being
6917      read.  Don't reassign the global entry to point to this DWO if that's
6918      the case.  Also note that if the TU is already being read, it may not
6919      have come from a DWO, the program may be a mix of Fission-compiled
6920      code and non-Fission-compiled code.  */
6921
6922   /* Have we already tried to read this TU?
6923      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6924      needn't exist in the global table yet).  */
6925   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6926     return sig_entry;
6927
6928   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6929      dwo_unit of the TU itself.  */
6930   dwo_file = cu->dwo_unit->dwo_file;
6931
6932   /* Ok, this is the first time we're reading this TU.  */
6933   if (dwo_file->tus == NULL)
6934     return NULL;
6935   find_dwo_entry.signature = sig;
6936   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
6937   if (dwo_entry == NULL)
6938     return NULL;
6939
6940   /* If the global table doesn't have an entry for this TU, add one.  */
6941   if (sig_entry == NULL)
6942     sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6943
6944   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6945   sig_entry->per_cu.tu_read = 1;
6946   return sig_entry;
6947 }
6948
6949 /* Subroutine of lookup_signatured_type.
6950    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6951    then try the DWP file.  If the TU stub (skeleton) has been removed then
6952    it won't be in .gdb_index.  */
6953
6954 static struct signatured_type *
6955 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6956 {
6957   struct dwarf2_per_objfile *dwarf2_per_objfile
6958     = cu->per_cu->dwarf2_per_objfile;
6959   struct objfile *objfile = dwarf2_per_objfile->objfile;
6960   struct dwp_file *dwp_file = get_dwp_file (dwarf2_per_objfile);
6961   struct dwo_unit *dwo_entry;
6962   struct signatured_type find_sig_entry, *sig_entry;
6963   void **slot;
6964
6965   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6966   gdb_assert (dwp_file != NULL);
6967
6968   /* If TU skeletons have been removed then we may not have read in any
6969      TUs yet.  */
6970   if (dwarf2_per_objfile->signatured_types == NULL)
6971     {
6972       dwarf2_per_objfile->signatured_types
6973         = allocate_signatured_type_table (objfile);
6974     }
6975
6976   find_sig_entry.signature = sig;
6977   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6978                          &find_sig_entry, INSERT);
6979   sig_entry = (struct signatured_type *) *slot;
6980
6981   /* Have we already tried to read this TU?
6982      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6983      needn't exist in the global table yet).  */
6984   if (sig_entry != NULL)
6985     return sig_entry;
6986
6987   if (dwp_file->tus == NULL)
6988     return NULL;
6989   dwo_entry = lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, NULL,
6990                                       sig, 1 /* is_debug_types */);
6991   if (dwo_entry == NULL)
6992     return NULL;
6993
6994   sig_entry = add_type_unit (dwarf2_per_objfile, sig, slot);
6995   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, sig_entry, dwo_entry);
6996
6997   return sig_entry;
6998 }
6999
7000 /* Lookup a signature based type for DW_FORM_ref_sig8.
7001    Returns NULL if signature SIG is not present in the table.
7002    It is up to the caller to complain about this.  */
7003
7004 static struct signatured_type *
7005 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
7006 {
7007   struct dwarf2_per_objfile *dwarf2_per_objfile
7008     = cu->per_cu->dwarf2_per_objfile;
7009
7010   if (cu->dwo_unit
7011       && dwarf2_per_objfile->using_index)
7012     {
7013       /* We're in a DWO/DWP file, and we're using .gdb_index.
7014          These cases require special processing.  */
7015       if (get_dwp_file (dwarf2_per_objfile) == NULL)
7016         return lookup_dwo_signatured_type (cu, sig);
7017       else
7018         return lookup_dwp_signatured_type (cu, sig);
7019     }
7020   else
7021     {
7022       struct signatured_type find_entry, *entry;
7023
7024       if (dwarf2_per_objfile->signatured_types == NULL)
7025         return NULL;
7026       find_entry.signature = sig;
7027       entry = ((struct signatured_type *)
7028                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
7029       return entry;
7030     }
7031 }
7032 \f
7033 /* Low level DIE reading support.  */
7034
7035 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
7036
7037 static void
7038 init_cu_die_reader (struct die_reader_specs *reader,
7039                     struct dwarf2_cu *cu,
7040                     struct dwarf2_section_info *section,
7041                     struct dwo_file *dwo_file,
7042                     struct abbrev_table *abbrev_table)
7043 {
7044   gdb_assert (section->readin && section->buffer != NULL);
7045   reader->abfd = get_section_bfd_owner (section);
7046   reader->cu = cu;
7047   reader->dwo_file = dwo_file;
7048   reader->die_section = section;
7049   reader->buffer = section->buffer;
7050   reader->buffer_end = section->buffer + section->size;
7051   reader->comp_dir = NULL;
7052   reader->abbrev_table = abbrev_table;
7053 }
7054
7055 /* Subroutine of init_cutu_and_read_dies to simplify it.
7056    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
7057    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
7058    already.
7059
7060    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
7061    from it to the DIE in the DWO.  If NULL we are skipping the stub.
7062    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
7063    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
7064    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
7065    STUB_COMP_DIR may be non-NULL.
7066    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
7067    are filled in with the info of the DIE from the DWO file.
7068    *RESULT_DWO_ABBREV_TABLE will be filled in with the abbrev table allocated
7069    from the dwo.  Since *RESULT_READER references this abbrev table, it must be
7070    kept around for at least as long as *RESULT_READER.
7071
7072    The result is non-zero if a valid (non-dummy) DIE was found.  */
7073
7074 static int
7075 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
7076                         struct dwo_unit *dwo_unit,
7077                         struct die_info *stub_comp_unit_die,
7078                         const char *stub_comp_dir,
7079                         struct die_reader_specs *result_reader,
7080                         const gdb_byte **result_info_ptr,
7081                         struct die_info **result_comp_unit_die,
7082                         int *result_has_children,
7083                         abbrev_table_up *result_dwo_abbrev_table)
7084 {
7085   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7086   struct objfile *objfile = dwarf2_per_objfile->objfile;
7087   struct dwarf2_cu *cu = this_cu->cu;
7088   bfd *abfd;
7089   const gdb_byte *begin_info_ptr, *info_ptr;
7090   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
7091   int i,num_extra_attrs;
7092   struct dwarf2_section_info *dwo_abbrev_section;
7093   struct attribute *attr;
7094   struct die_info *comp_unit_die;
7095
7096   /* At most one of these may be provided.  */
7097   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
7098
7099   /* These attributes aren't processed until later:
7100      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
7101      DW_AT_comp_dir is used now, to find the DWO file, but it is also
7102      referenced later.  However, these attributes are found in the stub
7103      which we won't have later.  In order to not impose this complication
7104      on the rest of the code, we read them here and copy them to the
7105      DWO CU/TU die.  */
7106
7107   stmt_list = NULL;
7108   low_pc = NULL;
7109   high_pc = NULL;
7110   ranges = NULL;
7111   comp_dir = NULL;
7112
7113   if (stub_comp_unit_die != NULL)
7114     {
7115       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
7116          DWO file.  */
7117       if (! this_cu->is_debug_types)
7118         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
7119       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
7120       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
7121       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
7122       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
7123
7124       /* There should be a DW_AT_addr_base attribute here (if needed).
7125          We need the value before we can process DW_FORM_GNU_addr_index.  */
7126       cu->addr_base = 0;
7127       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
7128       if (attr)
7129         cu->addr_base = DW_UNSND (attr);
7130
7131       /* There should be a DW_AT_ranges_base attribute here (if needed).
7132          We need the value before we can process DW_AT_ranges.  */
7133       cu->ranges_base = 0;
7134       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
7135       if (attr)
7136         cu->ranges_base = DW_UNSND (attr);
7137     }
7138   else if (stub_comp_dir != NULL)
7139     {
7140       /* Reconstruct the comp_dir attribute to simplify the code below.  */
7141       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
7142       comp_dir->name = DW_AT_comp_dir;
7143       comp_dir->form = DW_FORM_string;
7144       DW_STRING_IS_CANONICAL (comp_dir) = 0;
7145       DW_STRING (comp_dir) = stub_comp_dir;
7146     }
7147
7148   /* Set up for reading the DWO CU/TU.  */
7149   cu->dwo_unit = dwo_unit;
7150   dwarf2_section_info *section = dwo_unit->section;
7151   dwarf2_read_section (objfile, section);
7152   abfd = get_section_bfd_owner (section);
7153   begin_info_ptr = info_ptr = (section->buffer
7154                                + to_underlying (dwo_unit->sect_off));
7155   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
7156
7157   if (this_cu->is_debug_types)
7158     {
7159       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
7160
7161       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7162                                                 &cu->header, section,
7163                                                 dwo_abbrev_section,
7164                                                 info_ptr, rcuh_kind::TYPE);
7165       /* This is not an assert because it can be caused by bad debug info.  */
7166       if (sig_type->signature != cu->header.signature)
7167         {
7168           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
7169                    " TU at offset %s [in module %s]"),
7170                  hex_string (sig_type->signature),
7171                  hex_string (cu->header.signature),
7172                  sect_offset_str (dwo_unit->sect_off),
7173                  bfd_get_filename (abfd));
7174         }
7175       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7176       /* For DWOs coming from DWP files, we don't know the CU length
7177          nor the type's offset in the TU until now.  */
7178       dwo_unit->length = get_cu_length (&cu->header);
7179       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
7180
7181       /* Establish the type offset that can be used to lookup the type.
7182          For DWO files, we don't know it until now.  */
7183       sig_type->type_offset_in_section
7184         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
7185     }
7186   else
7187     {
7188       info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7189                                                 &cu->header, section,
7190                                                 dwo_abbrev_section,
7191                                                 info_ptr, rcuh_kind::COMPILE);
7192       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
7193       /* For DWOs coming from DWP files, we don't know the CU length
7194          until now.  */
7195       dwo_unit->length = get_cu_length (&cu->header);
7196     }
7197
7198   *result_dwo_abbrev_table
7199     = abbrev_table_read_table (dwarf2_per_objfile, dwo_abbrev_section,
7200                                cu->header.abbrev_sect_off);
7201   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file,
7202                       result_dwo_abbrev_table->get ());
7203
7204   /* Read in the die, but leave space to copy over the attributes
7205      from the stub.  This has the benefit of simplifying the rest of
7206      the code - all the work to maintain the illusion of a single
7207      DW_TAG_{compile,type}_unit DIE is done here.  */
7208   num_extra_attrs = ((stmt_list != NULL)
7209                      + (low_pc != NULL)
7210                      + (high_pc != NULL)
7211                      + (ranges != NULL)
7212                      + (comp_dir != NULL));
7213   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
7214                               result_has_children, num_extra_attrs);
7215
7216   /* Copy over the attributes from the stub to the DIE we just read in.  */
7217   comp_unit_die = *result_comp_unit_die;
7218   i = comp_unit_die->num_attrs;
7219   if (stmt_list != NULL)
7220     comp_unit_die->attrs[i++] = *stmt_list;
7221   if (low_pc != NULL)
7222     comp_unit_die->attrs[i++] = *low_pc;
7223   if (high_pc != NULL)
7224     comp_unit_die->attrs[i++] = *high_pc;
7225   if (ranges != NULL)
7226     comp_unit_die->attrs[i++] = *ranges;
7227   if (comp_dir != NULL)
7228     comp_unit_die->attrs[i++] = *comp_dir;
7229   comp_unit_die->num_attrs += num_extra_attrs;
7230
7231   if (dwarf_die_debug)
7232     {
7233       fprintf_unfiltered (gdb_stdlog,
7234                           "Read die from %s@0x%x of %s:\n",
7235                           get_section_name (section),
7236                           (unsigned) (begin_info_ptr - section->buffer),
7237                           bfd_get_filename (abfd));
7238       dump_die (comp_unit_die, dwarf_die_debug);
7239     }
7240
7241   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
7242      TUs by skipping the stub and going directly to the entry in the DWO file.
7243      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
7244      to get it via circuitous means.  Blech.  */
7245   if (comp_dir != NULL)
7246     result_reader->comp_dir = DW_STRING (comp_dir);
7247
7248   /* Skip dummy compilation units.  */
7249   if (info_ptr >= begin_info_ptr + dwo_unit->length
7250       || peek_abbrev_code (abfd, info_ptr) == 0)
7251     return 0;
7252
7253   *result_info_ptr = info_ptr;
7254   return 1;
7255 }
7256
7257 /* Subroutine of init_cutu_and_read_dies to simplify it.
7258    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
7259    Returns NULL if the specified DWO unit cannot be found.  */
7260
7261 static struct dwo_unit *
7262 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
7263                  struct die_info *comp_unit_die)
7264 {
7265   struct dwarf2_cu *cu = this_cu->cu;
7266   ULONGEST signature;
7267   struct dwo_unit *dwo_unit;
7268   const char *comp_dir, *dwo_name;
7269
7270   gdb_assert (cu != NULL);
7271
7272   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
7273   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7274   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7275
7276   if (this_cu->is_debug_types)
7277     {
7278       struct signatured_type *sig_type;
7279
7280       /* Since this_cu is the first member of struct signatured_type,
7281          we can go from a pointer to one to a pointer to the other.  */
7282       sig_type = (struct signatured_type *) this_cu;
7283       signature = sig_type->signature;
7284       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
7285     }
7286   else
7287     {
7288       struct attribute *attr;
7289
7290       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
7291       if (! attr)
7292         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
7293                  " [in module %s]"),
7294                dwo_name, objfile_name (this_cu->dwarf2_per_objfile->objfile));
7295       signature = DW_UNSND (attr);
7296       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
7297                                        signature);
7298     }
7299
7300   return dwo_unit;
7301 }
7302
7303 /* Subroutine of init_cutu_and_read_dies to simplify it.
7304    See it for a description of the parameters.
7305    Read a TU directly from a DWO file, bypassing the stub.  */
7306
7307 static void
7308 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
7309                            int use_existing_cu, int keep,
7310                            die_reader_func_ftype *die_reader_func,
7311                            void *data)
7312 {
7313   std::unique_ptr<dwarf2_cu> new_cu;
7314   struct signatured_type *sig_type;
7315   struct die_reader_specs reader;
7316   const gdb_byte *info_ptr;
7317   struct die_info *comp_unit_die;
7318   int has_children;
7319   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7320
7321   /* Verify we can do the following downcast, and that we have the
7322      data we need.  */
7323   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
7324   sig_type = (struct signatured_type *) this_cu;
7325   gdb_assert (sig_type->dwo_unit != NULL);
7326
7327   if (use_existing_cu && this_cu->cu != NULL)
7328     {
7329       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
7330       /* There's no need to do the rereading_dwo_cu handling that
7331          init_cutu_and_read_dies does since we don't read the stub.  */
7332     }
7333   else
7334     {
7335       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7336       gdb_assert (this_cu->cu == NULL);
7337       new_cu.reset (new dwarf2_cu (this_cu));
7338     }
7339
7340   /* A future optimization, if needed, would be to use an existing
7341      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
7342      could share abbrev tables.  */
7343
7344   /* The abbreviation table used by READER, this must live at least as long as
7345      READER.  */
7346   abbrev_table_up dwo_abbrev_table;
7347
7348   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
7349                               NULL /* stub_comp_unit_die */,
7350                               sig_type->dwo_unit->dwo_file->comp_dir,
7351                               &reader, &info_ptr,
7352                               &comp_unit_die, &has_children,
7353                               &dwo_abbrev_table) == 0)
7354     {
7355       /* Dummy die.  */
7356       return;
7357     }
7358
7359   /* All the "real" work is done here.  */
7360   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7361
7362   /* This duplicates the code in init_cutu_and_read_dies,
7363      but the alternative is making the latter more complex.
7364      This function is only for the special case of using DWO files directly:
7365      no point in overly complicating the general case just to handle this.  */
7366   if (new_cu != NULL && keep)
7367     {
7368       /* Link this CU into read_in_chain.  */
7369       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7370       dwarf2_per_objfile->read_in_chain = this_cu;
7371       /* The chain owns it now.  */
7372       new_cu.release ();
7373     }
7374 }
7375
7376 /* Initialize a CU (or TU) and read its DIEs.
7377    If the CU defers to a DWO file, read the DWO file as well.
7378
7379    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
7380    Otherwise the table specified in the comp unit header is read in and used.
7381    This is an optimization for when we already have the abbrev table.
7382
7383    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
7384    Otherwise, a new CU is allocated with xmalloc.
7385
7386    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
7387    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
7388
7389    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7390    linker) then DIE_READER_FUNC will not get called.  */
7391
7392 static void
7393 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
7394                          struct abbrev_table *abbrev_table,
7395                          int use_existing_cu, int keep,
7396                          bool skip_partial,
7397                          die_reader_func_ftype *die_reader_func,
7398                          void *data)
7399 {
7400   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7401   struct objfile *objfile = dwarf2_per_objfile->objfile;
7402   struct dwarf2_section_info *section = this_cu->section;
7403   bfd *abfd = get_section_bfd_owner (section);
7404   struct dwarf2_cu *cu;
7405   const gdb_byte *begin_info_ptr, *info_ptr;
7406   struct die_reader_specs reader;
7407   struct die_info *comp_unit_die;
7408   int has_children;
7409   struct attribute *attr;
7410   struct signatured_type *sig_type = NULL;
7411   struct dwarf2_section_info *abbrev_section;
7412   /* Non-zero if CU currently points to a DWO file and we need to
7413      reread it.  When this happens we need to reread the skeleton die
7414      before we can reread the DWO file (this only applies to CUs, not TUs).  */
7415   int rereading_dwo_cu = 0;
7416
7417   if (dwarf_die_debug)
7418     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7419                         this_cu->is_debug_types ? "type" : "comp",
7420                         sect_offset_str (this_cu->sect_off));
7421
7422   if (use_existing_cu)
7423     gdb_assert (keep);
7424
7425   /* If we're reading a TU directly from a DWO file, including a virtual DWO
7426      file (instead of going through the stub), short-circuit all of this.  */
7427   if (this_cu->reading_dwo_directly)
7428     {
7429       /* Narrow down the scope of possibilities to have to understand.  */
7430       gdb_assert (this_cu->is_debug_types);
7431       gdb_assert (abbrev_table == NULL);
7432       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
7433                                  die_reader_func, data);
7434       return;
7435     }
7436
7437   /* This is cheap if the section is already read in.  */
7438   dwarf2_read_section (objfile, section);
7439
7440   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7441
7442   abbrev_section = get_abbrev_section_for_cu (this_cu);
7443
7444   std::unique_ptr<dwarf2_cu> new_cu;
7445   if (use_existing_cu && this_cu->cu != NULL)
7446     {
7447       cu = this_cu->cu;
7448       /* If this CU is from a DWO file we need to start over, we need to
7449          refetch the attributes from the skeleton CU.
7450          This could be optimized by retrieving those attributes from when we
7451          were here the first time: the previous comp_unit_die was stored in
7452          comp_unit_obstack.  But there's no data yet that we need this
7453          optimization.  */
7454       if (cu->dwo_unit != NULL)
7455         rereading_dwo_cu = 1;
7456     }
7457   else
7458     {
7459       /* If !use_existing_cu, this_cu->cu must be NULL.  */
7460       gdb_assert (this_cu->cu == NULL);
7461       new_cu.reset (new dwarf2_cu (this_cu));
7462       cu = new_cu.get ();
7463     }
7464
7465   /* Get the header.  */
7466   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
7467     {
7468       /* We already have the header, there's no need to read it in again.  */
7469       info_ptr += to_underlying (cu->header.first_die_cu_offset);
7470     }
7471   else
7472     {
7473       if (this_cu->is_debug_types)
7474         {
7475           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7476                                                     &cu->header, section,
7477                                                     abbrev_section, info_ptr,
7478                                                     rcuh_kind::TYPE);
7479
7480           /* Since per_cu is the first member of struct signatured_type,
7481              we can go from a pointer to one to a pointer to the other.  */
7482           sig_type = (struct signatured_type *) this_cu;
7483           gdb_assert (sig_type->signature == cu->header.signature);
7484           gdb_assert (sig_type->type_offset_in_tu
7485                       == cu->header.type_cu_offset_in_tu);
7486           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7487
7488           /* LENGTH has not been set yet for type units if we're
7489              using .gdb_index.  */
7490           this_cu->length = get_cu_length (&cu->header);
7491
7492           /* Establish the type offset that can be used to lookup the type.  */
7493           sig_type->type_offset_in_section =
7494             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
7495
7496           this_cu->dwarf_version = cu->header.version;
7497         }
7498       else
7499         {
7500           info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7501                                                     &cu->header, section,
7502                                                     abbrev_section,
7503                                                     info_ptr,
7504                                                     rcuh_kind::COMPILE);
7505
7506           gdb_assert (this_cu->sect_off == cu->header.sect_off);
7507           gdb_assert (this_cu->length == get_cu_length (&cu->header));
7508           this_cu->dwarf_version = cu->header.version;
7509         }
7510     }
7511
7512   /* Skip dummy compilation units.  */
7513   if (info_ptr >= begin_info_ptr + this_cu->length
7514       || peek_abbrev_code (abfd, info_ptr) == 0)
7515     return;
7516
7517   /* If we don't have them yet, read the abbrevs for this compilation unit.
7518      And if we need to read them now, make sure they're freed when we're
7519      done (own the table through ABBREV_TABLE_HOLDER).  */
7520   abbrev_table_up abbrev_table_holder;
7521   if (abbrev_table != NULL)
7522     gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
7523   else
7524     {
7525       abbrev_table_holder
7526         = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7527                                    cu->header.abbrev_sect_off);
7528       abbrev_table = abbrev_table_holder.get ();
7529     }
7530
7531   /* Read the top level CU/TU die.  */
7532   init_cu_die_reader (&reader, cu, section, NULL, abbrev_table);
7533   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7534
7535   if (skip_partial && comp_unit_die->tag == DW_TAG_partial_unit)
7536     return;
7537
7538   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
7539      from the DWO file.  read_cutu_die_from_dwo will allocate the abbreviation
7540      table from the DWO file and pass the ownership over to us.  It will be
7541      referenced from READER, so we must make sure to free it after we're done
7542      with READER.
7543
7544      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
7545      DWO CU, that this test will fail (the attribute will not be present).  */
7546   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
7547   abbrev_table_up dwo_abbrev_table;
7548   if (attr)
7549     {
7550       struct dwo_unit *dwo_unit;
7551       struct die_info *dwo_comp_unit_die;
7552
7553       if (has_children)
7554         {
7555           complaint (_("compilation unit with DW_AT_GNU_dwo_name"
7556                        " has children (offset %s) [in module %s]"),
7557                      sect_offset_str (this_cu->sect_off),
7558                      bfd_get_filename (abfd));
7559         }
7560       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
7561       if (dwo_unit != NULL)
7562         {
7563           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
7564                                       comp_unit_die, NULL,
7565                                       &reader, &info_ptr,
7566                                       &dwo_comp_unit_die, &has_children,
7567                                       &dwo_abbrev_table) == 0)
7568             {
7569               /* Dummy die.  */
7570               return;
7571             }
7572           comp_unit_die = dwo_comp_unit_die;
7573         }
7574       else
7575         {
7576           /* Yikes, we couldn't find the rest of the DIE, we only have
7577              the stub.  A complaint has already been logged.  There's
7578              not much more we can do except pass on the stub DIE to
7579              die_reader_func.  We don't want to throw an error on bad
7580              debug info.  */
7581         }
7582     }
7583
7584   /* All of the above is setup for this call.  Yikes.  */
7585   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7586
7587   /* Done, clean up.  */
7588   if (new_cu != NULL && keep)
7589     {
7590       /* Link this CU into read_in_chain.  */
7591       this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
7592       dwarf2_per_objfile->read_in_chain = this_cu;
7593       /* The chain owns it now.  */
7594       new_cu.release ();
7595     }
7596 }
7597
7598 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
7599    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
7600    to have already done the lookup to find the DWO file).
7601
7602    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
7603    THIS_CU->is_debug_types, but nothing else.
7604
7605    We fill in THIS_CU->length.
7606
7607    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
7608    linker) then DIE_READER_FUNC will not get called.
7609
7610    THIS_CU->cu is always freed when done.
7611    This is done in order to not leave THIS_CU->cu in a state where we have
7612    to care whether it refers to the "main" CU or the DWO CU.  */
7613
7614 static void
7615 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
7616                                    struct dwo_file *dwo_file,
7617                                    die_reader_func_ftype *die_reader_func,
7618                                    void *data)
7619 {
7620   struct dwarf2_per_objfile *dwarf2_per_objfile = this_cu->dwarf2_per_objfile;
7621   struct objfile *objfile = dwarf2_per_objfile->objfile;
7622   struct dwarf2_section_info *section = this_cu->section;
7623   bfd *abfd = get_section_bfd_owner (section);
7624   struct dwarf2_section_info *abbrev_section;
7625   const gdb_byte *begin_info_ptr, *info_ptr;
7626   struct die_reader_specs reader;
7627   struct die_info *comp_unit_die;
7628   int has_children;
7629
7630   if (dwarf_die_debug)
7631     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset %s\n",
7632                         this_cu->is_debug_types ? "type" : "comp",
7633                         sect_offset_str (this_cu->sect_off));
7634
7635   gdb_assert (this_cu->cu == NULL);
7636
7637   abbrev_section = (dwo_file != NULL
7638                     ? &dwo_file->sections.abbrev
7639                     : get_abbrev_section_for_cu (this_cu));
7640
7641   /* This is cheap if the section is already read in.  */
7642   dwarf2_read_section (objfile, section);
7643
7644   struct dwarf2_cu cu (this_cu);
7645
7646   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
7647   info_ptr = read_and_check_comp_unit_head (dwarf2_per_objfile,
7648                                             &cu.header, section,
7649                                             abbrev_section, info_ptr,
7650                                             (this_cu->is_debug_types
7651                                              ? rcuh_kind::TYPE
7652                                              : rcuh_kind::COMPILE));
7653
7654   this_cu->length = get_cu_length (&cu.header);
7655
7656   /* Skip dummy compilation units.  */
7657   if (info_ptr >= begin_info_ptr + this_cu->length
7658       || peek_abbrev_code (abfd, info_ptr) == 0)
7659     return;
7660
7661   abbrev_table_up abbrev_table
7662     = abbrev_table_read_table (dwarf2_per_objfile, abbrev_section,
7663                                cu.header.abbrev_sect_off);
7664
7665   init_cu_die_reader (&reader, &cu, section, dwo_file, abbrev_table.get ());
7666   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
7667
7668   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
7669 }
7670
7671 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
7672    does not lookup the specified DWO file.
7673    This cannot be used to read DWO files.
7674
7675    THIS_CU->cu is always freed when done.
7676    This is done in order to not leave THIS_CU->cu in a state where we have
7677    to care whether it refers to the "main" CU or the DWO CU.
7678    We can revisit this if the data shows there's a performance issue.  */
7679
7680 static void
7681 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
7682                                 die_reader_func_ftype *die_reader_func,
7683                                 void *data)
7684 {
7685   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
7686 }
7687 \f
7688 /* Type Unit Groups.
7689
7690    Type Unit Groups are a way to collapse the set of all TUs (type units) into
7691    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
7692    so that all types coming from the same compilation (.o file) are grouped
7693    together.  A future step could be to put the types in the same symtab as
7694    the CU the types ultimately came from.  */
7695
7696 static hashval_t
7697 hash_type_unit_group (const void *item)
7698 {
7699   const struct type_unit_group *tu_group
7700     = (const struct type_unit_group *) item;
7701
7702   return hash_stmt_list_entry (&tu_group->hash);
7703 }
7704
7705 static int
7706 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
7707 {
7708   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
7709   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
7710
7711   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
7712 }
7713
7714 /* Allocate a hash table for type unit groups.  */
7715
7716 static htab_t
7717 allocate_type_unit_groups_table (struct objfile *objfile)
7718 {
7719   return htab_create_alloc_ex (3,
7720                                hash_type_unit_group,
7721                                eq_type_unit_group,
7722                                NULL,
7723                                &objfile->objfile_obstack,
7724                                hashtab_obstack_allocate,
7725                                dummy_obstack_deallocate);
7726 }
7727
7728 /* Type units that don't have DW_AT_stmt_list are grouped into their own
7729    partial symtabs.  We combine several TUs per psymtab to not let the size
7730    of any one psymtab grow too big.  */
7731 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
7732 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
7733
7734 /* Helper routine for get_type_unit_group.
7735    Create the type_unit_group object used to hold one or more TUs.  */
7736
7737 static struct type_unit_group *
7738 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
7739 {
7740   struct dwarf2_per_objfile *dwarf2_per_objfile
7741     = cu->per_cu->dwarf2_per_objfile;
7742   struct objfile *objfile = dwarf2_per_objfile->objfile;
7743   struct dwarf2_per_cu_data *per_cu;
7744   struct type_unit_group *tu_group;
7745
7746   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7747                              struct type_unit_group);
7748   per_cu = &tu_group->per_cu;
7749   per_cu->dwarf2_per_objfile = dwarf2_per_objfile;
7750
7751   if (dwarf2_per_objfile->using_index)
7752     {
7753       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
7754                                         struct dwarf2_per_cu_quick_data);
7755     }
7756   else
7757     {
7758       unsigned int line_offset = to_underlying (line_offset_struct);
7759       struct partial_symtab *pst;
7760       char *name;
7761
7762       /* Give the symtab a useful name for debug purposes.  */
7763       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
7764         name = xstrprintf ("<type_units_%d>",
7765                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
7766       else
7767         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
7768
7769       pst = create_partial_symtab (per_cu, name);
7770       pst->anonymous = 1;
7771
7772       xfree (name);
7773     }
7774
7775   tu_group->hash.dwo_unit = cu->dwo_unit;
7776   tu_group->hash.line_sect_off = line_offset_struct;
7777
7778   return tu_group;
7779 }
7780
7781 /* Look up the type_unit_group for type unit CU, and create it if necessary.
7782    STMT_LIST is a DW_AT_stmt_list attribute.  */
7783
7784 static struct type_unit_group *
7785 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
7786 {
7787   struct dwarf2_per_objfile *dwarf2_per_objfile
7788     = cu->per_cu->dwarf2_per_objfile;
7789   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7790   struct type_unit_group *tu_group;
7791   void **slot;
7792   unsigned int line_offset;
7793   struct type_unit_group type_unit_group_for_lookup;
7794
7795   if (dwarf2_per_objfile->type_unit_groups == NULL)
7796     {
7797       dwarf2_per_objfile->type_unit_groups =
7798         allocate_type_unit_groups_table (dwarf2_per_objfile->objfile);
7799     }
7800
7801   /* Do we need to create a new group, or can we use an existing one?  */
7802
7803   if (stmt_list)
7804     {
7805       line_offset = DW_UNSND (stmt_list);
7806       ++tu_stats->nr_symtab_sharers;
7807     }
7808   else
7809     {
7810       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7811          We can do various things here like create one group per TU or
7812          spread them over multiple groups to split up the expansion work.
7813          To avoid worst case scenarios (too many groups or too large groups)
7814          we, umm, group them in bunches.  */
7815       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7816                      | (tu_stats->nr_stmt_less_type_units
7817                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7818       ++tu_stats->nr_stmt_less_type_units;
7819     }
7820
7821   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7822   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7823   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7824                          &type_unit_group_for_lookup, INSERT);
7825   if (*slot != NULL)
7826     {
7827       tu_group = (struct type_unit_group *) *slot;
7828       gdb_assert (tu_group != NULL);
7829     }
7830   else
7831     {
7832       sect_offset line_offset_struct = (sect_offset) line_offset;
7833       tu_group = create_type_unit_group (cu, line_offset_struct);
7834       *slot = tu_group;
7835       ++tu_stats->nr_symtabs;
7836     }
7837
7838   return tu_group;
7839 }
7840 \f
7841 /* Partial symbol tables.  */
7842
7843 /* Create a psymtab named NAME and assign it to PER_CU.
7844
7845    The caller must fill in the following details:
7846    dirname, textlow, texthigh.  */
7847
7848 static struct partial_symtab *
7849 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7850 {
7851   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
7852   struct partial_symtab *pst;
7853
7854   pst = start_psymtab_common (objfile, name, 0,
7855                               objfile->global_psymbols,
7856                               objfile->static_psymbols);
7857
7858   pst->psymtabs_addrmap_supported = 1;
7859
7860   /* This is the glue that links PST into GDB's symbol API.  */
7861   pst->read_symtab_private = per_cu;
7862   pst->read_symtab = dwarf2_read_symtab;
7863   per_cu->v.psymtab = pst;
7864
7865   return pst;
7866 }
7867
7868 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7869    type.  */
7870
7871 struct process_psymtab_comp_unit_data
7872 {
7873   /* True if we are reading a DW_TAG_partial_unit.  */
7874
7875   int want_partial_unit;
7876
7877   /* The "pretend" language that is used if the CU doesn't declare a
7878      language.  */
7879
7880   enum language pretend_language;
7881 };
7882
7883 /* die_reader_func for process_psymtab_comp_unit.  */
7884
7885 static void
7886 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7887                                   const gdb_byte *info_ptr,
7888                                   struct die_info *comp_unit_die,
7889                                   int has_children,
7890                                   void *data)
7891 {
7892   struct dwarf2_cu *cu = reader->cu;
7893   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
7894   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7895   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7896   CORE_ADDR baseaddr;
7897   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7898   struct partial_symtab *pst;
7899   enum pc_bounds_kind cu_bounds_kind;
7900   const char *filename;
7901   struct process_psymtab_comp_unit_data *info
7902     = (struct process_psymtab_comp_unit_data *) data;
7903
7904   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7905     return;
7906
7907   gdb_assert (! per_cu->is_debug_types);
7908
7909   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7910
7911   cu->list_in_scope = &file_symbols;
7912
7913   /* Allocate a new partial symbol table structure.  */
7914   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7915   if (filename == NULL)
7916     filename = "";
7917
7918   pst = create_partial_symtab (per_cu, filename);
7919
7920   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7921   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7922
7923   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7924
7925   dwarf2_find_base_address (comp_unit_die, cu);
7926
7927   /* Possibly set the default values of LOWPC and HIGHPC from
7928      `DW_AT_ranges'.  */
7929   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7930                                          &best_highpc, cu, pst);
7931   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7932     /* Store the contiguous range if it is not empty; it can be empty for
7933        CUs with no code.  */
7934     addrmap_set_empty (objfile->psymtabs_addrmap,
7935                        gdbarch_adjust_dwarf2_addr (gdbarch,
7936                                                    best_lowpc + baseaddr),
7937                        gdbarch_adjust_dwarf2_addr (gdbarch,
7938                                                    best_highpc + baseaddr) - 1,
7939                        pst);
7940
7941   /* Check if comp unit has_children.
7942      If so, read the rest of the partial symbols from this comp unit.
7943      If not, there's no more debug_info for this comp unit.  */
7944   if (has_children)
7945     {
7946       struct partial_die_info *first_die;
7947       CORE_ADDR lowpc, highpc;
7948
7949       lowpc = ((CORE_ADDR) -1);
7950       highpc = ((CORE_ADDR) 0);
7951
7952       first_die = load_partial_dies (reader, info_ptr, 1);
7953
7954       scan_partial_symbols (first_die, &lowpc, &highpc,
7955                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7956
7957       /* If we didn't find a lowpc, set it to highpc to avoid
7958          complaints from `maint check'.  */
7959       if (lowpc == ((CORE_ADDR) -1))
7960         lowpc = highpc;
7961
7962       /* If the compilation unit didn't have an explicit address range,
7963          then use the information extracted from its child dies.  */
7964       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7965         {
7966           best_lowpc = lowpc;
7967           best_highpc = highpc;
7968         }
7969     }
7970   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
7971   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
7972
7973   end_psymtab_common (objfile, pst);
7974
7975   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
7976     {
7977       int i;
7978       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7979       struct dwarf2_per_cu_data *iter;
7980
7981       /* Fill in 'dependencies' here; we fill in 'users' in a
7982          post-pass.  */
7983       pst->number_of_dependencies = len;
7984       pst->dependencies =
7985         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7986       for (i = 0;
7987            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7988                         i, iter);
7989            ++i)
7990         pst->dependencies[i] = iter->v.psymtab;
7991
7992       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7993     }
7994
7995   /* Get the list of files included in the current compilation unit,
7996      and build a psymtab for each of them.  */
7997   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7998
7999   if (dwarf_read_debug)
8000     {
8001       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8002
8003       fprintf_unfiltered (gdb_stdlog,
8004                           "Psymtab for %s unit @%s: %s - %s"
8005                           ", %d global, %d static syms\n",
8006                           per_cu->is_debug_types ? "type" : "comp",
8007                           sect_offset_str (per_cu->sect_off),
8008                           paddress (gdbarch, pst->textlow),
8009                           paddress (gdbarch, pst->texthigh),
8010                           pst->n_global_syms, pst->n_static_syms);
8011     }
8012 }
8013
8014 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8015    Process compilation unit THIS_CU for a psymtab.  */
8016
8017 static void
8018 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8019                            int want_partial_unit,
8020                            enum language pretend_language)
8021 {
8022   /* If this compilation unit was already read in, free the
8023      cached copy in order to read it in again.  This is
8024      necessary because we skipped some symbols when we first
8025      read in the compilation unit (see load_partial_dies).
8026      This problem could be avoided, but the benefit is unclear.  */
8027   if (this_cu->cu != NULL)
8028     free_one_cached_comp_unit (this_cu);
8029
8030   if (this_cu->is_debug_types)
8031     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8032                              build_type_psymtabs_reader, NULL);
8033   else
8034     {
8035       process_psymtab_comp_unit_data info;
8036       info.want_partial_unit = want_partial_unit;
8037       info.pretend_language = pretend_language;
8038       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8039                                process_psymtab_comp_unit_reader, &info);
8040     }
8041
8042   /* Age out any secondary CUs.  */
8043   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8044 }
8045
8046 /* Reader function for build_type_psymtabs.  */
8047
8048 static void
8049 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8050                             const gdb_byte *info_ptr,
8051                             struct die_info *type_unit_die,
8052                             int has_children,
8053                             void *data)
8054 {
8055   struct dwarf2_per_objfile *dwarf2_per_objfile
8056     = reader->cu->per_cu->dwarf2_per_objfile;
8057   struct objfile *objfile = dwarf2_per_objfile->objfile;
8058   struct dwarf2_cu *cu = reader->cu;
8059   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8060   struct signatured_type *sig_type;
8061   struct type_unit_group *tu_group;
8062   struct attribute *attr;
8063   struct partial_die_info *first_die;
8064   CORE_ADDR lowpc, highpc;
8065   struct partial_symtab *pst;
8066
8067   gdb_assert (data == NULL);
8068   gdb_assert (per_cu->is_debug_types);
8069   sig_type = (struct signatured_type *) per_cu;
8070
8071   if (! has_children)
8072     return;
8073
8074   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8075   tu_group = get_type_unit_group (cu, attr);
8076
8077   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8078
8079   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8080   cu->list_in_scope = &file_symbols;
8081   pst = create_partial_symtab (per_cu, "");
8082   pst->anonymous = 1;
8083
8084   first_die = load_partial_dies (reader, info_ptr, 1);
8085
8086   lowpc = (CORE_ADDR) -1;
8087   highpc = (CORE_ADDR) 0;
8088   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8089
8090   end_psymtab_common (objfile, pst);
8091 }
8092
8093 /* Struct used to sort TUs by their abbreviation table offset.  */
8094
8095 struct tu_abbrev_offset
8096 {
8097   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8098   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8099   {}
8100
8101   signatured_type *sig_type;
8102   sect_offset abbrev_offset;
8103 };
8104
8105 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8106
8107 static bool
8108 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8109                           const struct tu_abbrev_offset &b)
8110 {
8111   return a.abbrev_offset < b.abbrev_offset;
8112 }
8113
8114 /* Efficiently read all the type units.
8115    This does the bulk of the work for build_type_psymtabs.
8116
8117    The efficiency is because we sort TUs by the abbrev table they use and
8118    only read each abbrev table once.  In one program there are 200K TUs
8119    sharing 8K abbrev tables.
8120
8121    The main purpose of this function is to support building the
8122    dwarf2_per_objfile->type_unit_groups table.
8123    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8124    can collapse the search space by grouping them by stmt_list.
8125    The savings can be significant, in the same program from above the 200K TUs
8126    share 8K stmt_list tables.
8127
8128    FUNC is expected to call get_type_unit_group, which will create the
8129    struct type_unit_group if necessary and add it to
8130    dwarf2_per_objfile->type_unit_groups.  */
8131
8132 static void
8133 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8134 {
8135   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8136   abbrev_table_up abbrev_table;
8137   sect_offset abbrev_offset;
8138
8139   /* It's up to the caller to not call us multiple times.  */
8140   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8141
8142   if (dwarf2_per_objfile->all_type_units.empty ())
8143     return;
8144
8145   /* TUs typically share abbrev tables, and there can be way more TUs than
8146      abbrev tables.  Sort by abbrev table to reduce the number of times we
8147      read each abbrev table in.
8148      Alternatives are to punt or to maintain a cache of abbrev tables.
8149      This is simpler and efficient enough for now.
8150
8151      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8152      symtab to use).  Typically TUs with the same abbrev offset have the same
8153      stmt_list value too so in practice this should work well.
8154
8155      The basic algorithm here is:
8156
8157       sort TUs by abbrev table
8158       for each TU with same abbrev table:
8159         read abbrev table if first user
8160         read TU top level DIE
8161           [IWBN if DWO skeletons had DW_AT_stmt_list]
8162         call FUNC  */
8163
8164   if (dwarf_read_debug)
8165     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8166
8167   /* Sort in a separate table to maintain the order of all_type_units
8168      for .gdb_index: TU indices directly index all_type_units.  */
8169   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8170   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8171
8172   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8173     sorted_by_abbrev.emplace_back
8174       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8175                                      sig_type->per_cu.section,
8176                                      sig_type->per_cu.sect_off));
8177
8178   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8179              sort_tu_by_abbrev_offset);
8180
8181   abbrev_offset = (sect_offset) ~(unsigned) 0;
8182
8183   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8184     {
8185       /* Switch to the next abbrev table if necessary.  */
8186       if (abbrev_table == NULL
8187           || tu.abbrev_offset != abbrev_offset)
8188         {
8189           abbrev_offset = tu.abbrev_offset;
8190           abbrev_table =
8191             abbrev_table_read_table (dwarf2_per_objfile,
8192                                      &dwarf2_per_objfile->abbrev,
8193                                      abbrev_offset);
8194           ++tu_stats->nr_uniq_abbrev_tables;
8195         }
8196
8197       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8198                                0, 0, false, build_type_psymtabs_reader, NULL);
8199     }
8200 }
8201
8202 /* Print collected type unit statistics.  */
8203
8204 static void
8205 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8206 {
8207   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8208
8209   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8210   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8211                       dwarf2_per_objfile->all_type_units.size ());
8212   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8213                       tu_stats->nr_uniq_abbrev_tables);
8214   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8215                       tu_stats->nr_symtabs);
8216   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8217                       tu_stats->nr_symtab_sharers);
8218   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8219                       tu_stats->nr_stmt_less_type_units);
8220   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8221                       tu_stats->nr_all_type_units_reallocs);
8222 }
8223
8224 /* Traversal function for build_type_psymtabs.  */
8225
8226 static int
8227 build_type_psymtab_dependencies (void **slot, void *info)
8228 {
8229   struct dwarf2_per_objfile *dwarf2_per_objfile
8230     = (struct dwarf2_per_objfile *) info;
8231   struct objfile *objfile = dwarf2_per_objfile->objfile;
8232   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8233   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8234   struct partial_symtab *pst = per_cu->v.psymtab;
8235   int len = VEC_length (sig_type_ptr, tu_group->tus);
8236   struct signatured_type *iter;
8237   int i;
8238
8239   gdb_assert (len > 0);
8240   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8241
8242   pst->number_of_dependencies = len;
8243   pst->dependencies =
8244     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8245   for (i = 0;
8246        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8247        ++i)
8248     {
8249       gdb_assert (iter->per_cu.is_debug_types);
8250       pst->dependencies[i] = iter->per_cu.v.psymtab;
8251       iter->type_unit_group = tu_group;
8252     }
8253
8254   VEC_free (sig_type_ptr, tu_group->tus);
8255
8256   return 1;
8257 }
8258
8259 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8260    Build partial symbol tables for the .debug_types comp-units.  */
8261
8262 static void
8263 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8264 {
8265   if (! create_all_type_units (dwarf2_per_objfile))
8266     return;
8267
8268   build_type_psymtabs_1 (dwarf2_per_objfile);
8269 }
8270
8271 /* Traversal function for process_skeletonless_type_unit.
8272    Read a TU in a DWO file and build partial symbols for it.  */
8273
8274 static int
8275 process_skeletonless_type_unit (void **slot, void *info)
8276 {
8277   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8278   struct dwarf2_per_objfile *dwarf2_per_objfile
8279     = (struct dwarf2_per_objfile *) info;
8280   struct signatured_type find_entry, *entry;
8281
8282   /* If this TU doesn't exist in the global table, add it and read it in.  */
8283
8284   if (dwarf2_per_objfile->signatured_types == NULL)
8285     {
8286       dwarf2_per_objfile->signatured_types
8287         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8288     }
8289
8290   find_entry.signature = dwo_unit->signature;
8291   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8292                          INSERT);
8293   /* If we've already seen this type there's nothing to do.  What's happening
8294      is we're doing our own version of comdat-folding here.  */
8295   if (*slot != NULL)
8296     return 1;
8297
8298   /* This does the job that create_all_type_units would have done for
8299      this TU.  */
8300   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8301   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8302   *slot = entry;
8303
8304   /* This does the job that build_type_psymtabs_1 would have done.  */
8305   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8306                            build_type_psymtabs_reader, NULL);
8307
8308   return 1;
8309 }
8310
8311 /* Traversal function for process_skeletonless_type_units.  */
8312
8313 static int
8314 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8315 {
8316   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8317
8318   if (dwo_file->tus != NULL)
8319     {
8320       htab_traverse_noresize (dwo_file->tus,
8321                               process_skeletonless_type_unit, info);
8322     }
8323
8324   return 1;
8325 }
8326
8327 /* Scan all TUs of DWO files, verifying we've processed them.
8328    This is needed in case a TU was emitted without its skeleton.
8329    Note: This can't be done until we know what all the DWO files are.  */
8330
8331 static void
8332 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8333 {
8334   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8335   if (get_dwp_file (dwarf2_per_objfile) == NULL
8336       && dwarf2_per_objfile->dwo_files != NULL)
8337     {
8338       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8339                               process_dwo_file_for_skeletonless_type_units,
8340                               dwarf2_per_objfile);
8341     }
8342 }
8343
8344 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8345
8346 static void
8347 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8348 {
8349   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8350     {
8351       struct partial_symtab *pst = per_cu->v.psymtab;
8352
8353       if (pst == NULL)
8354         continue;
8355
8356       for (int j = 0; j < pst->number_of_dependencies; ++j)
8357         {
8358           /* Set the 'user' field only if it is not already set.  */
8359           if (pst->dependencies[j]->user == NULL)
8360             pst->dependencies[j]->user = pst;
8361         }
8362     }
8363 }
8364
8365 /* Build the partial symbol table by doing a quick pass through the
8366    .debug_info and .debug_abbrev sections.  */
8367
8368 static void
8369 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8370 {
8371   struct objfile *objfile = dwarf2_per_objfile->objfile;
8372
8373   if (dwarf_read_debug)
8374     {
8375       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8376                           objfile_name (objfile));
8377     }
8378
8379   dwarf2_per_objfile->reading_partial_symbols = 1;
8380
8381   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8382
8383   /* Any cached compilation units will be linked by the per-objfile
8384      read_in_chain.  Make sure to free them when we're done.  */
8385   free_cached_comp_units freer (dwarf2_per_objfile);
8386
8387   build_type_psymtabs (dwarf2_per_objfile);
8388
8389   create_all_comp_units (dwarf2_per_objfile);
8390
8391   /* Create a temporary address map on a temporary obstack.  We later
8392      copy this to the final obstack.  */
8393   auto_obstack temp_obstack;
8394
8395   scoped_restore save_psymtabs_addrmap
8396     = make_scoped_restore (&objfile->psymtabs_addrmap,
8397                            addrmap_create_mutable (&temp_obstack));
8398
8399   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8400     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8401
8402   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8403   process_skeletonless_type_units (dwarf2_per_objfile);
8404
8405   /* Now that all TUs have been processed we can fill in the dependencies.  */
8406   if (dwarf2_per_objfile->type_unit_groups != NULL)
8407     {
8408       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8409                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8410     }
8411
8412   if (dwarf_read_debug)
8413     print_tu_stats (dwarf2_per_objfile);
8414
8415   set_partial_user (dwarf2_per_objfile);
8416
8417   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8418                                                     &objfile->objfile_obstack);
8419   /* At this point we want to keep the address map.  */
8420   save_psymtabs_addrmap.release ();
8421
8422   if (dwarf_read_debug)
8423     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8424                         objfile_name (objfile));
8425 }
8426
8427 /* die_reader_func for load_partial_comp_unit.  */
8428
8429 static void
8430 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8431                                const gdb_byte *info_ptr,
8432                                struct die_info *comp_unit_die,
8433                                int has_children,
8434                                void *data)
8435 {
8436   struct dwarf2_cu *cu = reader->cu;
8437
8438   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8439
8440   /* Check if comp unit has_children.
8441      If so, read the rest of the partial symbols from this comp unit.
8442      If not, there's no more debug_info for this comp unit.  */
8443   if (has_children)
8444     load_partial_dies (reader, info_ptr, 0);
8445 }
8446
8447 /* Load the partial DIEs for a secondary CU into memory.
8448    This is also used when rereading a primary CU with load_all_dies.  */
8449
8450 static void
8451 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8452 {
8453   init_cutu_and_read_dies (this_cu, NULL, 1, 1, false,
8454                            load_partial_comp_unit_reader, NULL);
8455 }
8456
8457 static void
8458 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8459                               struct dwarf2_section_info *section,
8460                               struct dwarf2_section_info *abbrev_section,
8461                               unsigned int is_dwz)
8462 {
8463   const gdb_byte *info_ptr;
8464   struct objfile *objfile = dwarf2_per_objfile->objfile;
8465
8466   if (dwarf_read_debug)
8467     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8468                         get_section_name (section),
8469                         get_section_file_name (section));
8470
8471   dwarf2_read_section (objfile, section);
8472
8473   info_ptr = section->buffer;
8474
8475   while (info_ptr < section->buffer + section->size)
8476     {
8477       struct dwarf2_per_cu_data *this_cu;
8478
8479       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8480
8481       comp_unit_head cu_header;
8482       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8483                                      abbrev_section, info_ptr,
8484                                      rcuh_kind::COMPILE);
8485
8486       /* Save the compilation unit for later lookup.  */
8487       if (cu_header.unit_type != DW_UT_type)
8488         {
8489           this_cu = XOBNEW (&objfile->objfile_obstack,
8490                             struct dwarf2_per_cu_data);
8491           memset (this_cu, 0, sizeof (*this_cu));
8492         }
8493       else
8494         {
8495           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8496                                   struct signatured_type);
8497           memset (sig_type, 0, sizeof (*sig_type));
8498           sig_type->signature = cu_header.signature;
8499           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8500           this_cu = &sig_type->per_cu;
8501         }
8502       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8503       this_cu->sect_off = sect_off;
8504       this_cu->length = cu_header.length + cu_header.initial_length_size;
8505       this_cu->is_dwz = is_dwz;
8506       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8507       this_cu->section = section;
8508
8509       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8510
8511       info_ptr = info_ptr + this_cu->length;
8512     }
8513 }
8514
8515 /* Create a list of all compilation units in OBJFILE.
8516    This is only done for -readnow and building partial symtabs.  */
8517
8518 static void
8519 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8520 {
8521   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8522   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8523                                 &dwarf2_per_objfile->abbrev, 0);
8524
8525   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8526   if (dwz != NULL)
8527     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8528                                   1);
8529 }
8530
8531 /* Process all loaded DIEs for compilation unit CU, starting at
8532    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8533    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8534    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8535    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8536
8537 static void
8538 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8539                       CORE_ADDR *highpc, int set_addrmap,
8540                       struct dwarf2_cu *cu)
8541 {
8542   struct partial_die_info *pdi;
8543
8544   /* Now, march along the PDI's, descending into ones which have
8545      interesting children but skipping the children of the other ones,
8546      until we reach the end of the compilation unit.  */
8547
8548   pdi = first_die;
8549
8550   while (pdi != NULL)
8551     {
8552       pdi->fixup (cu);
8553
8554       /* Anonymous namespaces or modules have no name but have interesting
8555          children, so we need to look at them.  Ditto for anonymous
8556          enums.  */
8557
8558       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8559           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8560           || pdi->tag == DW_TAG_imported_unit
8561           || pdi->tag == DW_TAG_inlined_subroutine)
8562         {
8563           switch (pdi->tag)
8564             {
8565             case DW_TAG_subprogram:
8566             case DW_TAG_inlined_subroutine:
8567               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8568               break;
8569             case DW_TAG_constant:
8570             case DW_TAG_variable:
8571             case DW_TAG_typedef:
8572             case DW_TAG_union_type:
8573               if (!pdi->is_declaration)
8574                 {
8575                   add_partial_symbol (pdi, cu);
8576                 }
8577               break;
8578             case DW_TAG_class_type:
8579             case DW_TAG_interface_type:
8580             case DW_TAG_structure_type:
8581               if (!pdi->is_declaration)
8582                 {
8583                   add_partial_symbol (pdi, cu);
8584                 }
8585               if ((cu->language == language_rust
8586                    || cu->language == language_cplus) && pdi->has_children)
8587                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8588                                       set_addrmap, cu);
8589               break;
8590             case DW_TAG_enumeration_type:
8591               if (!pdi->is_declaration)
8592                 add_partial_enumeration (pdi, cu);
8593               break;
8594             case DW_TAG_base_type:
8595             case DW_TAG_subrange_type:
8596               /* File scope base type definitions are added to the partial
8597                  symbol table.  */
8598               add_partial_symbol (pdi, cu);
8599               break;
8600             case DW_TAG_namespace:
8601               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8602               break;
8603             case DW_TAG_module:
8604               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8605               break;
8606             case DW_TAG_imported_unit:
8607               {
8608                 struct dwarf2_per_cu_data *per_cu;
8609
8610                 /* For now we don't handle imported units in type units.  */
8611                 if (cu->per_cu->is_debug_types)
8612                   {
8613                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8614                              " supported in type units [in module %s]"),
8615                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8616                   }
8617
8618                 per_cu = dwarf2_find_containing_comp_unit
8619                            (pdi->d.sect_off, pdi->is_dwz,
8620                             cu->per_cu->dwarf2_per_objfile);
8621
8622                 /* Go read the partial unit, if needed.  */
8623                 if (per_cu->v.psymtab == NULL)
8624                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8625
8626                 VEC_safe_push (dwarf2_per_cu_ptr,
8627                                cu->per_cu->imported_symtabs, per_cu);
8628               }
8629               break;
8630             case DW_TAG_imported_declaration:
8631               add_partial_symbol (pdi, cu);
8632               break;
8633             default:
8634               break;
8635             }
8636         }
8637
8638       /* If the die has a sibling, skip to the sibling.  */
8639
8640       pdi = pdi->die_sibling;
8641     }
8642 }
8643
8644 /* Functions used to compute the fully scoped name of a partial DIE.
8645
8646    Normally, this is simple.  For C++, the parent DIE's fully scoped
8647    name is concatenated with "::" and the partial DIE's name.
8648    Enumerators are an exception; they use the scope of their parent
8649    enumeration type, i.e. the name of the enumeration type is not
8650    prepended to the enumerator.
8651
8652    There are two complexities.  One is DW_AT_specification; in this
8653    case "parent" means the parent of the target of the specification,
8654    instead of the direct parent of the DIE.  The other is compilers
8655    which do not emit DW_TAG_namespace; in this case we try to guess
8656    the fully qualified name of structure types from their members'
8657    linkage names.  This must be done using the DIE's children rather
8658    than the children of any DW_AT_specification target.  We only need
8659    to do this for structures at the top level, i.e. if the target of
8660    any DW_AT_specification (if any; otherwise the DIE itself) does not
8661    have a parent.  */
8662
8663 /* Compute the scope prefix associated with PDI's parent, in
8664    compilation unit CU.  The result will be allocated on CU's
8665    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8666    field.  NULL is returned if no prefix is necessary.  */
8667 static const char *
8668 partial_die_parent_scope (struct partial_die_info *pdi,
8669                           struct dwarf2_cu *cu)
8670 {
8671   const char *grandparent_scope;
8672   struct partial_die_info *parent, *real_pdi;
8673
8674   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8675      then this means the parent of the specification DIE.  */
8676
8677   real_pdi = pdi;
8678   while (real_pdi->has_specification)
8679     real_pdi = find_partial_die (real_pdi->spec_offset,
8680                                  real_pdi->spec_is_dwz, cu);
8681
8682   parent = real_pdi->die_parent;
8683   if (parent == NULL)
8684     return NULL;
8685
8686   if (parent->scope_set)
8687     return parent->scope;
8688
8689   parent->fixup (cu);
8690
8691   grandparent_scope = partial_die_parent_scope (parent, cu);
8692
8693   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8694      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8695      Work around this problem here.  */
8696   if (cu->language == language_cplus
8697       && parent->tag == DW_TAG_namespace
8698       && strcmp (parent->name, "::") == 0
8699       && grandparent_scope == NULL)
8700     {
8701       parent->scope = NULL;
8702       parent->scope_set = 1;
8703       return NULL;
8704     }
8705
8706   if (pdi->tag == DW_TAG_enumerator)
8707     /* Enumerators should not get the name of the enumeration as a prefix.  */
8708     parent->scope = grandparent_scope;
8709   else if (parent->tag == DW_TAG_namespace
8710       || parent->tag == DW_TAG_module
8711       || parent->tag == DW_TAG_structure_type
8712       || parent->tag == DW_TAG_class_type
8713       || parent->tag == DW_TAG_interface_type
8714       || parent->tag == DW_TAG_union_type
8715       || parent->tag == DW_TAG_enumeration_type)
8716     {
8717       if (grandparent_scope == NULL)
8718         parent->scope = parent->name;
8719       else
8720         parent->scope = typename_concat (&cu->comp_unit_obstack,
8721                                          grandparent_scope,
8722                                          parent->name, 0, cu);
8723     }
8724   else
8725     {
8726       /* FIXME drow/2004-04-01: What should we be doing with
8727          function-local names?  For partial symbols, we should probably be
8728          ignoring them.  */
8729       complaint (_("unhandled containing DIE tag %d for DIE at %s"),
8730                  parent->tag, sect_offset_str (pdi->sect_off));
8731       parent->scope = grandparent_scope;
8732     }
8733
8734   parent->scope_set = 1;
8735   return parent->scope;
8736 }
8737
8738 /* Return the fully scoped name associated with PDI, from compilation unit
8739    CU.  The result will be allocated with malloc.  */
8740
8741 static char *
8742 partial_die_full_name (struct partial_die_info *pdi,
8743                        struct dwarf2_cu *cu)
8744 {
8745   const char *parent_scope;
8746
8747   /* If this is a template instantiation, we can not work out the
8748      template arguments from partial DIEs.  So, unfortunately, we have
8749      to go through the full DIEs.  At least any work we do building
8750      types here will be reused if full symbols are loaded later.  */
8751   if (pdi->has_template_arguments)
8752     {
8753       pdi->fixup (cu);
8754
8755       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8756         {
8757           struct die_info *die;
8758           struct attribute attr;
8759           struct dwarf2_cu *ref_cu = cu;
8760
8761           /* DW_FORM_ref_addr is using section offset.  */
8762           attr.name = (enum dwarf_attribute) 0;
8763           attr.form = DW_FORM_ref_addr;
8764           attr.u.unsnd = to_underlying (pdi->sect_off);
8765           die = follow_die_ref (NULL, &attr, &ref_cu);
8766
8767           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8768         }
8769     }
8770
8771   parent_scope = partial_die_parent_scope (pdi, cu);
8772   if (parent_scope == NULL)
8773     return NULL;
8774   else
8775     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8776 }
8777
8778 static void
8779 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8780 {
8781   struct dwarf2_per_objfile *dwarf2_per_objfile
8782     = cu->per_cu->dwarf2_per_objfile;
8783   struct objfile *objfile = dwarf2_per_objfile->objfile;
8784   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8785   CORE_ADDR addr = 0;
8786   const char *actual_name = NULL;
8787   CORE_ADDR baseaddr;
8788   char *built_actual_name;
8789
8790   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8791
8792   built_actual_name = partial_die_full_name (pdi, cu);
8793   if (built_actual_name != NULL)
8794     actual_name = built_actual_name;
8795
8796   if (actual_name == NULL)
8797     actual_name = pdi->name;
8798
8799   switch (pdi->tag)
8800     {
8801     case DW_TAG_inlined_subroutine:
8802     case DW_TAG_subprogram:
8803       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
8804       if (pdi->is_external || cu->language == language_ada)
8805         {
8806           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8807              of the global scope.  But in Ada, we want to be able to access
8808              nested procedures globally.  So all Ada subprograms are stored
8809              in the global scope.  */
8810           add_psymbol_to_list (actual_name, strlen (actual_name),
8811                                built_actual_name != NULL,
8812                                VAR_DOMAIN, LOC_BLOCK,
8813                                &objfile->global_psymbols,
8814                                addr, cu->language, objfile);
8815         }
8816       else
8817         {
8818           add_psymbol_to_list (actual_name, strlen (actual_name),
8819                                built_actual_name != NULL,
8820                                VAR_DOMAIN, LOC_BLOCK,
8821                                &objfile->static_psymbols,
8822                                addr, cu->language, objfile);
8823         }
8824
8825       if (pdi->main_subprogram && actual_name != NULL)
8826         set_objfile_main_name (objfile, actual_name, cu->language);
8827       break;
8828     case DW_TAG_constant:
8829       {
8830         std::vector<partial_symbol *> *list;
8831
8832         if (pdi->is_external)
8833           list = &objfile->global_psymbols;
8834         else
8835           list = &objfile->static_psymbols;
8836         add_psymbol_to_list (actual_name, strlen (actual_name),
8837                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8838                              list, 0, cu->language, objfile);
8839       }
8840       break;
8841     case DW_TAG_variable:
8842       if (pdi->d.locdesc)
8843         addr = decode_locdesc (pdi->d.locdesc, cu);
8844
8845       if (pdi->d.locdesc
8846           && addr == 0
8847           && !dwarf2_per_objfile->has_section_at_zero)
8848         {
8849           /* A global or static variable may also have been stripped
8850              out by the linker if unused, in which case its address
8851              will be nullified; do not add such variables into partial
8852              symbol table then.  */
8853         }
8854       else if (pdi->is_external)
8855         {
8856           /* Global Variable.
8857              Don't enter into the minimal symbol tables as there is
8858              a minimal symbol table entry from the ELF symbols already.
8859              Enter into partial symbol table if it has a location
8860              descriptor or a type.
8861              If the location descriptor is missing, new_symbol will create
8862              a LOC_UNRESOLVED symbol, the address of the variable will then
8863              be determined from the minimal symbol table whenever the variable
8864              is referenced.
8865              The address for the partial symbol table entry is not
8866              used by GDB, but it comes in handy for debugging partial symbol
8867              table building.  */
8868
8869           if (pdi->d.locdesc || pdi->has_type)
8870             add_psymbol_to_list (actual_name, strlen (actual_name),
8871                                  built_actual_name != NULL,
8872                                  VAR_DOMAIN, LOC_STATIC,
8873                                  &objfile->global_psymbols,
8874                                  addr + baseaddr,
8875                                  cu->language, objfile);
8876         }
8877       else
8878         {
8879           int has_loc = pdi->d.locdesc != NULL;
8880
8881           /* Static Variable.  Skip symbols whose value we cannot know (those
8882              without location descriptors or constant values).  */
8883           if (!has_loc && !pdi->has_const_value)
8884             {
8885               xfree (built_actual_name);
8886               return;
8887             }
8888
8889           add_psymbol_to_list (actual_name, strlen (actual_name),
8890                                built_actual_name != NULL,
8891                                VAR_DOMAIN, LOC_STATIC,
8892                                &objfile->static_psymbols,
8893                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
8894                                cu->language, objfile);
8895         }
8896       break;
8897     case DW_TAG_typedef:
8898     case DW_TAG_base_type:
8899     case DW_TAG_subrange_type:
8900       add_psymbol_to_list (actual_name, strlen (actual_name),
8901                            built_actual_name != NULL,
8902                            VAR_DOMAIN, LOC_TYPEDEF,
8903                            &objfile->static_psymbols,
8904                            0, cu->language, objfile);
8905       break;
8906     case DW_TAG_imported_declaration:
8907     case DW_TAG_namespace:
8908       add_psymbol_to_list (actual_name, strlen (actual_name),
8909                            built_actual_name != NULL,
8910                            VAR_DOMAIN, LOC_TYPEDEF,
8911                            &objfile->global_psymbols,
8912                            0, cu->language, objfile);
8913       break;
8914     case DW_TAG_module:
8915       add_psymbol_to_list (actual_name, strlen (actual_name),
8916                            built_actual_name != NULL,
8917                            MODULE_DOMAIN, LOC_TYPEDEF,
8918                            &objfile->global_psymbols,
8919                            0, cu->language, objfile);
8920       break;
8921     case DW_TAG_class_type:
8922     case DW_TAG_interface_type:
8923     case DW_TAG_structure_type:
8924     case DW_TAG_union_type:
8925     case DW_TAG_enumeration_type:
8926       /* Skip external references.  The DWARF standard says in the section
8927          about "Structure, Union, and Class Type Entries": "An incomplete
8928          structure, union or class type is represented by a structure,
8929          union or class entry that does not have a byte size attribute
8930          and that has a DW_AT_declaration attribute."  */
8931       if (!pdi->has_byte_size && pdi->is_declaration)
8932         {
8933           xfree (built_actual_name);
8934           return;
8935         }
8936
8937       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8938          static vs. global.  */
8939       add_psymbol_to_list (actual_name, strlen (actual_name),
8940                            built_actual_name != NULL,
8941                            STRUCT_DOMAIN, LOC_TYPEDEF,
8942                            cu->language == language_cplus
8943                            ? &objfile->global_psymbols
8944                            : &objfile->static_psymbols,
8945                            0, cu->language, objfile);
8946
8947       break;
8948     case DW_TAG_enumerator:
8949       add_psymbol_to_list (actual_name, strlen (actual_name),
8950                            built_actual_name != NULL,
8951                            VAR_DOMAIN, LOC_CONST,
8952                            cu->language == language_cplus
8953                            ? &objfile->global_psymbols
8954                            : &objfile->static_psymbols,
8955                            0, cu->language, objfile);
8956       break;
8957     default:
8958       break;
8959     }
8960
8961   xfree (built_actual_name);
8962 }
8963
8964 /* Read a partial die corresponding to a namespace; also, add a symbol
8965    corresponding to that namespace to the symbol table.  NAMESPACE is
8966    the name of the enclosing namespace.  */
8967
8968 static void
8969 add_partial_namespace (struct partial_die_info *pdi,
8970                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8971                        int set_addrmap, struct dwarf2_cu *cu)
8972 {
8973   /* Add a symbol for the namespace.  */
8974
8975   add_partial_symbol (pdi, cu);
8976
8977   /* Now scan partial symbols in that namespace.  */
8978
8979   if (pdi->has_children)
8980     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8981 }
8982
8983 /* Read a partial die corresponding to a Fortran module.  */
8984
8985 static void
8986 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8987                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8988 {
8989   /* Add a symbol for the namespace.  */
8990
8991   add_partial_symbol (pdi, cu);
8992
8993   /* Now scan partial symbols in that module.  */
8994
8995   if (pdi->has_children)
8996     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8997 }
8998
8999 /* Read a partial die corresponding to a subprogram or an inlined
9000    subprogram and create a partial symbol for that subprogram.
9001    When the CU language allows it, this routine also defines a partial
9002    symbol for each nested subprogram that this subprogram contains.
9003    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9004    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9005
9006    PDI may also be a lexical block, in which case we simply search
9007    recursively for subprograms defined inside that lexical block.
9008    Again, this is only performed when the CU language allows this
9009    type of definitions.  */
9010
9011 static void
9012 add_partial_subprogram (struct partial_die_info *pdi,
9013                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9014                         int set_addrmap, struct dwarf2_cu *cu)
9015 {
9016   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9017     {
9018       if (pdi->has_pc_info)
9019         {
9020           if (pdi->lowpc < *lowpc)
9021             *lowpc = pdi->lowpc;
9022           if (pdi->highpc > *highpc)
9023             *highpc = pdi->highpc;
9024           if (set_addrmap)
9025             {
9026               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9027               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9028               CORE_ADDR baseaddr;
9029               CORE_ADDR highpc;
9030               CORE_ADDR lowpc;
9031
9032               baseaddr = ANOFFSET (objfile->section_offsets,
9033                                    SECT_OFF_TEXT (objfile));
9034               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9035                                                   pdi->lowpc + baseaddr);
9036               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9037                                                    pdi->highpc + baseaddr);
9038               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9039                                  cu->per_cu->v.psymtab);
9040             }
9041         }
9042
9043       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9044         {
9045           if (!pdi->is_declaration)
9046             /* Ignore subprogram DIEs that do not have a name, they are
9047                illegal.  Do not emit a complaint at this point, we will
9048                do so when we convert this psymtab into a symtab.  */
9049             if (pdi->name)
9050               add_partial_symbol (pdi, cu);
9051         }
9052     }
9053
9054   if (! pdi->has_children)
9055     return;
9056
9057   if (cu->language == language_ada)
9058     {
9059       pdi = pdi->die_child;
9060       while (pdi != NULL)
9061         {
9062           pdi->fixup (cu);
9063           if (pdi->tag == DW_TAG_subprogram
9064               || pdi->tag == DW_TAG_inlined_subroutine
9065               || pdi->tag == DW_TAG_lexical_block)
9066             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9067           pdi = pdi->die_sibling;
9068         }
9069     }
9070 }
9071
9072 /* Read a partial die corresponding to an enumeration type.  */
9073
9074 static void
9075 add_partial_enumeration (struct partial_die_info *enum_pdi,
9076                          struct dwarf2_cu *cu)
9077 {
9078   struct partial_die_info *pdi;
9079
9080   if (enum_pdi->name != NULL)
9081     add_partial_symbol (enum_pdi, cu);
9082
9083   pdi = enum_pdi->die_child;
9084   while (pdi)
9085     {
9086       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9087         complaint (_("malformed enumerator DIE ignored"));
9088       else
9089         add_partial_symbol (pdi, cu);
9090       pdi = pdi->die_sibling;
9091     }
9092 }
9093
9094 /* Return the initial uleb128 in the die at INFO_PTR.  */
9095
9096 static unsigned int
9097 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9098 {
9099   unsigned int bytes_read;
9100
9101   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9102 }
9103
9104 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9105    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9106
9107    Return the corresponding abbrev, or NULL if the number is zero (indicating
9108    an empty DIE).  In either case *BYTES_READ will be set to the length of
9109    the initial number.  */
9110
9111 static struct abbrev_info *
9112 peek_die_abbrev (const die_reader_specs &reader,
9113                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9114 {
9115   dwarf2_cu *cu = reader.cu;
9116   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9117   unsigned int abbrev_number
9118     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9119
9120   if (abbrev_number == 0)
9121     return NULL;
9122
9123   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9124   if (!abbrev)
9125     {
9126       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9127                " at offset %s [in module %s]"),
9128              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9129              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9130     }
9131
9132   return abbrev;
9133 }
9134
9135 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9136    Returns a pointer to the end of a series of DIEs, terminated by an empty
9137    DIE.  Any children of the skipped DIEs will also be skipped.  */
9138
9139 static const gdb_byte *
9140 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9141 {
9142   while (1)
9143     {
9144       unsigned int bytes_read;
9145       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9146
9147       if (abbrev == NULL)
9148         return info_ptr + bytes_read;
9149       else
9150         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9151     }
9152 }
9153
9154 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9155    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9156    abbrev corresponding to that skipped uleb128 should be passed in
9157    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9158    children.  */
9159
9160 static const gdb_byte *
9161 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9162               struct abbrev_info *abbrev)
9163 {
9164   unsigned int bytes_read;
9165   struct attribute attr;
9166   bfd *abfd = reader->abfd;
9167   struct dwarf2_cu *cu = reader->cu;
9168   const gdb_byte *buffer = reader->buffer;
9169   const gdb_byte *buffer_end = reader->buffer_end;
9170   unsigned int form, i;
9171
9172   for (i = 0; i < abbrev->num_attrs; i++)
9173     {
9174       /* The only abbrev we care about is DW_AT_sibling.  */
9175       if (abbrev->attrs[i].name == DW_AT_sibling)
9176         {
9177           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9178           if (attr.form == DW_FORM_ref_addr)
9179             complaint (_("ignoring absolute DW_AT_sibling"));
9180           else
9181             {
9182               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9183               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9184
9185               if (sibling_ptr < info_ptr)
9186                 complaint (_("DW_AT_sibling points backwards"));
9187               else if (sibling_ptr > reader->buffer_end)
9188                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9189               else
9190                 return sibling_ptr;
9191             }
9192         }
9193
9194       /* If it isn't DW_AT_sibling, skip this attribute.  */
9195       form = abbrev->attrs[i].form;
9196     skip_attribute:
9197       switch (form)
9198         {
9199         case DW_FORM_ref_addr:
9200           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9201              and later it is offset sized.  */
9202           if (cu->header.version == 2)
9203             info_ptr += cu->header.addr_size;
9204           else
9205             info_ptr += cu->header.offset_size;
9206           break;
9207         case DW_FORM_GNU_ref_alt:
9208           info_ptr += cu->header.offset_size;
9209           break;
9210         case DW_FORM_addr:
9211           info_ptr += cu->header.addr_size;
9212           break;
9213         case DW_FORM_data1:
9214         case DW_FORM_ref1:
9215         case DW_FORM_flag:
9216           info_ptr += 1;
9217           break;
9218         case DW_FORM_flag_present:
9219         case DW_FORM_implicit_const:
9220           break;
9221         case DW_FORM_data2:
9222         case DW_FORM_ref2:
9223           info_ptr += 2;
9224           break;
9225         case DW_FORM_data4:
9226         case DW_FORM_ref4:
9227           info_ptr += 4;
9228           break;
9229         case DW_FORM_data8:
9230         case DW_FORM_ref8:
9231         case DW_FORM_ref_sig8:
9232           info_ptr += 8;
9233           break;
9234         case DW_FORM_data16:
9235           info_ptr += 16;
9236           break;
9237         case DW_FORM_string:
9238           read_direct_string (abfd, info_ptr, &bytes_read);
9239           info_ptr += bytes_read;
9240           break;
9241         case DW_FORM_sec_offset:
9242         case DW_FORM_strp:
9243         case DW_FORM_GNU_strp_alt:
9244           info_ptr += cu->header.offset_size;
9245           break;
9246         case DW_FORM_exprloc:
9247         case DW_FORM_block:
9248           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9249           info_ptr += bytes_read;
9250           break;
9251         case DW_FORM_block1:
9252           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9253           break;
9254         case DW_FORM_block2:
9255           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9256           break;
9257         case DW_FORM_block4:
9258           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9259           break;
9260         case DW_FORM_sdata:
9261         case DW_FORM_udata:
9262         case DW_FORM_ref_udata:
9263         case DW_FORM_GNU_addr_index:
9264         case DW_FORM_GNU_str_index:
9265           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9266           break;
9267         case DW_FORM_indirect:
9268           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9269           info_ptr += bytes_read;
9270           /* We need to continue parsing from here, so just go back to
9271              the top.  */
9272           goto skip_attribute;
9273
9274         default:
9275           error (_("Dwarf Error: Cannot handle %s "
9276                    "in DWARF reader [in module %s]"),
9277                  dwarf_form_name (form),
9278                  bfd_get_filename (abfd));
9279         }
9280     }
9281
9282   if (abbrev->has_children)
9283     return skip_children (reader, info_ptr);
9284   else
9285     return info_ptr;
9286 }
9287
9288 /* Locate ORIG_PDI's sibling.
9289    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9290
9291 static const gdb_byte *
9292 locate_pdi_sibling (const struct die_reader_specs *reader,
9293                     struct partial_die_info *orig_pdi,
9294                     const gdb_byte *info_ptr)
9295 {
9296   /* Do we know the sibling already?  */
9297
9298   if (orig_pdi->sibling)
9299     return orig_pdi->sibling;
9300
9301   /* Are there any children to deal with?  */
9302
9303   if (!orig_pdi->has_children)
9304     return info_ptr;
9305
9306   /* Skip the children the long way.  */
9307
9308   return skip_children (reader, info_ptr);
9309 }
9310
9311 /* Expand this partial symbol table into a full symbol table.  SELF is
9312    not NULL.  */
9313
9314 static void
9315 dwarf2_read_symtab (struct partial_symtab *self,
9316                     struct objfile *objfile)
9317 {
9318   struct dwarf2_per_objfile *dwarf2_per_objfile
9319     = get_dwarf2_per_objfile (objfile);
9320
9321   if (self->readin)
9322     {
9323       warning (_("bug: psymtab for %s is already read in."),
9324                self->filename);
9325     }
9326   else
9327     {
9328       if (info_verbose)
9329         {
9330           printf_filtered (_("Reading in symbols for %s..."),
9331                            self->filename);
9332           gdb_flush (gdb_stdout);
9333         }
9334
9335       /* If this psymtab is constructed from a debug-only objfile, the
9336          has_section_at_zero flag will not necessarily be correct.  We
9337          can get the correct value for this flag by looking at the data
9338          associated with the (presumably stripped) associated objfile.  */
9339       if (objfile->separate_debug_objfile_backlink)
9340         {
9341           struct dwarf2_per_objfile *dpo_backlink
9342             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9343
9344           dwarf2_per_objfile->has_section_at_zero
9345             = dpo_backlink->has_section_at_zero;
9346         }
9347
9348       dwarf2_per_objfile->reading_partial_symbols = 0;
9349
9350       psymtab_to_symtab_1 (self);
9351
9352       /* Finish up the debug error message.  */
9353       if (info_verbose)
9354         printf_filtered (_("done.\n"));
9355     }
9356
9357   process_cu_includes (dwarf2_per_objfile);
9358 }
9359 \f
9360 /* Reading in full CUs.  */
9361
9362 /* Add PER_CU to the queue.  */
9363
9364 static void
9365 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9366                  enum language pretend_language)
9367 {
9368   struct dwarf2_queue_item *item;
9369
9370   per_cu->queued = 1;
9371   item = XNEW (struct dwarf2_queue_item);
9372   item->per_cu = per_cu;
9373   item->pretend_language = pretend_language;
9374   item->next = NULL;
9375
9376   if (dwarf2_queue == NULL)
9377     dwarf2_queue = item;
9378   else
9379     dwarf2_queue_tail->next = item;
9380
9381   dwarf2_queue_tail = item;
9382 }
9383
9384 /* If PER_CU is not yet queued, add it to the queue.
9385    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9386    dependency.
9387    The result is non-zero if PER_CU was queued, otherwise the result is zero
9388    meaning either PER_CU is already queued or it is already loaded.
9389
9390    N.B. There is an invariant here that if a CU is queued then it is loaded.
9391    The caller is required to load PER_CU if we return non-zero.  */
9392
9393 static int
9394 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9395                        struct dwarf2_per_cu_data *per_cu,
9396                        enum language pretend_language)
9397 {
9398   /* We may arrive here during partial symbol reading, if we need full
9399      DIEs to process an unusual case (e.g. template arguments).  Do
9400      not queue PER_CU, just tell our caller to load its DIEs.  */
9401   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9402     {
9403       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9404         return 1;
9405       return 0;
9406     }
9407
9408   /* Mark the dependence relation so that we don't flush PER_CU
9409      too early.  */
9410   if (dependent_cu != NULL)
9411     dwarf2_add_dependence (dependent_cu, per_cu);
9412
9413   /* If it's already on the queue, we have nothing to do.  */
9414   if (per_cu->queued)
9415     return 0;
9416
9417   /* If the compilation unit is already loaded, just mark it as
9418      used.  */
9419   if (per_cu->cu != NULL)
9420     {
9421       per_cu->cu->last_used = 0;
9422       return 0;
9423     }
9424
9425   /* Add it to the queue.  */
9426   queue_comp_unit (per_cu, pretend_language);
9427
9428   return 1;
9429 }
9430
9431 /* Process the queue.  */
9432
9433 static void
9434 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9435 {
9436   struct dwarf2_queue_item *item, *next_item;
9437
9438   if (dwarf_read_debug)
9439     {
9440       fprintf_unfiltered (gdb_stdlog,
9441                           "Expanding one or more symtabs of objfile %s ...\n",
9442                           objfile_name (dwarf2_per_objfile->objfile));
9443     }
9444
9445   /* The queue starts out with one item, but following a DIE reference
9446      may load a new CU, adding it to the end of the queue.  */
9447   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9448     {
9449       if ((dwarf2_per_objfile->using_index
9450            ? !item->per_cu->v.quick->compunit_symtab
9451            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9452           /* Skip dummy CUs.  */
9453           && item->per_cu->cu != NULL)
9454         {
9455           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9456           unsigned int debug_print_threshold;
9457           char buf[100];
9458
9459           if (per_cu->is_debug_types)
9460             {
9461               struct signatured_type *sig_type =
9462                 (struct signatured_type *) per_cu;
9463
9464               sprintf (buf, "TU %s at offset %s",
9465                        hex_string (sig_type->signature),
9466                        sect_offset_str (per_cu->sect_off));
9467               /* There can be 100s of TUs.
9468                  Only print them in verbose mode.  */
9469               debug_print_threshold = 2;
9470             }
9471           else
9472             {
9473               sprintf (buf, "CU at offset %s",
9474                        sect_offset_str (per_cu->sect_off));
9475               debug_print_threshold = 1;
9476             }
9477
9478           if (dwarf_read_debug >= debug_print_threshold)
9479             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9480
9481           if (per_cu->is_debug_types)
9482             process_full_type_unit (per_cu, item->pretend_language);
9483           else
9484             process_full_comp_unit (per_cu, item->pretend_language);
9485
9486           if (dwarf_read_debug >= debug_print_threshold)
9487             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9488         }
9489
9490       item->per_cu->queued = 0;
9491       next_item = item->next;
9492       xfree (item);
9493     }
9494
9495   dwarf2_queue_tail = NULL;
9496
9497   if (dwarf_read_debug)
9498     {
9499       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9500                           objfile_name (dwarf2_per_objfile->objfile));
9501     }
9502 }
9503
9504 /* Read in full symbols for PST, and anything it depends on.  */
9505
9506 static void
9507 psymtab_to_symtab_1 (struct partial_symtab *pst)
9508 {
9509   struct dwarf2_per_cu_data *per_cu;
9510   int i;
9511
9512   if (pst->readin)
9513     return;
9514
9515   for (i = 0; i < pst->number_of_dependencies; i++)
9516     if (!pst->dependencies[i]->readin
9517         && pst->dependencies[i]->user == NULL)
9518       {
9519         /* Inform about additional files that need to be read in.  */
9520         if (info_verbose)
9521           {
9522             /* FIXME: i18n: Need to make this a single string.  */
9523             fputs_filtered (" ", gdb_stdout);
9524             wrap_here ("");
9525             fputs_filtered ("and ", gdb_stdout);
9526             wrap_here ("");
9527             printf_filtered ("%s...", pst->dependencies[i]->filename);
9528             wrap_here ("");     /* Flush output.  */
9529             gdb_flush (gdb_stdout);
9530           }
9531         psymtab_to_symtab_1 (pst->dependencies[i]);
9532       }
9533
9534   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9535
9536   if (per_cu == NULL)
9537     {
9538       /* It's an include file, no symbols to read for it.
9539          Everything is in the parent symtab.  */
9540       pst->readin = 1;
9541       return;
9542     }
9543
9544   dw2_do_instantiate_symtab (per_cu, false);
9545 }
9546
9547 /* Trivial hash function for die_info: the hash value of a DIE
9548    is its offset in .debug_info for this objfile.  */
9549
9550 static hashval_t
9551 die_hash (const void *item)
9552 {
9553   const struct die_info *die = (const struct die_info *) item;
9554
9555   return to_underlying (die->sect_off);
9556 }
9557
9558 /* Trivial comparison function for die_info structures: two DIEs
9559    are equal if they have the same offset.  */
9560
9561 static int
9562 die_eq (const void *item_lhs, const void *item_rhs)
9563 {
9564   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9565   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9566
9567   return die_lhs->sect_off == die_rhs->sect_off;
9568 }
9569
9570 /* die_reader_func for load_full_comp_unit.
9571    This is identical to read_signatured_type_reader,
9572    but is kept separate for now.  */
9573
9574 static void
9575 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9576                             const gdb_byte *info_ptr,
9577                             struct die_info *comp_unit_die,
9578                             int has_children,
9579                             void *data)
9580 {
9581   struct dwarf2_cu *cu = reader->cu;
9582   enum language *language_ptr = (enum language *) data;
9583
9584   gdb_assert (cu->die_hash == NULL);
9585   cu->die_hash =
9586     htab_create_alloc_ex (cu->header.length / 12,
9587                           die_hash,
9588                           die_eq,
9589                           NULL,
9590                           &cu->comp_unit_obstack,
9591                           hashtab_obstack_allocate,
9592                           dummy_obstack_deallocate);
9593
9594   if (has_children)
9595     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9596                                                   &info_ptr, comp_unit_die);
9597   cu->dies = comp_unit_die;
9598   /* comp_unit_die is not stored in die_hash, no need.  */
9599
9600   /* We try not to read any attributes in this function, because not
9601      all CUs needed for references have been loaded yet, and symbol
9602      table processing isn't initialized.  But we have to set the CU language,
9603      or we won't be able to build types correctly.
9604      Similarly, if we do not read the producer, we can not apply
9605      producer-specific interpretation.  */
9606   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9607 }
9608
9609 /* Load the DIEs associated with PER_CU into memory.  */
9610
9611 static void
9612 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9613                      bool skip_partial,
9614                      enum language pretend_language)
9615 {
9616   gdb_assert (! this_cu->is_debug_types);
9617
9618   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9619                            load_full_comp_unit_reader, &pretend_language);
9620 }
9621
9622 /* Add a DIE to the delayed physname list.  */
9623
9624 static void
9625 add_to_method_list (struct type *type, int fnfield_index, int index,
9626                     const char *name, struct die_info *die,
9627                     struct dwarf2_cu *cu)
9628 {
9629   struct delayed_method_info mi;
9630   mi.type = type;
9631   mi.fnfield_index = fnfield_index;
9632   mi.index = index;
9633   mi.name = name;
9634   mi.die = die;
9635   cu->method_list.push_back (mi);
9636 }
9637
9638 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9639    "const" / "volatile".  If so, decrements LEN by the length of the
9640    modifier and return true.  Otherwise return false.  */
9641
9642 template<size_t N>
9643 static bool
9644 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9645 {
9646   size_t mod_len = sizeof (mod) - 1;
9647   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9648     {
9649       len -= mod_len;
9650       return true;
9651     }
9652   return false;
9653 }
9654
9655 /* Compute the physnames of any methods on the CU's method list.
9656
9657    The computation of method physnames is delayed in order to avoid the
9658    (bad) condition that one of the method's formal parameters is of an as yet
9659    incomplete type.  */
9660
9661 static void
9662 compute_delayed_physnames (struct dwarf2_cu *cu)
9663 {
9664   /* Only C++ delays computing physnames.  */
9665   if (cu->method_list.empty ())
9666     return;
9667   gdb_assert (cu->language == language_cplus);
9668
9669   for (const delayed_method_info &mi : cu->method_list)
9670     {
9671       const char *physname;
9672       struct fn_fieldlist *fn_flp
9673         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9674       physname = dwarf2_physname (mi.name, mi.die, cu);
9675       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9676         = physname ? physname : "";
9677
9678       /* Since there's no tag to indicate whether a method is a
9679          const/volatile overload, extract that information out of the
9680          demangled name.  */
9681       if (physname != NULL)
9682         {
9683           size_t len = strlen (physname);
9684
9685           while (1)
9686             {
9687               if (physname[len] == ')') /* shortcut */
9688                 break;
9689               else if (check_modifier (physname, len, " const"))
9690                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9691               else if (check_modifier (physname, len, " volatile"))
9692                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9693               else
9694                 break;
9695             }
9696         }
9697     }
9698
9699   /* The list is no longer needed.  */
9700   cu->method_list.clear ();
9701 }
9702
9703 /* Go objects should be embedded in a DW_TAG_module DIE,
9704    and it's not clear if/how imported objects will appear.
9705    To keep Go support simple until that's worked out,
9706    go back through what we've read and create something usable.
9707    We could do this while processing each DIE, and feels kinda cleaner,
9708    but that way is more invasive.
9709    This is to, for example, allow the user to type "p var" or "b main"
9710    without having to specify the package name, and allow lookups
9711    of module.object to work in contexts that use the expression
9712    parser.  */
9713
9714 static void
9715 fixup_go_packaging (struct dwarf2_cu *cu)
9716 {
9717   char *package_name = NULL;
9718   struct pending *list;
9719   int i;
9720
9721   for (list = global_symbols; list != NULL; list = list->next)
9722     {
9723       for (i = 0; i < list->nsyms; ++i)
9724         {
9725           struct symbol *sym = list->symbol[i];
9726
9727           if (SYMBOL_LANGUAGE (sym) == language_go
9728               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9729             {
9730               char *this_package_name = go_symbol_package_name (sym);
9731
9732               if (this_package_name == NULL)
9733                 continue;
9734               if (package_name == NULL)
9735                 package_name = this_package_name;
9736               else
9737                 {
9738                   struct objfile *objfile
9739                     = cu->per_cu->dwarf2_per_objfile->objfile;
9740                   if (strcmp (package_name, this_package_name) != 0)
9741                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9742                                (symbol_symtab (sym) != NULL
9743                                 ? symtab_to_filename_for_display
9744                                     (symbol_symtab (sym))
9745                                 : objfile_name (objfile)),
9746                                this_package_name, package_name);
9747                   xfree (this_package_name);
9748                 }
9749             }
9750         }
9751     }
9752
9753   if (package_name != NULL)
9754     {
9755       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9756       const char *saved_package_name
9757         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9758                                         package_name,
9759                                         strlen (package_name));
9760       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9761                                      saved_package_name);
9762       struct symbol *sym;
9763
9764       sym = allocate_symbol (objfile);
9765       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9766       SYMBOL_SET_NAMES (sym, saved_package_name,
9767                         strlen (saved_package_name), 0, objfile);
9768       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9769          e.g., "main" finds the "main" module and not C's main().  */
9770       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9771       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9772       SYMBOL_TYPE (sym) = type;
9773
9774       add_symbol_to_list (sym, &global_symbols);
9775
9776       xfree (package_name);
9777     }
9778 }
9779
9780 /* Allocate a fully-qualified name consisting of the two parts on the
9781    obstack.  */
9782
9783 static const char *
9784 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9785 {
9786   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9787 }
9788
9789 /* A helper that allocates a struct discriminant_info to attach to a
9790    union type.  */
9791
9792 static struct discriminant_info *
9793 alloc_discriminant_info (struct type *type, int discriminant_index,
9794                          int default_index)
9795 {
9796   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9797   gdb_assert (discriminant_index == -1
9798               || (discriminant_index >= 0
9799                   && discriminant_index < TYPE_NFIELDS (type)));
9800   gdb_assert (default_index == -1
9801               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9802
9803   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9804
9805   struct discriminant_info *disc
9806     = ((struct discriminant_info *)
9807        TYPE_ZALLOC (type,
9808                     offsetof (struct discriminant_info, discriminants)
9809                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9810   disc->default_index = default_index;
9811   disc->discriminant_index = discriminant_index;
9812
9813   struct dynamic_prop prop;
9814   prop.kind = PROP_UNDEFINED;
9815   prop.data.baton = disc;
9816
9817   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9818
9819   return disc;
9820 }
9821
9822 /* Some versions of rustc emitted enums in an unusual way.
9823
9824    Ordinary enums were emitted as unions.  The first element of each
9825    structure in the union was named "RUST$ENUM$DISR".  This element
9826    held the discriminant.
9827
9828    These versions of Rust also implemented the "non-zero"
9829    optimization.  When the enum had two values, and one is empty and
9830    the other holds a pointer that cannot be zero, the pointer is used
9831    as the discriminant, with a zero value meaning the empty variant.
9832    Here, the union's first member is of the form
9833    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9834    where the fieldnos are the indices of the fields that should be
9835    traversed in order to find the field (which may be several fields deep)
9836    and the variantname is the name of the variant of the case when the
9837    field is zero.
9838
9839    This function recognizes whether TYPE is of one of these forms,
9840    and, if so, smashes it to be a variant type.  */
9841
9842 static void
9843 quirk_rust_enum (struct type *type, struct objfile *objfile)
9844 {
9845   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9846
9847   /* We don't need to deal with empty enums.  */
9848   if (TYPE_NFIELDS (type) == 0)
9849     return;
9850
9851 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9852   if (TYPE_NFIELDS (type) == 1
9853       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9854     {
9855       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9856
9857       /* Decode the field name to find the offset of the
9858          discriminant.  */
9859       ULONGEST bit_offset = 0;
9860       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9861       while (name[0] >= '0' && name[0] <= '9')
9862         {
9863           char *tail;
9864           unsigned long index = strtoul (name, &tail, 10);
9865           name = tail;
9866           if (*name != '$'
9867               || index >= TYPE_NFIELDS (field_type)
9868               || (TYPE_FIELD_LOC_KIND (field_type, index)
9869                   != FIELD_LOC_KIND_BITPOS))
9870             {
9871               complaint (_("Could not parse Rust enum encoding string \"%s\""
9872                            "[in module %s]"),
9873                          TYPE_FIELD_NAME (type, 0),
9874                          objfile_name (objfile));
9875               return;
9876             }
9877           ++name;
9878
9879           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9880           field_type = TYPE_FIELD_TYPE (field_type, index);
9881         }
9882
9883       /* Make a union to hold the variants.  */
9884       struct type *union_type = alloc_type (objfile);
9885       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9886       TYPE_NFIELDS (union_type) = 3;
9887       TYPE_FIELDS (union_type)
9888         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9889       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9890       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9891
9892       /* Put the discriminant must at index 0.  */
9893       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9894       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9895       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9896       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9897
9898       /* The order of fields doesn't really matter, so put the real
9899          field at index 1 and the data-less field at index 2.  */
9900       struct discriminant_info *disc
9901         = alloc_discriminant_info (union_type, 0, 1);
9902       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9903       TYPE_FIELD_NAME (union_type, 1)
9904         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9905       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9906         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9907                               TYPE_FIELD_NAME (union_type, 1));
9908
9909       const char *dataless_name
9910         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9911                               name);
9912       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9913                                               dataless_name);
9914       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9915       /* NAME points into the original discriminant name, which
9916          already has the correct lifetime.  */
9917       TYPE_FIELD_NAME (union_type, 2) = name;
9918       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9919       disc->discriminants[2] = 0;
9920
9921       /* Smash this type to be a structure type.  We have to do this
9922          because the type has already been recorded.  */
9923       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9924       TYPE_NFIELDS (type) = 1;
9925       TYPE_FIELDS (type)
9926         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9927
9928       /* Install the variant part.  */
9929       TYPE_FIELD_TYPE (type, 0) = union_type;
9930       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9931       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9932     }
9933   else if (TYPE_NFIELDS (type) == 1)
9934     {
9935       /* We assume that a union with a single field is a univariant
9936          enum.  */
9937       /* Smash this type to be a structure type.  We have to do this
9938          because the type has already been recorded.  */
9939       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9940
9941       /* Make a union to hold the variants.  */
9942       struct type *union_type = alloc_type (objfile);
9943       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9944       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
9945       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9946       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9947       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
9948
9949       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
9950       const char *variant_name
9951         = rust_last_path_segment (TYPE_NAME (field_type));
9952       TYPE_FIELD_NAME (union_type, 0) = variant_name;
9953       TYPE_NAME (field_type)
9954         = rust_fully_qualify (&objfile->objfile_obstack,
9955                               TYPE_NAME (type), variant_name);
9956
9957       /* Install the union in the outer struct type.  */
9958       TYPE_NFIELDS (type) = 1;
9959       TYPE_FIELDS (type)
9960         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
9961       TYPE_FIELD_TYPE (type, 0) = union_type;
9962       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9963       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9964
9965       alloc_discriminant_info (union_type, -1, 0);
9966     }
9967   else
9968     {
9969       struct type *disr_type = nullptr;
9970       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
9971         {
9972           disr_type = TYPE_FIELD_TYPE (type, i);
9973
9974           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
9975             {
9976               /* All fields of a true enum will be structs.  */
9977               return;
9978             }
9979           else if (TYPE_NFIELDS (disr_type) == 0)
9980             {
9981               /* Could be data-less variant, so keep going.  */
9982               disr_type = nullptr;
9983             }
9984           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
9985                            "RUST$ENUM$DISR") != 0)
9986             {
9987               /* Not a Rust enum.  */
9988               return;
9989             }
9990           else
9991             {
9992               /* Found one.  */
9993               break;
9994             }
9995         }
9996
9997       /* If we got here without a discriminant, then it's probably
9998          just a union.  */
9999       if (disr_type == nullptr)
10000         return;
10001
10002       /* Smash this type to be a structure type.  We have to do this
10003          because the type has already been recorded.  */
10004       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10005
10006       /* Make a union to hold the variants.  */
10007       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10008       struct type *union_type = alloc_type (objfile);
10009       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10010       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10011       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10012       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10013       TYPE_FIELDS (union_type)
10014         = (struct field *) TYPE_ZALLOC (union_type,
10015                                         (TYPE_NFIELDS (union_type)
10016                                          * sizeof (struct field)));
10017
10018       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10019               TYPE_NFIELDS (type) * sizeof (struct field));
10020
10021       /* Install the discriminant at index 0 in the union.  */
10022       TYPE_FIELD (union_type, 0) = *disr_field;
10023       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10024       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10025
10026       /* Install the union in the outer struct type.  */
10027       TYPE_FIELD_TYPE (type, 0) = union_type;
10028       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10029       TYPE_NFIELDS (type) = 1;
10030
10031       /* Set the size and offset of the union type.  */
10032       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10033
10034       /* We need a way to find the correct discriminant given a
10035          variant name.  For convenience we build a map here.  */
10036       struct type *enum_type = FIELD_TYPE (*disr_field);
10037       std::unordered_map<std::string, ULONGEST> discriminant_map;
10038       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10039         {
10040           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10041             {
10042               const char *name
10043                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10044               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10045             }
10046         }
10047
10048       int n_fields = TYPE_NFIELDS (union_type);
10049       struct discriminant_info *disc
10050         = alloc_discriminant_info (union_type, 0, -1);
10051       /* Skip the discriminant here.  */
10052       for (int i = 1; i < n_fields; ++i)
10053         {
10054           /* Find the final word in the name of this variant's type.
10055              That name can be used to look up the correct
10056              discriminant.  */
10057           const char *variant_name
10058             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10059                                                                   i)));
10060
10061           auto iter = discriminant_map.find (variant_name);
10062           if (iter != discriminant_map.end ())
10063             disc->discriminants[i] = iter->second;
10064
10065           /* Remove the discriminant field, if it exists.  */
10066           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10067           if (TYPE_NFIELDS (sub_type) > 0)
10068             {
10069               --TYPE_NFIELDS (sub_type);
10070               ++TYPE_FIELDS (sub_type);
10071             }
10072           TYPE_FIELD_NAME (union_type, i) = variant_name;
10073           TYPE_NAME (sub_type)
10074             = rust_fully_qualify (&objfile->objfile_obstack,
10075                                   TYPE_NAME (type), variant_name);
10076         }
10077     }
10078 }
10079
10080 /* Rewrite some Rust unions to be structures with variants parts.  */
10081
10082 static void
10083 rust_union_quirks (struct dwarf2_cu *cu)
10084 {
10085   gdb_assert (cu->language == language_rust);
10086   for (type *type_ : cu->rust_unions)
10087     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10088   /* We don't need this any more.  */
10089   cu->rust_unions.clear ();
10090 }
10091
10092 /* Return the symtab for PER_CU.  This works properly regardless of
10093    whether we're using the index or psymtabs.  */
10094
10095 static struct compunit_symtab *
10096 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10097 {
10098   return (per_cu->dwarf2_per_objfile->using_index
10099           ? per_cu->v.quick->compunit_symtab
10100           : per_cu->v.psymtab->compunit_symtab);
10101 }
10102
10103 /* A helper function for computing the list of all symbol tables
10104    included by PER_CU.  */
10105
10106 static void
10107 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10108                                 htab_t all_children, htab_t all_type_symtabs,
10109                                 struct dwarf2_per_cu_data *per_cu,
10110                                 struct compunit_symtab *immediate_parent)
10111 {
10112   void **slot;
10113   int ix;
10114   struct compunit_symtab *cust;
10115   struct dwarf2_per_cu_data *iter;
10116
10117   slot = htab_find_slot (all_children, per_cu, INSERT);
10118   if (*slot != NULL)
10119     {
10120       /* This inclusion and its children have been processed.  */
10121       return;
10122     }
10123
10124   *slot = per_cu;
10125   /* Only add a CU if it has a symbol table.  */
10126   cust = get_compunit_symtab (per_cu);
10127   if (cust != NULL)
10128     {
10129       /* If this is a type unit only add its symbol table if we haven't
10130          seen it yet (type unit per_cu's can share symtabs).  */
10131       if (per_cu->is_debug_types)
10132         {
10133           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10134           if (*slot == NULL)
10135             {
10136               *slot = cust;
10137               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10138               if (cust->user == NULL)
10139                 cust->user = immediate_parent;
10140             }
10141         }
10142       else
10143         {
10144           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10145           if (cust->user == NULL)
10146             cust->user = immediate_parent;
10147         }
10148     }
10149
10150   for (ix = 0;
10151        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10152        ++ix)
10153     {
10154       recursively_compute_inclusions (result, all_children,
10155                                       all_type_symtabs, iter, cust);
10156     }
10157 }
10158
10159 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10160    PER_CU.  */
10161
10162 static void
10163 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10164 {
10165   gdb_assert (! per_cu->is_debug_types);
10166
10167   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10168     {
10169       int ix, len;
10170       struct dwarf2_per_cu_data *per_cu_iter;
10171       struct compunit_symtab *compunit_symtab_iter;
10172       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10173       htab_t all_children, all_type_symtabs;
10174       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10175
10176       /* If we don't have a symtab, we can just skip this case.  */
10177       if (cust == NULL)
10178         return;
10179
10180       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10181                                         NULL, xcalloc, xfree);
10182       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10183                                             NULL, xcalloc, xfree);
10184
10185       for (ix = 0;
10186            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10187                         ix, per_cu_iter);
10188            ++ix)
10189         {
10190           recursively_compute_inclusions (&result_symtabs, all_children,
10191                                           all_type_symtabs, per_cu_iter,
10192                                           cust);
10193         }
10194
10195       /* Now we have a transitive closure of all the included symtabs.  */
10196       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10197       cust->includes
10198         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10199                      struct compunit_symtab *, len + 1);
10200       for (ix = 0;
10201            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10202                         compunit_symtab_iter);
10203            ++ix)
10204         cust->includes[ix] = compunit_symtab_iter;
10205       cust->includes[len] = NULL;
10206
10207       VEC_free (compunit_symtab_ptr, result_symtabs);
10208       htab_delete (all_children);
10209       htab_delete (all_type_symtabs);
10210     }
10211 }
10212
10213 /* Compute the 'includes' field for the symtabs of all the CUs we just
10214    read.  */
10215
10216 static void
10217 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10218 {
10219   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10220     {
10221       if (! iter->is_debug_types)
10222         compute_compunit_symtab_includes (iter);
10223     }
10224
10225   dwarf2_per_objfile->just_read_cus.clear ();
10226 }
10227
10228 /* Generate full symbol information for PER_CU, whose DIEs have
10229    already been loaded into memory.  */
10230
10231 static void
10232 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10233                         enum language pretend_language)
10234 {
10235   struct dwarf2_cu *cu = per_cu->cu;
10236   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10237   struct objfile *objfile = dwarf2_per_objfile->objfile;
10238   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10239   CORE_ADDR lowpc, highpc;
10240   struct compunit_symtab *cust;
10241   CORE_ADDR baseaddr;
10242   struct block *static_block;
10243   CORE_ADDR addr;
10244
10245   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10246
10247   buildsym_init ();
10248   scoped_free_pendings free_pending;
10249
10250   /* Clear the list here in case something was left over.  */
10251   cu->method_list.clear ();
10252
10253   cu->list_in_scope = &file_symbols;
10254
10255   cu->language = pretend_language;
10256   cu->language_defn = language_def (cu->language);
10257
10258   /* Do line number decoding in read_file_scope () */
10259   process_die (cu->dies, cu);
10260
10261   /* For now fudge the Go package.  */
10262   if (cu->language == language_go)
10263     fixup_go_packaging (cu);
10264
10265   /* Now that we have processed all the DIEs in the CU, all the types 
10266      should be complete, and it should now be safe to compute all of the
10267      physnames.  */
10268   compute_delayed_physnames (cu);
10269
10270   if (cu->language == language_rust)
10271     rust_union_quirks (cu);
10272
10273   /* Some compilers don't define a DW_AT_high_pc attribute for the
10274      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10275      it, by scanning the DIE's below the compilation unit.  */
10276   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10277
10278   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10279   static_block = end_symtab_get_static_block (addr, 0, 1);
10280
10281   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10282      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10283      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10284      addrmap to help ensure it has an accurate map of pc values belonging to
10285      this comp unit.  */
10286   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10287
10288   cust = end_symtab_from_static_block (static_block,
10289                                        SECT_OFF_TEXT (objfile), 0);
10290
10291   if (cust != NULL)
10292     {
10293       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10294
10295       /* Set symtab language to language from DW_AT_language.  If the
10296          compilation is from a C file generated by language preprocessors, do
10297          not set the language if it was already deduced by start_subfile.  */
10298       if (!(cu->language == language_c
10299             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10300         COMPUNIT_FILETABS (cust)->language = cu->language;
10301
10302       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10303          produce DW_AT_location with location lists but it can be possibly
10304          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10305          there were bugs in prologue debug info, fixed later in GCC-4.5
10306          by "unwind info for epilogues" patch (which is not directly related).
10307
10308          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10309          needed, it would be wrong due to missing DW_AT_producer there.
10310
10311          Still one can confuse GDB by using non-standard GCC compilation
10312          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10313          */ 
10314       if (cu->has_loclist && gcc_4_minor >= 5)
10315         cust->locations_valid = 1;
10316
10317       if (gcc_4_minor >= 5)
10318         cust->epilogue_unwind_valid = 1;
10319
10320       cust->call_site_htab = cu->call_site_htab;
10321     }
10322
10323   if (dwarf2_per_objfile->using_index)
10324     per_cu->v.quick->compunit_symtab = cust;
10325   else
10326     {
10327       struct partial_symtab *pst = per_cu->v.psymtab;
10328       pst->compunit_symtab = cust;
10329       pst->readin = 1;
10330     }
10331
10332   /* Push it for inclusion processing later.  */
10333   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10334 }
10335
10336 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10337    already been loaded into memory.  */
10338
10339 static void
10340 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10341                         enum language pretend_language)
10342 {
10343   struct dwarf2_cu *cu = per_cu->cu;
10344   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10345   struct objfile *objfile = dwarf2_per_objfile->objfile;
10346   struct compunit_symtab *cust;
10347   struct signatured_type *sig_type;
10348
10349   gdb_assert (per_cu->is_debug_types);
10350   sig_type = (struct signatured_type *) per_cu;
10351
10352   buildsym_init ();
10353   scoped_free_pendings free_pending;
10354
10355   /* Clear the list here in case something was left over.  */
10356   cu->method_list.clear ();
10357
10358   cu->list_in_scope = &file_symbols;
10359
10360   cu->language = pretend_language;
10361   cu->language_defn = language_def (cu->language);
10362
10363   /* The symbol tables are set up in read_type_unit_scope.  */
10364   process_die (cu->dies, cu);
10365
10366   /* For now fudge the Go package.  */
10367   if (cu->language == language_go)
10368     fixup_go_packaging (cu);
10369
10370   /* Now that we have processed all the DIEs in the CU, all the types 
10371      should be complete, and it should now be safe to compute all of the
10372      physnames.  */
10373   compute_delayed_physnames (cu);
10374
10375   if (cu->language == language_rust)
10376     rust_union_quirks (cu);
10377
10378   /* TUs share symbol tables.
10379      If this is the first TU to use this symtab, complete the construction
10380      of it with end_expandable_symtab.  Otherwise, complete the addition of
10381      this TU's symbols to the existing symtab.  */
10382   if (sig_type->type_unit_group->compunit_symtab == NULL)
10383     {
10384       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10385       sig_type->type_unit_group->compunit_symtab = cust;
10386
10387       if (cust != NULL)
10388         {
10389           /* Set symtab language to language from DW_AT_language.  If the
10390              compilation is from a C file generated by language preprocessors,
10391              do not set the language if it was already deduced by
10392              start_subfile.  */
10393           if (!(cu->language == language_c
10394                 && COMPUNIT_FILETABS (cust)->language != language_c))
10395             COMPUNIT_FILETABS (cust)->language = cu->language;
10396         }
10397     }
10398   else
10399     {
10400       augment_type_symtab ();
10401       cust = sig_type->type_unit_group->compunit_symtab;
10402     }
10403
10404   if (dwarf2_per_objfile->using_index)
10405     per_cu->v.quick->compunit_symtab = cust;
10406   else
10407     {
10408       struct partial_symtab *pst = per_cu->v.psymtab;
10409       pst->compunit_symtab = cust;
10410       pst->readin = 1;
10411     }
10412 }
10413
10414 /* Process an imported unit DIE.  */
10415
10416 static void
10417 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10418 {
10419   struct attribute *attr;
10420
10421   /* For now we don't handle imported units in type units.  */
10422   if (cu->per_cu->is_debug_types)
10423     {
10424       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10425                " supported in type units [in module %s]"),
10426              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10427     }
10428
10429   attr = dwarf2_attr (die, DW_AT_import, cu);
10430   if (attr != NULL)
10431     {
10432       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10433       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10434       dwarf2_per_cu_data *per_cu
10435         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10436                                             cu->per_cu->dwarf2_per_objfile);
10437
10438       /* If necessary, add it to the queue and load its DIEs.  */
10439       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10440         load_full_comp_unit (per_cu, false, cu->language);
10441
10442       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10443                      per_cu);
10444     }
10445 }
10446
10447 /* RAII object that represents a process_die scope: i.e.,
10448    starts/finishes processing a DIE.  */
10449 class process_die_scope
10450 {
10451 public:
10452   process_die_scope (die_info *die, dwarf2_cu *cu)
10453     : m_die (die), m_cu (cu)
10454   {
10455     /* We should only be processing DIEs not already in process.  */
10456     gdb_assert (!m_die->in_process);
10457     m_die->in_process = true;
10458   }
10459
10460   ~process_die_scope ()
10461   {
10462     m_die->in_process = false;
10463
10464     /* If we're done processing the DIE for the CU that owns the line
10465        header, we don't need the line header anymore.  */
10466     if (m_cu->line_header_die_owner == m_die)
10467       {
10468         delete m_cu->line_header;
10469         m_cu->line_header = NULL;
10470         m_cu->line_header_die_owner = NULL;
10471       }
10472   }
10473
10474 private:
10475   die_info *m_die;
10476   dwarf2_cu *m_cu;
10477 };
10478
10479 /* Process a die and its children.  */
10480
10481 static void
10482 process_die (struct die_info *die, struct dwarf2_cu *cu)
10483 {
10484   process_die_scope scope (die, cu);
10485
10486   switch (die->tag)
10487     {
10488     case DW_TAG_padding:
10489       break;
10490     case DW_TAG_compile_unit:
10491     case DW_TAG_partial_unit:
10492       read_file_scope (die, cu);
10493       break;
10494     case DW_TAG_type_unit:
10495       read_type_unit_scope (die, cu);
10496       break;
10497     case DW_TAG_subprogram:
10498     case DW_TAG_inlined_subroutine:
10499       read_func_scope (die, cu);
10500       break;
10501     case DW_TAG_lexical_block:
10502     case DW_TAG_try_block:
10503     case DW_TAG_catch_block:
10504       read_lexical_block_scope (die, cu);
10505       break;
10506     case DW_TAG_call_site:
10507     case DW_TAG_GNU_call_site:
10508       read_call_site_scope (die, cu);
10509       break;
10510     case DW_TAG_class_type:
10511     case DW_TAG_interface_type:
10512     case DW_TAG_structure_type:
10513     case DW_TAG_union_type:
10514       process_structure_scope (die, cu);
10515       break;
10516     case DW_TAG_enumeration_type:
10517       process_enumeration_scope (die, cu);
10518       break;
10519
10520     /* These dies have a type, but processing them does not create
10521        a symbol or recurse to process the children.  Therefore we can
10522        read them on-demand through read_type_die.  */
10523     case DW_TAG_subroutine_type:
10524     case DW_TAG_set_type:
10525     case DW_TAG_array_type:
10526     case DW_TAG_pointer_type:
10527     case DW_TAG_ptr_to_member_type:
10528     case DW_TAG_reference_type:
10529     case DW_TAG_rvalue_reference_type:
10530     case DW_TAG_string_type:
10531       break;
10532
10533     case DW_TAG_base_type:
10534     case DW_TAG_subrange_type:
10535     case DW_TAG_typedef:
10536       /* Add a typedef symbol for the type definition, if it has a
10537          DW_AT_name.  */
10538       new_symbol (die, read_type_die (die, cu), cu);
10539       break;
10540     case DW_TAG_common_block:
10541       read_common_block (die, cu);
10542       break;
10543     case DW_TAG_common_inclusion:
10544       break;
10545     case DW_TAG_namespace:
10546       cu->processing_has_namespace_info = 1;
10547       read_namespace (die, cu);
10548       break;
10549     case DW_TAG_module:
10550       cu->processing_has_namespace_info = 1;
10551       read_module (die, cu);
10552       break;
10553     case DW_TAG_imported_declaration:
10554       cu->processing_has_namespace_info = 1;
10555       if (read_namespace_alias (die, cu))
10556         break;
10557       /* The declaration is not a global namespace alias.  */
10558       /* Fall through.  */
10559     case DW_TAG_imported_module:
10560       cu->processing_has_namespace_info = 1;
10561       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10562                                  || cu->language != language_fortran))
10563         complaint (_("Tag '%s' has unexpected children"),
10564                    dwarf_tag_name (die->tag));
10565       read_import_statement (die, cu);
10566       break;
10567
10568     case DW_TAG_imported_unit:
10569       process_imported_unit_die (die, cu);
10570       break;
10571
10572     case DW_TAG_variable:
10573       read_variable (die, cu);
10574       break;
10575
10576     default:
10577       new_symbol (die, NULL, cu);
10578       break;
10579     }
10580 }
10581 \f
10582 /* DWARF name computation.  */
10583
10584 /* A helper function for dwarf2_compute_name which determines whether DIE
10585    needs to have the name of the scope prepended to the name listed in the
10586    die.  */
10587
10588 static int
10589 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10590 {
10591   struct attribute *attr;
10592
10593   switch (die->tag)
10594     {
10595     case DW_TAG_namespace:
10596     case DW_TAG_typedef:
10597     case DW_TAG_class_type:
10598     case DW_TAG_interface_type:
10599     case DW_TAG_structure_type:
10600     case DW_TAG_union_type:
10601     case DW_TAG_enumeration_type:
10602     case DW_TAG_enumerator:
10603     case DW_TAG_subprogram:
10604     case DW_TAG_inlined_subroutine:
10605     case DW_TAG_member:
10606     case DW_TAG_imported_declaration:
10607       return 1;
10608
10609     case DW_TAG_variable:
10610     case DW_TAG_constant:
10611       /* We only need to prefix "globally" visible variables.  These include
10612          any variable marked with DW_AT_external or any variable that
10613          lives in a namespace.  [Variables in anonymous namespaces
10614          require prefixing, but they are not DW_AT_external.]  */
10615
10616       if (dwarf2_attr (die, DW_AT_specification, cu))
10617         {
10618           struct dwarf2_cu *spec_cu = cu;
10619
10620           return die_needs_namespace (die_specification (die, &spec_cu),
10621                                       spec_cu);
10622         }
10623
10624       attr = dwarf2_attr (die, DW_AT_external, cu);
10625       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10626           && die->parent->tag != DW_TAG_module)
10627         return 0;
10628       /* A variable in a lexical block of some kind does not need a
10629          namespace, even though in C++ such variables may be external
10630          and have a mangled name.  */
10631       if (die->parent->tag ==  DW_TAG_lexical_block
10632           || die->parent->tag ==  DW_TAG_try_block
10633           || die->parent->tag ==  DW_TAG_catch_block
10634           || die->parent->tag == DW_TAG_subprogram)
10635         return 0;
10636       return 1;
10637
10638     default:
10639       return 0;
10640     }
10641 }
10642
10643 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10644    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10645    defined for the given DIE.  */
10646
10647 static struct attribute *
10648 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10649 {
10650   struct attribute *attr;
10651
10652   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10653   if (attr == NULL)
10654     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10655
10656   return attr;
10657 }
10658
10659 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10660    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10661    defined for the given DIE.  */
10662
10663 static const char *
10664 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10665 {
10666   const char *linkage_name;
10667
10668   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10669   if (linkage_name == NULL)
10670     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10671
10672   return linkage_name;
10673 }
10674
10675 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10676    compute the physname for the object, which include a method's:
10677    - formal parameters (C++),
10678    - receiver type (Go),
10679
10680    The term "physname" is a bit confusing.
10681    For C++, for example, it is the demangled name.
10682    For Go, for example, it's the mangled name.
10683
10684    For Ada, return the DIE's linkage name rather than the fully qualified
10685    name.  PHYSNAME is ignored..
10686
10687    The result is allocated on the objfile_obstack and canonicalized.  */
10688
10689 static const char *
10690 dwarf2_compute_name (const char *name,
10691                      struct die_info *die, struct dwarf2_cu *cu,
10692                      int physname)
10693 {
10694   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10695
10696   if (name == NULL)
10697     name = dwarf2_name (die, cu);
10698
10699   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10700      but otherwise compute it by typename_concat inside GDB.
10701      FIXME: Actually this is not really true, or at least not always true.
10702      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10703      Fortran names because there is no mangling standard.  So new_symbol
10704      will set the demangled name to the result of dwarf2_full_name, and it is
10705      the demangled name that GDB uses if it exists.  */
10706   if (cu->language == language_ada
10707       || (cu->language == language_fortran && physname))
10708     {
10709       /* For Ada unit, we prefer the linkage name over the name, as
10710          the former contains the exported name, which the user expects
10711          to be able to reference.  Ideally, we want the user to be able
10712          to reference this entity using either natural or linkage name,
10713          but we haven't started looking at this enhancement yet.  */
10714       const char *linkage_name = dw2_linkage_name (die, cu);
10715
10716       if (linkage_name != NULL)
10717         return linkage_name;
10718     }
10719
10720   /* These are the only languages we know how to qualify names in.  */
10721   if (name != NULL
10722       && (cu->language == language_cplus
10723           || cu->language == language_fortran || cu->language == language_d
10724           || cu->language == language_rust))
10725     {
10726       if (die_needs_namespace (die, cu))
10727         {
10728           const char *prefix;
10729           const char *canonical_name = NULL;
10730
10731           string_file buf;
10732
10733           prefix = determine_prefix (die, cu);
10734           if (*prefix != '\0')
10735             {
10736               char *prefixed_name = typename_concat (NULL, prefix, name,
10737                                                      physname, cu);
10738
10739               buf.puts (prefixed_name);
10740               xfree (prefixed_name);
10741             }
10742           else
10743             buf.puts (name);
10744
10745           /* Template parameters may be specified in the DIE's DW_AT_name, or
10746              as children with DW_TAG_template_type_param or
10747              DW_TAG_value_type_param.  If the latter, add them to the name
10748              here.  If the name already has template parameters, then
10749              skip this step; some versions of GCC emit both, and
10750              it is more efficient to use the pre-computed name.
10751
10752              Something to keep in mind about this process: it is very
10753              unlikely, or in some cases downright impossible, to produce
10754              something that will match the mangled name of a function.
10755              If the definition of the function has the same debug info,
10756              we should be able to match up with it anyway.  But fallbacks
10757              using the minimal symbol, for instance to find a method
10758              implemented in a stripped copy of libstdc++, will not work.
10759              If we do not have debug info for the definition, we will have to
10760              match them up some other way.
10761
10762              When we do name matching there is a related problem with function
10763              templates; two instantiated function templates are allowed to
10764              differ only by their return types, which we do not add here.  */
10765
10766           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10767             {
10768               struct attribute *attr;
10769               struct die_info *child;
10770               int first = 1;
10771
10772               die->building_fullname = 1;
10773
10774               for (child = die->child; child != NULL; child = child->sibling)
10775                 {
10776                   struct type *type;
10777                   LONGEST value;
10778                   const gdb_byte *bytes;
10779                   struct dwarf2_locexpr_baton *baton;
10780                   struct value *v;
10781
10782                   if (child->tag != DW_TAG_template_type_param
10783                       && child->tag != DW_TAG_template_value_param)
10784                     continue;
10785
10786                   if (first)
10787                     {
10788                       buf.puts ("<");
10789                       first = 0;
10790                     }
10791                   else
10792                     buf.puts (", ");
10793
10794                   attr = dwarf2_attr (child, DW_AT_type, cu);
10795                   if (attr == NULL)
10796                     {
10797                       complaint (_("template parameter missing DW_AT_type"));
10798                       buf.puts ("UNKNOWN_TYPE");
10799                       continue;
10800                     }
10801                   type = die_type (child, cu);
10802
10803                   if (child->tag == DW_TAG_template_type_param)
10804                     {
10805                       c_print_type (type, "", &buf, -1, 0, cu->language,
10806                                     &type_print_raw_options);
10807                       continue;
10808                     }
10809
10810                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10811                   if (attr == NULL)
10812                     {
10813                       complaint (_("template parameter missing "
10814                                    "DW_AT_const_value"));
10815                       buf.puts ("UNKNOWN_VALUE");
10816                       continue;
10817                     }
10818
10819                   dwarf2_const_value_attr (attr, type, name,
10820                                            &cu->comp_unit_obstack, cu,
10821                                            &value, &bytes, &baton);
10822
10823                   if (TYPE_NOSIGN (type))
10824                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10825                        changed, this can use value_print instead.  */
10826                     c_printchar (value, type, &buf);
10827                   else
10828                     {
10829                       struct value_print_options opts;
10830
10831                       if (baton != NULL)
10832                         v = dwarf2_evaluate_loc_desc (type, NULL,
10833                                                       baton->data,
10834                                                       baton->size,
10835                                                       baton->per_cu);
10836                       else if (bytes != NULL)
10837                         {
10838                           v = allocate_value (type);
10839                           memcpy (value_contents_writeable (v), bytes,
10840                                   TYPE_LENGTH (type));
10841                         }
10842                       else
10843                         v = value_from_longest (type, value);
10844
10845                       /* Specify decimal so that we do not depend on
10846                          the radix.  */
10847                       get_formatted_print_options (&opts, 'd');
10848                       opts.raw = 1;
10849                       value_print (v, &buf, &opts);
10850                       release_value (v);
10851                     }
10852                 }
10853
10854               die->building_fullname = 0;
10855
10856               if (!first)
10857                 {
10858                   /* Close the argument list, with a space if necessary
10859                      (nested templates).  */
10860                   if (!buf.empty () && buf.string ().back () == '>')
10861                     buf.puts (" >");
10862                   else
10863                     buf.puts (">");
10864                 }
10865             }
10866
10867           /* For C++ methods, append formal parameter type
10868              information, if PHYSNAME.  */
10869
10870           if (physname && die->tag == DW_TAG_subprogram
10871               && cu->language == language_cplus)
10872             {
10873               struct type *type = read_type_die (die, cu);
10874
10875               c_type_print_args (type, &buf, 1, cu->language,
10876                                  &type_print_raw_options);
10877
10878               if (cu->language == language_cplus)
10879                 {
10880                   /* Assume that an artificial first parameter is
10881                      "this", but do not crash if it is not.  RealView
10882                      marks unnamed (and thus unused) parameters as
10883                      artificial; there is no way to differentiate
10884                      the two cases.  */
10885                   if (TYPE_NFIELDS (type) > 0
10886                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10887                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10888                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10889                                                                         0))))
10890                     buf.puts (" const");
10891                 }
10892             }
10893
10894           const std::string &intermediate_name = buf.string ();
10895
10896           if (cu->language == language_cplus)
10897             canonical_name
10898               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10899                                           &objfile->per_bfd->storage_obstack);
10900
10901           /* If we only computed INTERMEDIATE_NAME, or if
10902              INTERMEDIATE_NAME is already canonical, then we need to
10903              copy it to the appropriate obstack.  */
10904           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10905             name = ((const char *)
10906                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10907                                    intermediate_name.c_str (),
10908                                    intermediate_name.length ()));
10909           else
10910             name = canonical_name;
10911         }
10912     }
10913
10914   return name;
10915 }
10916
10917 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10918    If scope qualifiers are appropriate they will be added.  The result
10919    will be allocated on the storage_obstack, or NULL if the DIE does
10920    not have a name.  NAME may either be from a previous call to
10921    dwarf2_name or NULL.
10922
10923    The output string will be canonicalized (if C++).  */
10924
10925 static const char *
10926 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10927 {
10928   return dwarf2_compute_name (name, die, cu, 0);
10929 }
10930
10931 /* Construct a physname for the given DIE in CU.  NAME may either be
10932    from a previous call to dwarf2_name or NULL.  The result will be
10933    allocated on the objfile_objstack or NULL if the DIE does not have a
10934    name.
10935
10936    The output string will be canonicalized (if C++).  */
10937
10938 static const char *
10939 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10940 {
10941   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10942   const char *retval, *mangled = NULL, *canon = NULL;
10943   int need_copy = 1;
10944
10945   /* In this case dwarf2_compute_name is just a shortcut not building anything
10946      on its own.  */
10947   if (!die_needs_namespace (die, cu))
10948     return dwarf2_compute_name (name, die, cu, 1);
10949
10950   mangled = dw2_linkage_name (die, cu);
10951
10952   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10953      See https://github.com/rust-lang/rust/issues/32925.  */
10954   if (cu->language == language_rust && mangled != NULL
10955       && strchr (mangled, '{') != NULL)
10956     mangled = NULL;
10957
10958   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10959      has computed.  */
10960   gdb::unique_xmalloc_ptr<char> demangled;
10961   if (mangled != NULL)
10962     {
10963
10964       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
10965         {
10966           /* Do nothing (do not demangle the symbol name).  */
10967         }
10968       else if (cu->language == language_go)
10969         {
10970           /* This is a lie, but we already lie to the caller new_symbol.
10971              new_symbol assumes we return the mangled name.
10972              This just undoes that lie until things are cleaned up.  */
10973         }
10974       else
10975         {
10976           /* Use DMGL_RET_DROP for C++ template functions to suppress
10977              their return type.  It is easier for GDB users to search
10978              for such functions as `name(params)' than `long name(params)'.
10979              In such case the minimal symbol names do not match the full
10980              symbol names but for template functions there is never a need
10981              to look up their definition from their declaration so
10982              the only disadvantage remains the minimal symbol variant
10983              `long name(params)' does not have the proper inferior type.  */
10984           demangled.reset (gdb_demangle (mangled,
10985                                          (DMGL_PARAMS | DMGL_ANSI
10986                                           | DMGL_RET_DROP)));
10987         }
10988       if (demangled)
10989         canon = demangled.get ();
10990       else
10991         {
10992           canon = mangled;
10993           need_copy = 0;
10994         }
10995     }
10996
10997   if (canon == NULL || check_physname)
10998     {
10999       const char *physname = dwarf2_compute_name (name, die, cu, 1);
11000
11001       if (canon != NULL && strcmp (physname, canon) != 0)
11002         {
11003           /* It may not mean a bug in GDB.  The compiler could also
11004              compute DW_AT_linkage_name incorrectly.  But in such case
11005              GDB would need to be bug-to-bug compatible.  */
11006
11007           complaint (_("Computed physname <%s> does not match demangled <%s> "
11008                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11009                      physname, canon, mangled, sect_offset_str (die->sect_off),
11010                      objfile_name (objfile));
11011
11012           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11013              is available here - over computed PHYSNAME.  It is safer
11014              against both buggy GDB and buggy compilers.  */
11015
11016           retval = canon;
11017         }
11018       else
11019         {
11020           retval = physname;
11021           need_copy = 0;
11022         }
11023     }
11024   else
11025     retval = canon;
11026
11027   if (need_copy)
11028     retval = ((const char *)
11029               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11030                              retval, strlen (retval)));
11031
11032   return retval;
11033 }
11034
11035 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11036    a new symbol for it.
11037
11038    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11039
11040 static int
11041 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11042 {
11043   struct attribute *attr;
11044
11045   /* If the die does not have a name, this is not a namespace
11046      alias.  */
11047   attr = dwarf2_attr (die, DW_AT_name, cu);
11048   if (attr != NULL)
11049     {
11050       int num;
11051       struct die_info *d = die;
11052       struct dwarf2_cu *imported_cu = cu;
11053
11054       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11055          keep inspecting DIEs until we hit the underlying import.  */
11056 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11057       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11058         {
11059           attr = dwarf2_attr (d, DW_AT_import, cu);
11060           if (attr == NULL)
11061             break;
11062
11063           d = follow_die_ref (d, attr, &imported_cu);
11064           if (d->tag != DW_TAG_imported_declaration)
11065             break;
11066         }
11067
11068       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11069         {
11070           complaint (_("DIE at %s has too many recursively imported "
11071                        "declarations"), sect_offset_str (d->sect_off));
11072           return 0;
11073         }
11074
11075       if (attr != NULL)
11076         {
11077           struct type *type;
11078           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11079
11080           type = get_die_type_at_offset (sect_off, cu->per_cu);
11081           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11082             {
11083               /* This declaration is a global namespace alias.  Add
11084                  a symbol for it whose type is the aliased namespace.  */
11085               new_symbol (die, type, cu);
11086               return 1;
11087             }
11088         }
11089     }
11090
11091   return 0;
11092 }
11093
11094 /* Return the using directives repository (global or local?) to use in the
11095    current context for LANGUAGE.
11096
11097    For Ada, imported declarations can materialize renamings, which *may* be
11098    global.  However it is impossible (for now?) in DWARF to distinguish
11099    "external" imported declarations and "static" ones.  As all imported
11100    declarations seem to be static in all other languages, make them all CU-wide
11101    global only in Ada.  */
11102
11103 static struct using_direct **
11104 using_directives (enum language language)
11105 {
11106   if (language == language_ada && context_stack_depth == 0)
11107     return &global_using_directives;
11108   else
11109     return &local_using_directives;
11110 }
11111
11112 /* Read the import statement specified by the given die and record it.  */
11113
11114 static void
11115 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11116 {
11117   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11118   struct attribute *import_attr;
11119   struct die_info *imported_die, *child_die;
11120   struct dwarf2_cu *imported_cu;
11121   const char *imported_name;
11122   const char *imported_name_prefix;
11123   const char *canonical_name;
11124   const char *import_alias;
11125   const char *imported_declaration = NULL;
11126   const char *import_prefix;
11127   std::vector<const char *> excludes;
11128
11129   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11130   if (import_attr == NULL)
11131     {
11132       complaint (_("Tag '%s' has no DW_AT_import"),
11133                  dwarf_tag_name (die->tag));
11134       return;
11135     }
11136
11137   imported_cu = cu;
11138   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11139   imported_name = dwarf2_name (imported_die, imported_cu);
11140   if (imported_name == NULL)
11141     {
11142       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11143
11144         The import in the following code:
11145         namespace A
11146           {
11147             typedef int B;
11148           }
11149
11150         int main ()
11151           {
11152             using A::B;
11153             B b;
11154             return b;
11155           }
11156
11157         ...
11158          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11159             <52>   DW_AT_decl_file   : 1
11160             <53>   DW_AT_decl_line   : 6
11161             <54>   DW_AT_import      : <0x75>
11162          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11163             <59>   DW_AT_name        : B
11164             <5b>   DW_AT_decl_file   : 1
11165             <5c>   DW_AT_decl_line   : 2
11166             <5d>   DW_AT_type        : <0x6e>
11167         ...
11168          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11169             <76>   DW_AT_byte_size   : 4
11170             <77>   DW_AT_encoding    : 5        (signed)
11171
11172         imports the wrong die ( 0x75 instead of 0x58 ).
11173         This case will be ignored until the gcc bug is fixed.  */
11174       return;
11175     }
11176
11177   /* Figure out the local name after import.  */
11178   import_alias = dwarf2_name (die, cu);
11179
11180   /* Figure out where the statement is being imported to.  */
11181   import_prefix = determine_prefix (die, cu);
11182
11183   /* Figure out what the scope of the imported die is and prepend it
11184      to the name of the imported die.  */
11185   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11186
11187   if (imported_die->tag != DW_TAG_namespace
11188       && imported_die->tag != DW_TAG_module)
11189     {
11190       imported_declaration = imported_name;
11191       canonical_name = imported_name_prefix;
11192     }
11193   else if (strlen (imported_name_prefix) > 0)
11194     canonical_name = obconcat (&objfile->objfile_obstack,
11195                                imported_name_prefix,
11196                                (cu->language == language_d ? "." : "::"),
11197                                imported_name, (char *) NULL);
11198   else
11199     canonical_name = imported_name;
11200
11201   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11202     for (child_die = die->child; child_die && child_die->tag;
11203          child_die = sibling_die (child_die))
11204       {
11205         /* DWARF-4: A Fortran use statement with a “rename list” may be
11206            represented by an imported module entry with an import attribute
11207            referring to the module and owned entries corresponding to those
11208            entities that are renamed as part of being imported.  */
11209
11210         if (child_die->tag != DW_TAG_imported_declaration)
11211           {
11212             complaint (_("child DW_TAG_imported_declaration expected "
11213                          "- DIE at %s [in module %s]"),
11214                        sect_offset_str (child_die->sect_off),
11215                        objfile_name (objfile));
11216             continue;
11217           }
11218
11219         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11220         if (import_attr == NULL)
11221           {
11222             complaint (_("Tag '%s' has no DW_AT_import"),
11223                        dwarf_tag_name (child_die->tag));
11224             continue;
11225           }
11226
11227         imported_cu = cu;
11228         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11229                                               &imported_cu);
11230         imported_name = dwarf2_name (imported_die, imported_cu);
11231         if (imported_name == NULL)
11232           {
11233             complaint (_("child DW_TAG_imported_declaration has unknown "
11234                          "imported name - DIE at %s [in module %s]"),
11235                        sect_offset_str (child_die->sect_off),
11236                        objfile_name (objfile));
11237             continue;
11238           }
11239
11240         excludes.push_back (imported_name);
11241
11242         process_die (child_die, cu);
11243       }
11244
11245   add_using_directive (using_directives (cu->language),
11246                        import_prefix,
11247                        canonical_name,
11248                        import_alias,
11249                        imported_declaration,
11250                        excludes,
11251                        0,
11252                        &objfile->objfile_obstack);
11253 }
11254
11255 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11256    types, but gives them a size of zero.  Starting with version 14,
11257    ICC is compatible with GCC.  */
11258
11259 static int
11260 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11261 {
11262   if (!cu->checked_producer)
11263     check_producer (cu);
11264
11265   return cu->producer_is_icc_lt_14;
11266 }
11267
11268 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11269    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11270    this, it was first present in GCC release 4.3.0.  */
11271
11272 static int
11273 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11274 {
11275   if (!cu->checked_producer)
11276     check_producer (cu);
11277
11278   return cu->producer_is_gcc_lt_4_3;
11279 }
11280
11281 static file_and_directory
11282 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11283 {
11284   file_and_directory res;
11285
11286   /* Find the filename.  Do not use dwarf2_name here, since the filename
11287      is not a source language identifier.  */
11288   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11289   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11290
11291   if (res.comp_dir == NULL
11292       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11293       && IS_ABSOLUTE_PATH (res.name))
11294     {
11295       res.comp_dir_storage = ldirname (res.name);
11296       if (!res.comp_dir_storage.empty ())
11297         res.comp_dir = res.comp_dir_storage.c_str ();
11298     }
11299   if (res.comp_dir != NULL)
11300     {
11301       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11302          directory, get rid of it.  */
11303       const char *cp = strchr (res.comp_dir, ':');
11304
11305       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11306         res.comp_dir = cp + 1;
11307     }
11308
11309   if (res.name == NULL)
11310     res.name = "<unknown>";
11311
11312   return res;
11313 }
11314
11315 /* Handle DW_AT_stmt_list for a compilation unit.
11316    DIE is the DW_TAG_compile_unit die for CU.
11317    COMP_DIR is the compilation directory.  LOWPC is passed to
11318    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11319
11320 static void
11321 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11322                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11323 {
11324   struct dwarf2_per_objfile *dwarf2_per_objfile
11325     = cu->per_cu->dwarf2_per_objfile;
11326   struct objfile *objfile = dwarf2_per_objfile->objfile;
11327   struct attribute *attr;
11328   struct line_header line_header_local;
11329   hashval_t line_header_local_hash;
11330   void **slot;
11331   int decode_mapping;
11332
11333   gdb_assert (! cu->per_cu->is_debug_types);
11334
11335   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11336   if (attr == NULL)
11337     return;
11338
11339   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11340
11341   /* The line header hash table is only created if needed (it exists to
11342      prevent redundant reading of the line table for partial_units).
11343      If we're given a partial_unit, we'll need it.  If we're given a
11344      compile_unit, then use the line header hash table if it's already
11345      created, but don't create one just yet.  */
11346
11347   if (dwarf2_per_objfile->line_header_hash == NULL
11348       && die->tag == DW_TAG_partial_unit)
11349     {
11350       dwarf2_per_objfile->line_header_hash
11351         = htab_create_alloc_ex (127, line_header_hash_voidp,
11352                                 line_header_eq_voidp,
11353                                 free_line_header_voidp,
11354                                 &objfile->objfile_obstack,
11355                                 hashtab_obstack_allocate,
11356                                 dummy_obstack_deallocate);
11357     }
11358
11359   line_header_local.sect_off = line_offset;
11360   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11361   line_header_local_hash = line_header_hash (&line_header_local);
11362   if (dwarf2_per_objfile->line_header_hash != NULL)
11363     {
11364       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11365                                        &line_header_local,
11366                                        line_header_local_hash, NO_INSERT);
11367
11368       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11369          is not present in *SLOT (since if there is something in *SLOT then
11370          it will be for a partial_unit).  */
11371       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11372         {
11373           gdb_assert (*slot != NULL);
11374           cu->line_header = (struct line_header *) *slot;
11375           return;
11376         }
11377     }
11378
11379   /* dwarf_decode_line_header does not yet provide sufficient information.
11380      We always have to call also dwarf_decode_lines for it.  */
11381   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11382   if (lh == NULL)
11383     return;
11384
11385   cu->line_header = lh.release ();
11386   cu->line_header_die_owner = die;
11387
11388   if (dwarf2_per_objfile->line_header_hash == NULL)
11389     slot = NULL;
11390   else
11391     {
11392       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11393                                        &line_header_local,
11394                                        line_header_local_hash, INSERT);
11395       gdb_assert (slot != NULL);
11396     }
11397   if (slot != NULL && *slot == NULL)
11398     {
11399       /* This newly decoded line number information unit will be owned
11400          by line_header_hash hash table.  */
11401       *slot = cu->line_header;
11402       cu->line_header_die_owner = NULL;
11403     }
11404   else
11405     {
11406       /* We cannot free any current entry in (*slot) as that struct line_header
11407          may be already used by multiple CUs.  Create only temporary decoded
11408          line_header for this CU - it may happen at most once for each line
11409          number information unit.  And if we're not using line_header_hash
11410          then this is what we want as well.  */
11411       gdb_assert (die->tag != DW_TAG_partial_unit);
11412     }
11413   decode_mapping = (die->tag != DW_TAG_partial_unit);
11414   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11415                       decode_mapping);
11416
11417 }
11418
11419 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11420
11421 static void
11422 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11423 {
11424   struct dwarf2_per_objfile *dwarf2_per_objfile
11425     = cu->per_cu->dwarf2_per_objfile;
11426   struct objfile *objfile = dwarf2_per_objfile->objfile;
11427   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11428   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11429   CORE_ADDR highpc = ((CORE_ADDR) 0);
11430   struct attribute *attr;
11431   struct die_info *child_die;
11432   CORE_ADDR baseaddr;
11433
11434   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11435
11436   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11437
11438   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11439      from finish_block.  */
11440   if (lowpc == ((CORE_ADDR) -1))
11441     lowpc = highpc;
11442   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11443
11444   file_and_directory fnd = find_file_and_directory (die, cu);
11445
11446   prepare_one_comp_unit (cu, die, cu->language);
11447
11448   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11449      standardised yet.  As a workaround for the language detection we fall
11450      back to the DW_AT_producer string.  */
11451   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11452     cu->language = language_opencl;
11453
11454   /* Similar hack for Go.  */
11455   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11456     set_cu_language (DW_LANG_Go, cu);
11457
11458   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11459
11460   /* Decode line number information if present.  We do this before
11461      processing child DIEs, so that the line header table is available
11462      for DW_AT_decl_file.  */
11463   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11464
11465   /* Process all dies in compilation unit.  */
11466   if (die->child != NULL)
11467     {
11468       child_die = die->child;
11469       while (child_die && child_die->tag)
11470         {
11471           process_die (child_die, cu);
11472           child_die = sibling_die (child_die);
11473         }
11474     }
11475
11476   /* Decode macro information, if present.  Dwarf 2 macro information
11477      refers to information in the line number info statement program
11478      header, so we can only read it if we've read the header
11479      successfully.  */
11480   attr = dwarf2_attr (die, DW_AT_macros, cu);
11481   if (attr == NULL)
11482     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11483   if (attr && cu->line_header)
11484     {
11485       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11486         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11487
11488       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11489     }
11490   else
11491     {
11492       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11493       if (attr && cu->line_header)
11494         {
11495           unsigned int macro_offset = DW_UNSND (attr);
11496
11497           dwarf_decode_macros (cu, macro_offset, 0);
11498         }
11499     }
11500 }
11501
11502 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11503    Create the set of symtabs used by this TU, or if this TU is sharing
11504    symtabs with another TU and the symtabs have already been created
11505    then restore those symtabs in the line header.
11506    We don't need the pc/line-number mapping for type units.  */
11507
11508 static void
11509 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11510 {
11511   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11512   struct type_unit_group *tu_group;
11513   int first_time;
11514   struct attribute *attr;
11515   unsigned int i;
11516   struct signatured_type *sig_type;
11517
11518   gdb_assert (per_cu->is_debug_types);
11519   sig_type = (struct signatured_type *) per_cu;
11520
11521   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11522
11523   /* If we're using .gdb_index (includes -readnow) then
11524      per_cu->type_unit_group may not have been set up yet.  */
11525   if (sig_type->type_unit_group == NULL)
11526     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11527   tu_group = sig_type->type_unit_group;
11528
11529   /* If we've already processed this stmt_list there's no real need to
11530      do it again, we could fake it and just recreate the part we need
11531      (file name,index -> symtab mapping).  If data shows this optimization
11532      is useful we can do it then.  */
11533   first_time = tu_group->compunit_symtab == NULL;
11534
11535   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11536      debug info.  */
11537   line_header_up lh;
11538   if (attr != NULL)
11539     {
11540       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11541       lh = dwarf_decode_line_header (line_offset, cu);
11542     }
11543   if (lh == NULL)
11544     {
11545       if (first_time)
11546         dwarf2_start_symtab (cu, "", NULL, 0);
11547       else
11548         {
11549           gdb_assert (tu_group->symtabs == NULL);
11550           restart_symtab (tu_group->compunit_symtab, "", 0);
11551         }
11552       return;
11553     }
11554
11555   cu->line_header = lh.release ();
11556   cu->line_header_die_owner = die;
11557
11558   if (first_time)
11559     {
11560       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11561
11562       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11563          still initializing it, and our caller (a few levels up)
11564          process_full_type_unit still needs to know if this is the first
11565          time.  */
11566
11567       tu_group->num_symtabs = cu->line_header->file_names.size ();
11568       tu_group->symtabs = XNEWVEC (struct symtab *,
11569                                    cu->line_header->file_names.size ());
11570
11571       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11572         {
11573           file_entry &fe = cu->line_header->file_names[i];
11574
11575           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11576
11577           if (current_subfile->symtab == NULL)
11578             {
11579               /* NOTE: start_subfile will recognize when it's been
11580                  passed a file it has already seen.  So we can't
11581                  assume there's a simple mapping from
11582                  cu->line_header->file_names to subfiles, plus
11583                  cu->line_header->file_names may contain dups.  */
11584               current_subfile->symtab
11585                 = allocate_symtab (cust, current_subfile->name);
11586             }
11587
11588           fe.symtab = current_subfile->symtab;
11589           tu_group->symtabs[i] = fe.symtab;
11590         }
11591     }
11592   else
11593     {
11594       restart_symtab (tu_group->compunit_symtab, "", 0);
11595
11596       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11597         {
11598           file_entry &fe = cu->line_header->file_names[i];
11599
11600           fe.symtab = tu_group->symtabs[i];
11601         }
11602     }
11603
11604   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11605      so they don't have a "real" (so to speak) symtab anyway.
11606      There is later code that will assign the main symtab to all symbols
11607      that don't have one.  We need to handle the case of a symbol with a
11608      missing symtab (DW_AT_decl_file) anyway.  */
11609 }
11610
11611 /* Process DW_TAG_type_unit.
11612    For TUs we want to skip the first top level sibling if it's not the
11613    actual type being defined by this TU.  In this case the first top
11614    level sibling is there to provide context only.  */
11615
11616 static void
11617 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11618 {
11619   struct die_info *child_die;
11620
11621   prepare_one_comp_unit (cu, die, language_minimal);
11622
11623   /* Initialize (or reinitialize) the machinery for building symtabs.
11624      We do this before processing child DIEs, so that the line header table
11625      is available for DW_AT_decl_file.  */
11626   setup_type_unit_groups (die, cu);
11627
11628   if (die->child != NULL)
11629     {
11630       child_die = die->child;
11631       while (child_die && child_die->tag)
11632         {
11633           process_die (child_die, cu);
11634           child_die = sibling_die (child_die);
11635         }
11636     }
11637 }
11638 \f
11639 /* DWO/DWP files.
11640
11641    http://gcc.gnu.org/wiki/DebugFission
11642    http://gcc.gnu.org/wiki/DebugFissionDWP
11643
11644    To simplify handling of both DWO files ("object" files with the DWARF info)
11645    and DWP files (a file with the DWOs packaged up into one file), we treat
11646    DWP files as having a collection of virtual DWO files.  */
11647
11648 static hashval_t
11649 hash_dwo_file (const void *item)
11650 {
11651   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11652   hashval_t hash;
11653
11654   hash = htab_hash_string (dwo_file->dwo_name);
11655   if (dwo_file->comp_dir != NULL)
11656     hash += htab_hash_string (dwo_file->comp_dir);
11657   return hash;
11658 }
11659
11660 static int
11661 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11662 {
11663   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11664   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11665
11666   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11667     return 0;
11668   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11669     return lhs->comp_dir == rhs->comp_dir;
11670   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11671 }
11672
11673 /* Allocate a hash table for DWO files.  */
11674
11675 static htab_t
11676 allocate_dwo_file_hash_table (struct objfile *objfile)
11677 {
11678   return htab_create_alloc_ex (41,
11679                                hash_dwo_file,
11680                                eq_dwo_file,
11681                                NULL,
11682                                &objfile->objfile_obstack,
11683                                hashtab_obstack_allocate,
11684                                dummy_obstack_deallocate);
11685 }
11686
11687 /* Lookup DWO file DWO_NAME.  */
11688
11689 static void **
11690 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11691                       const char *dwo_name,
11692                       const char *comp_dir)
11693 {
11694   struct dwo_file find_entry;
11695   void **slot;
11696
11697   if (dwarf2_per_objfile->dwo_files == NULL)
11698     dwarf2_per_objfile->dwo_files
11699       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11700
11701   memset (&find_entry, 0, sizeof (find_entry));
11702   find_entry.dwo_name = dwo_name;
11703   find_entry.comp_dir = comp_dir;
11704   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11705
11706   return slot;
11707 }
11708
11709 static hashval_t
11710 hash_dwo_unit (const void *item)
11711 {
11712   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11713
11714   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11715   return dwo_unit->signature;
11716 }
11717
11718 static int
11719 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11720 {
11721   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11722   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11723
11724   /* The signature is assumed to be unique within the DWO file.
11725      So while object file CU dwo_id's always have the value zero,
11726      that's OK, assuming each object file DWO file has only one CU,
11727      and that's the rule for now.  */
11728   return lhs->signature == rhs->signature;
11729 }
11730
11731 /* Allocate a hash table for DWO CUs,TUs.
11732    There is one of these tables for each of CUs,TUs for each DWO file.  */
11733
11734 static htab_t
11735 allocate_dwo_unit_table (struct objfile *objfile)
11736 {
11737   /* Start out with a pretty small number.
11738      Generally DWO files contain only one CU and maybe some TUs.  */
11739   return htab_create_alloc_ex (3,
11740                                hash_dwo_unit,
11741                                eq_dwo_unit,
11742                                NULL,
11743                                &objfile->objfile_obstack,
11744                                hashtab_obstack_allocate,
11745                                dummy_obstack_deallocate);
11746 }
11747
11748 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11749
11750 struct create_dwo_cu_data
11751 {
11752   struct dwo_file *dwo_file;
11753   struct dwo_unit dwo_unit;
11754 };
11755
11756 /* die_reader_func for create_dwo_cu.  */
11757
11758 static void
11759 create_dwo_cu_reader (const struct die_reader_specs *reader,
11760                       const gdb_byte *info_ptr,
11761                       struct die_info *comp_unit_die,
11762                       int has_children,
11763                       void *datap)
11764 {
11765   struct dwarf2_cu *cu = reader->cu;
11766   sect_offset sect_off = cu->per_cu->sect_off;
11767   struct dwarf2_section_info *section = cu->per_cu->section;
11768   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11769   struct dwo_file *dwo_file = data->dwo_file;
11770   struct dwo_unit *dwo_unit = &data->dwo_unit;
11771   struct attribute *attr;
11772
11773   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11774   if (attr == NULL)
11775     {
11776       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11777                    " its dwo_id [in module %s]"),
11778                  sect_offset_str (sect_off), dwo_file->dwo_name);
11779       return;
11780     }
11781
11782   dwo_unit->dwo_file = dwo_file;
11783   dwo_unit->signature = DW_UNSND (attr);
11784   dwo_unit->section = section;
11785   dwo_unit->sect_off = sect_off;
11786   dwo_unit->length = cu->per_cu->length;
11787
11788   if (dwarf_read_debug)
11789     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11790                         sect_offset_str (sect_off),
11791                         hex_string (dwo_unit->signature));
11792 }
11793
11794 /* Create the dwo_units for the CUs in a DWO_FILE.
11795    Note: This function processes DWO files only, not DWP files.  */
11796
11797 static void
11798 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11799                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11800                        htab_t &cus_htab)
11801 {
11802   struct objfile *objfile = dwarf2_per_objfile->objfile;
11803   const gdb_byte *info_ptr, *end_ptr;
11804
11805   dwarf2_read_section (objfile, &section);
11806   info_ptr = section.buffer;
11807
11808   if (info_ptr == NULL)
11809     return;
11810
11811   if (dwarf_read_debug)
11812     {
11813       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11814                           get_section_name (&section),
11815                           get_section_file_name (&section));
11816     }
11817
11818   end_ptr = info_ptr + section.size;
11819   while (info_ptr < end_ptr)
11820     {
11821       struct dwarf2_per_cu_data per_cu;
11822       struct create_dwo_cu_data create_dwo_cu_data;
11823       struct dwo_unit *dwo_unit;
11824       void **slot;
11825       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11826
11827       memset (&create_dwo_cu_data.dwo_unit, 0,
11828               sizeof (create_dwo_cu_data.dwo_unit));
11829       memset (&per_cu, 0, sizeof (per_cu));
11830       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11831       per_cu.is_debug_types = 0;
11832       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11833       per_cu.section = &section;
11834       create_dwo_cu_data.dwo_file = &dwo_file;
11835
11836       init_cutu_and_read_dies_no_follow (
11837           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11838       info_ptr += per_cu.length;
11839
11840       // If the unit could not be parsed, skip it.
11841       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11842         continue;
11843
11844       if (cus_htab == NULL)
11845         cus_htab = allocate_dwo_unit_table (objfile);
11846
11847       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11848       *dwo_unit = create_dwo_cu_data.dwo_unit;
11849       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11850       gdb_assert (slot != NULL);
11851       if (*slot != NULL)
11852         {
11853           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11854           sect_offset dup_sect_off = dup_cu->sect_off;
11855
11856           complaint (_("debug cu entry at offset %s is duplicate to"
11857                        " the entry at offset %s, signature %s"),
11858                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11859                      hex_string (dwo_unit->signature));
11860         }
11861       *slot = (void *)dwo_unit;
11862     }
11863 }
11864
11865 /* DWP file .debug_{cu,tu}_index section format:
11866    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11867
11868    DWP Version 1:
11869
11870    Both index sections have the same format, and serve to map a 64-bit
11871    signature to a set of section numbers.  Each section begins with a header,
11872    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11873    indexes, and a pool of 32-bit section numbers.  The index sections will be
11874    aligned at 8-byte boundaries in the file.
11875
11876    The index section header consists of:
11877
11878     V, 32 bit version number
11879     -, 32 bits unused
11880     N, 32 bit number of compilation units or type units in the index
11881     M, 32 bit number of slots in the hash table
11882
11883    Numbers are recorded using the byte order of the application binary.
11884
11885    The hash table begins at offset 16 in the section, and consists of an array
11886    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11887    order of the application binary).  Unused slots in the hash table are 0.
11888    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11889
11890    The parallel table begins immediately after the hash table
11891    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11892    array of 32-bit indexes (using the byte order of the application binary),
11893    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11894    table contains a 32-bit index into the pool of section numbers.  For unused
11895    hash table slots, the corresponding entry in the parallel table will be 0.
11896
11897    The pool of section numbers begins immediately following the hash table
11898    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11899    section numbers consists of an array of 32-bit words (using the byte order
11900    of the application binary).  Each item in the array is indexed starting
11901    from 0.  The hash table entry provides the index of the first section
11902    number in the set.  Additional section numbers in the set follow, and the
11903    set is terminated by a 0 entry (section number 0 is not used in ELF).
11904
11905    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11906    section must be the first entry in the set, and the .debug_abbrev.dwo must
11907    be the second entry. Other members of the set may follow in any order.
11908
11909    ---
11910
11911    DWP Version 2:
11912
11913    DWP Version 2 combines all the .debug_info, etc. sections into one,
11914    and the entries in the index tables are now offsets into these sections.
11915    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11916    section.
11917
11918    Index Section Contents:
11919     Header
11920     Hash Table of Signatures   dwp_hash_table.hash_table
11921     Parallel Table of Indices  dwp_hash_table.unit_table
11922     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11923     Table of Section Sizes     dwp_hash_table.v2.sizes
11924
11925    The index section header consists of:
11926
11927     V, 32 bit version number
11928     L, 32 bit number of columns in the table of section offsets
11929     N, 32 bit number of compilation units or type units in the index
11930     M, 32 bit number of slots in the hash table
11931
11932    Numbers are recorded using the byte order of the application binary.
11933
11934    The hash table has the same format as version 1.
11935    The parallel table of indices has the same format as version 1,
11936    except that the entries are origin-1 indices into the table of sections
11937    offsets and the table of section sizes.
11938
11939    The table of offsets begins immediately following the parallel table
11940    (at offset 16 + 12 * M from the beginning of the section).  The table is
11941    a two-dimensional array of 32-bit words (using the byte order of the
11942    application binary), with L columns and N+1 rows, in row-major order.
11943    Each row in the array is indexed starting from 0.  The first row provides
11944    a key to the remaining rows: each column in this row provides an identifier
11945    for a debug section, and the offsets in the same column of subsequent rows
11946    refer to that section.  The section identifiers are:
11947
11948     DW_SECT_INFO         1  .debug_info.dwo
11949     DW_SECT_TYPES        2  .debug_types.dwo
11950     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11951     DW_SECT_LINE         4  .debug_line.dwo
11952     DW_SECT_LOC          5  .debug_loc.dwo
11953     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11954     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11955     DW_SECT_MACRO        8  .debug_macro.dwo
11956
11957    The offsets provided by the CU and TU index sections are the base offsets
11958    for the contributions made by each CU or TU to the corresponding section
11959    in the package file.  Each CU and TU header contains an abbrev_offset
11960    field, used to find the abbreviations table for that CU or TU within the
11961    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11962    be interpreted as relative to the base offset given in the index section.
11963    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11964    should be interpreted as relative to the base offset for .debug_line.dwo,
11965    and offsets into other debug sections obtained from DWARF attributes should
11966    also be interpreted as relative to the corresponding base offset.
11967
11968    The table of sizes begins immediately following the table of offsets.
11969    Like the table of offsets, it is a two-dimensional array of 32-bit words,
11970    with L columns and N rows, in row-major order.  Each row in the array is
11971    indexed starting from 1 (row 0 is shared by the two tables).
11972
11973    ---
11974
11975    Hash table lookup is handled the same in version 1 and 2:
11976
11977    We assume that N and M will not exceed 2^32 - 1.
11978    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
11979
11980    Given a 64-bit compilation unit signature or a type signature S, an entry
11981    in the hash table is located as follows:
11982
11983    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
11984       the low-order k bits all set to 1.
11985
11986    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
11987
11988    3) If the hash table entry at index H matches the signature, use that
11989       entry.  If the hash table entry at index H is unused (all zeroes),
11990       terminate the search: the signature is not present in the table.
11991
11992    4) Let H = (H + H') modulo M. Repeat at Step 3.
11993
11994    Because M > N and H' and M are relatively prime, the search is guaranteed
11995    to stop at an unused slot or find the match.  */
11996
11997 /* Create a hash table to map DWO IDs to their CU/TU entry in
11998    .debug_{info,types}.dwo in DWP_FILE.
11999    Returns NULL if there isn't one.
12000    Note: This function processes DWP files only, not DWO files.  */
12001
12002 static struct dwp_hash_table *
12003 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12004                        struct dwp_file *dwp_file, int is_debug_types)
12005 {
12006   struct objfile *objfile = dwarf2_per_objfile->objfile;
12007   bfd *dbfd = dwp_file->dbfd.get ();
12008   const gdb_byte *index_ptr, *index_end;
12009   struct dwarf2_section_info *index;
12010   uint32_t version, nr_columns, nr_units, nr_slots;
12011   struct dwp_hash_table *htab;
12012
12013   if (is_debug_types)
12014     index = &dwp_file->sections.tu_index;
12015   else
12016     index = &dwp_file->sections.cu_index;
12017
12018   if (dwarf2_section_empty_p (index))
12019     return NULL;
12020   dwarf2_read_section (objfile, index);
12021
12022   index_ptr = index->buffer;
12023   index_end = index_ptr + index->size;
12024
12025   version = read_4_bytes (dbfd, index_ptr);
12026   index_ptr += 4;
12027   if (version == 2)
12028     nr_columns = read_4_bytes (dbfd, index_ptr);
12029   else
12030     nr_columns = 0;
12031   index_ptr += 4;
12032   nr_units = read_4_bytes (dbfd, index_ptr);
12033   index_ptr += 4;
12034   nr_slots = read_4_bytes (dbfd, index_ptr);
12035   index_ptr += 4;
12036
12037   if (version != 1 && version != 2)
12038     {
12039       error (_("Dwarf Error: unsupported DWP file version (%s)"
12040                " [in module %s]"),
12041              pulongest (version), dwp_file->name);
12042     }
12043   if (nr_slots != (nr_slots & -nr_slots))
12044     {
12045       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12046                " is not power of 2 [in module %s]"),
12047              pulongest (nr_slots), dwp_file->name);
12048     }
12049
12050   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12051   htab->version = version;
12052   htab->nr_columns = nr_columns;
12053   htab->nr_units = nr_units;
12054   htab->nr_slots = nr_slots;
12055   htab->hash_table = index_ptr;
12056   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12057
12058   /* Exit early if the table is empty.  */
12059   if (nr_slots == 0 || nr_units == 0
12060       || (version == 2 && nr_columns == 0))
12061     {
12062       /* All must be zero.  */
12063       if (nr_slots != 0 || nr_units != 0
12064           || (version == 2 && nr_columns != 0))
12065         {
12066           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12067                        " all zero [in modules %s]"),
12068                      dwp_file->name);
12069         }
12070       return htab;
12071     }
12072
12073   if (version == 1)
12074     {
12075       htab->section_pool.v1.indices =
12076         htab->unit_table + sizeof (uint32_t) * nr_slots;
12077       /* It's harder to decide whether the section is too small in v1.
12078          V1 is deprecated anyway so we punt.  */
12079     }
12080   else
12081     {
12082       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12083       int *ids = htab->section_pool.v2.section_ids;
12084       /* Reverse map for error checking.  */
12085       int ids_seen[DW_SECT_MAX + 1];
12086       int i;
12087
12088       if (nr_columns < 2)
12089         {
12090           error (_("Dwarf Error: bad DWP hash table, too few columns"
12091                    " in section table [in module %s]"),
12092                  dwp_file->name);
12093         }
12094       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12095         {
12096           error (_("Dwarf Error: bad DWP hash table, too many columns"
12097                    " in section table [in module %s]"),
12098                  dwp_file->name);
12099         }
12100       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12101       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12102       for (i = 0; i < nr_columns; ++i)
12103         {
12104           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12105
12106           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12107             {
12108               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12109                        " in section table [in module %s]"),
12110                      id, dwp_file->name);
12111             }
12112           if (ids_seen[id] != -1)
12113             {
12114               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12115                        " id %d in section table [in module %s]"),
12116                      id, dwp_file->name);
12117             }
12118           ids_seen[id] = i;
12119           ids[i] = id;
12120         }
12121       /* Must have exactly one info or types section.  */
12122       if (((ids_seen[DW_SECT_INFO] != -1)
12123            + (ids_seen[DW_SECT_TYPES] != -1))
12124           != 1)
12125         {
12126           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12127                    " DWO info/types section [in module %s]"),
12128                  dwp_file->name);
12129         }
12130       /* Must have an abbrev section.  */
12131       if (ids_seen[DW_SECT_ABBREV] == -1)
12132         {
12133           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12134                    " section [in module %s]"),
12135                  dwp_file->name);
12136         }
12137       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12138       htab->section_pool.v2.sizes =
12139         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12140                                          * nr_units * nr_columns);
12141       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12142                                           * nr_units * nr_columns))
12143           > index_end)
12144         {
12145           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12146                    " [in module %s]"),
12147                  dwp_file->name);
12148         }
12149     }
12150
12151   return htab;
12152 }
12153
12154 /* Update SECTIONS with the data from SECTP.
12155
12156    This function is like the other "locate" section routines that are
12157    passed to bfd_map_over_sections, but in this context the sections to
12158    read comes from the DWP V1 hash table, not the full ELF section table.
12159
12160    The result is non-zero for success, or zero if an error was found.  */
12161
12162 static int
12163 locate_v1_virtual_dwo_sections (asection *sectp,
12164                                 struct virtual_v1_dwo_sections *sections)
12165 {
12166   const struct dwop_section_names *names = &dwop_section_names;
12167
12168   if (section_is_p (sectp->name, &names->abbrev_dwo))
12169     {
12170       /* There can be only one.  */
12171       if (sections->abbrev.s.section != NULL)
12172         return 0;
12173       sections->abbrev.s.section = sectp;
12174       sections->abbrev.size = bfd_get_section_size (sectp);
12175     }
12176   else if (section_is_p (sectp->name, &names->info_dwo)
12177            || section_is_p (sectp->name, &names->types_dwo))
12178     {
12179       /* There can be only one.  */
12180       if (sections->info_or_types.s.section != NULL)
12181         return 0;
12182       sections->info_or_types.s.section = sectp;
12183       sections->info_or_types.size = bfd_get_section_size (sectp);
12184     }
12185   else if (section_is_p (sectp->name, &names->line_dwo))
12186     {
12187       /* There can be only one.  */
12188       if (sections->line.s.section != NULL)
12189         return 0;
12190       sections->line.s.section = sectp;
12191       sections->line.size = bfd_get_section_size (sectp);
12192     }
12193   else if (section_is_p (sectp->name, &names->loc_dwo))
12194     {
12195       /* There can be only one.  */
12196       if (sections->loc.s.section != NULL)
12197         return 0;
12198       sections->loc.s.section = sectp;
12199       sections->loc.size = bfd_get_section_size (sectp);
12200     }
12201   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12202     {
12203       /* There can be only one.  */
12204       if (sections->macinfo.s.section != NULL)
12205         return 0;
12206       sections->macinfo.s.section = sectp;
12207       sections->macinfo.size = bfd_get_section_size (sectp);
12208     }
12209   else if (section_is_p (sectp->name, &names->macro_dwo))
12210     {
12211       /* There can be only one.  */
12212       if (sections->macro.s.section != NULL)
12213         return 0;
12214       sections->macro.s.section = sectp;
12215       sections->macro.size = bfd_get_section_size (sectp);
12216     }
12217   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12218     {
12219       /* There can be only one.  */
12220       if (sections->str_offsets.s.section != NULL)
12221         return 0;
12222       sections->str_offsets.s.section = sectp;
12223       sections->str_offsets.size = bfd_get_section_size (sectp);
12224     }
12225   else
12226     {
12227       /* No other kind of section is valid.  */
12228       return 0;
12229     }
12230
12231   return 1;
12232 }
12233
12234 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12235    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12236    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12237    This is for DWP version 1 files.  */
12238
12239 static struct dwo_unit *
12240 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12241                            struct dwp_file *dwp_file,
12242                            uint32_t unit_index,
12243                            const char *comp_dir,
12244                            ULONGEST signature, int is_debug_types)
12245 {
12246   struct objfile *objfile = dwarf2_per_objfile->objfile;
12247   const struct dwp_hash_table *dwp_htab =
12248     is_debug_types ? dwp_file->tus : dwp_file->cus;
12249   bfd *dbfd = dwp_file->dbfd.get ();
12250   const char *kind = is_debug_types ? "TU" : "CU";
12251   struct dwo_file *dwo_file;
12252   struct dwo_unit *dwo_unit;
12253   struct virtual_v1_dwo_sections sections;
12254   void **dwo_file_slot;
12255   int i;
12256
12257   gdb_assert (dwp_file->version == 1);
12258
12259   if (dwarf_read_debug)
12260     {
12261       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12262                           kind,
12263                           pulongest (unit_index), hex_string (signature),
12264                           dwp_file->name);
12265     }
12266
12267   /* Fetch the sections of this DWO unit.
12268      Put a limit on the number of sections we look for so that bad data
12269      doesn't cause us to loop forever.  */
12270
12271 #define MAX_NR_V1_DWO_SECTIONS \
12272   (1 /* .debug_info or .debug_types */ \
12273    + 1 /* .debug_abbrev */ \
12274    + 1 /* .debug_line */ \
12275    + 1 /* .debug_loc */ \
12276    + 1 /* .debug_str_offsets */ \
12277    + 1 /* .debug_macro or .debug_macinfo */ \
12278    + 1 /* trailing zero */)
12279
12280   memset (&sections, 0, sizeof (sections));
12281
12282   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12283     {
12284       asection *sectp;
12285       uint32_t section_nr =
12286         read_4_bytes (dbfd,
12287                       dwp_htab->section_pool.v1.indices
12288                       + (unit_index + i) * sizeof (uint32_t));
12289
12290       if (section_nr == 0)
12291         break;
12292       if (section_nr >= dwp_file->num_sections)
12293         {
12294           error (_("Dwarf Error: bad DWP hash table, section number too large"
12295                    " [in module %s]"),
12296                  dwp_file->name);
12297         }
12298
12299       sectp = dwp_file->elf_sections[section_nr];
12300       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12301         {
12302           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12303                    " [in module %s]"),
12304                  dwp_file->name);
12305         }
12306     }
12307
12308   if (i < 2
12309       || dwarf2_section_empty_p (&sections.info_or_types)
12310       || dwarf2_section_empty_p (&sections.abbrev))
12311     {
12312       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12313                " [in module %s]"),
12314              dwp_file->name);
12315     }
12316   if (i == MAX_NR_V1_DWO_SECTIONS)
12317     {
12318       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12319                " [in module %s]"),
12320              dwp_file->name);
12321     }
12322
12323   /* It's easier for the rest of the code if we fake a struct dwo_file and
12324      have dwo_unit "live" in that.  At least for now.
12325
12326      The DWP file can be made up of a random collection of CUs and TUs.
12327      However, for each CU + set of TUs that came from the same original DWO
12328      file, we can combine them back into a virtual DWO file to save space
12329      (fewer struct dwo_file objects to allocate).  Remember that for really
12330      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12331
12332   std::string virtual_dwo_name =
12333     string_printf ("virtual-dwo/%d-%d-%d-%d",
12334                    get_section_id (&sections.abbrev),
12335                    get_section_id (&sections.line),
12336                    get_section_id (&sections.loc),
12337                    get_section_id (&sections.str_offsets));
12338   /* Can we use an existing virtual DWO file?  */
12339   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12340                                         virtual_dwo_name.c_str (),
12341                                         comp_dir);
12342   /* Create one if necessary.  */
12343   if (*dwo_file_slot == NULL)
12344     {
12345       if (dwarf_read_debug)
12346         {
12347           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12348                               virtual_dwo_name.c_str ());
12349         }
12350       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12351       dwo_file->dwo_name
12352         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12353                                         virtual_dwo_name.c_str (),
12354                                         virtual_dwo_name.size ());
12355       dwo_file->comp_dir = comp_dir;
12356       dwo_file->sections.abbrev = sections.abbrev;
12357       dwo_file->sections.line = sections.line;
12358       dwo_file->sections.loc = sections.loc;
12359       dwo_file->sections.macinfo = sections.macinfo;
12360       dwo_file->sections.macro = sections.macro;
12361       dwo_file->sections.str_offsets = sections.str_offsets;
12362       /* The "str" section is global to the entire DWP file.  */
12363       dwo_file->sections.str = dwp_file->sections.str;
12364       /* The info or types section is assigned below to dwo_unit,
12365          there's no need to record it in dwo_file.
12366          Also, we can't simply record type sections in dwo_file because
12367          we record a pointer into the vector in dwo_unit.  As we collect more
12368          types we'll grow the vector and eventually have to reallocate space
12369          for it, invalidating all copies of pointers into the previous
12370          contents.  */
12371       *dwo_file_slot = dwo_file;
12372     }
12373   else
12374     {
12375       if (dwarf_read_debug)
12376         {
12377           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12378                               virtual_dwo_name.c_str ());
12379         }
12380       dwo_file = (struct dwo_file *) *dwo_file_slot;
12381     }
12382
12383   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12384   dwo_unit->dwo_file = dwo_file;
12385   dwo_unit->signature = signature;
12386   dwo_unit->section =
12387     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12388   *dwo_unit->section = sections.info_or_types;
12389   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12390
12391   return dwo_unit;
12392 }
12393
12394 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12395    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12396    piece within that section used by a TU/CU, return a virtual section
12397    of just that piece.  */
12398
12399 static struct dwarf2_section_info
12400 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12401                        struct dwarf2_section_info *section,
12402                        bfd_size_type offset, bfd_size_type size)
12403 {
12404   struct dwarf2_section_info result;
12405   asection *sectp;
12406
12407   gdb_assert (section != NULL);
12408   gdb_assert (!section->is_virtual);
12409
12410   memset (&result, 0, sizeof (result));
12411   result.s.containing_section = section;
12412   result.is_virtual = 1;
12413
12414   if (size == 0)
12415     return result;
12416
12417   sectp = get_section_bfd_section (section);
12418
12419   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12420      bounds of the real section.  This is a pretty-rare event, so just
12421      flag an error (easier) instead of a warning and trying to cope.  */
12422   if (sectp == NULL
12423       || offset + size > bfd_get_section_size (sectp))
12424     {
12425       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12426                " in section %s [in module %s]"),
12427              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12428              objfile_name (dwarf2_per_objfile->objfile));
12429     }
12430
12431   result.virtual_offset = offset;
12432   result.size = size;
12433   return result;
12434 }
12435
12436 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12437    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12438    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12439    This is for DWP version 2 files.  */
12440
12441 static struct dwo_unit *
12442 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12443                            struct dwp_file *dwp_file,
12444                            uint32_t unit_index,
12445                            const char *comp_dir,
12446                            ULONGEST signature, int is_debug_types)
12447 {
12448   struct objfile *objfile = dwarf2_per_objfile->objfile;
12449   const struct dwp_hash_table *dwp_htab =
12450     is_debug_types ? dwp_file->tus : dwp_file->cus;
12451   bfd *dbfd = dwp_file->dbfd.get ();
12452   const char *kind = is_debug_types ? "TU" : "CU";
12453   struct dwo_file *dwo_file;
12454   struct dwo_unit *dwo_unit;
12455   struct virtual_v2_dwo_sections sections;
12456   void **dwo_file_slot;
12457   int i;
12458
12459   gdb_assert (dwp_file->version == 2);
12460
12461   if (dwarf_read_debug)
12462     {
12463       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12464                           kind,
12465                           pulongest (unit_index), hex_string (signature),
12466                           dwp_file->name);
12467     }
12468
12469   /* Fetch the section offsets of this DWO unit.  */
12470
12471   memset (&sections, 0, sizeof (sections));
12472
12473   for (i = 0; i < dwp_htab->nr_columns; ++i)
12474     {
12475       uint32_t offset = read_4_bytes (dbfd,
12476                                       dwp_htab->section_pool.v2.offsets
12477                                       + (((unit_index - 1) * dwp_htab->nr_columns
12478                                           + i)
12479                                          * sizeof (uint32_t)));
12480       uint32_t size = read_4_bytes (dbfd,
12481                                     dwp_htab->section_pool.v2.sizes
12482                                     + (((unit_index - 1) * dwp_htab->nr_columns
12483                                         + i)
12484                                        * sizeof (uint32_t)));
12485
12486       switch (dwp_htab->section_pool.v2.section_ids[i])
12487         {
12488         case DW_SECT_INFO:
12489         case DW_SECT_TYPES:
12490           sections.info_or_types_offset = offset;
12491           sections.info_or_types_size = size;
12492           break;
12493         case DW_SECT_ABBREV:
12494           sections.abbrev_offset = offset;
12495           sections.abbrev_size = size;
12496           break;
12497         case DW_SECT_LINE:
12498           sections.line_offset = offset;
12499           sections.line_size = size;
12500           break;
12501         case DW_SECT_LOC:
12502           sections.loc_offset = offset;
12503           sections.loc_size = size;
12504           break;
12505         case DW_SECT_STR_OFFSETS:
12506           sections.str_offsets_offset = offset;
12507           sections.str_offsets_size = size;
12508           break;
12509         case DW_SECT_MACINFO:
12510           sections.macinfo_offset = offset;
12511           sections.macinfo_size = size;
12512           break;
12513         case DW_SECT_MACRO:
12514           sections.macro_offset = offset;
12515           sections.macro_size = size;
12516           break;
12517         }
12518     }
12519
12520   /* It's easier for the rest of the code if we fake a struct dwo_file and
12521      have dwo_unit "live" in that.  At least for now.
12522
12523      The DWP file can be made up of a random collection of CUs and TUs.
12524      However, for each CU + set of TUs that came from the same original DWO
12525      file, we can combine them back into a virtual DWO file to save space
12526      (fewer struct dwo_file objects to allocate).  Remember that for really
12527      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12528
12529   std::string virtual_dwo_name =
12530     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12531                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12532                    (long) (sections.line_size ? sections.line_offset : 0),
12533                    (long) (sections.loc_size ? sections.loc_offset : 0),
12534                    (long) (sections.str_offsets_size
12535                            ? sections.str_offsets_offset : 0));
12536   /* Can we use an existing virtual DWO file?  */
12537   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12538                                         virtual_dwo_name.c_str (),
12539                                         comp_dir);
12540   /* Create one if necessary.  */
12541   if (*dwo_file_slot == NULL)
12542     {
12543       if (dwarf_read_debug)
12544         {
12545           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12546                               virtual_dwo_name.c_str ());
12547         }
12548       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12549       dwo_file->dwo_name
12550         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12551                                         virtual_dwo_name.c_str (),
12552                                         virtual_dwo_name.size ());
12553       dwo_file->comp_dir = comp_dir;
12554       dwo_file->sections.abbrev =
12555         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12556                                sections.abbrev_offset, sections.abbrev_size);
12557       dwo_file->sections.line =
12558         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12559                                sections.line_offset, sections.line_size);
12560       dwo_file->sections.loc =
12561         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12562                                sections.loc_offset, sections.loc_size);
12563       dwo_file->sections.macinfo =
12564         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12565                                sections.macinfo_offset, sections.macinfo_size);
12566       dwo_file->sections.macro =
12567         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12568                                sections.macro_offset, sections.macro_size);
12569       dwo_file->sections.str_offsets =
12570         create_dwp_v2_section (dwarf2_per_objfile,
12571                                &dwp_file->sections.str_offsets,
12572                                sections.str_offsets_offset,
12573                                sections.str_offsets_size);
12574       /* The "str" section is global to the entire DWP file.  */
12575       dwo_file->sections.str = dwp_file->sections.str;
12576       /* The info or types section is assigned below to dwo_unit,
12577          there's no need to record it in dwo_file.
12578          Also, we can't simply record type sections in dwo_file because
12579          we record a pointer into the vector in dwo_unit.  As we collect more
12580          types we'll grow the vector and eventually have to reallocate space
12581          for it, invalidating all copies of pointers into the previous
12582          contents.  */
12583       *dwo_file_slot = dwo_file;
12584     }
12585   else
12586     {
12587       if (dwarf_read_debug)
12588         {
12589           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12590                               virtual_dwo_name.c_str ());
12591         }
12592       dwo_file = (struct dwo_file *) *dwo_file_slot;
12593     }
12594
12595   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12596   dwo_unit->dwo_file = dwo_file;
12597   dwo_unit->signature = signature;
12598   dwo_unit->section =
12599     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12600   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12601                                               is_debug_types
12602                                               ? &dwp_file->sections.types
12603                                               : &dwp_file->sections.info,
12604                                               sections.info_or_types_offset,
12605                                               sections.info_or_types_size);
12606   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12607
12608   return dwo_unit;
12609 }
12610
12611 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12612    Returns NULL if the signature isn't found.  */
12613
12614 static struct dwo_unit *
12615 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12616                         struct dwp_file *dwp_file, const char *comp_dir,
12617                         ULONGEST signature, int is_debug_types)
12618 {
12619   const struct dwp_hash_table *dwp_htab =
12620     is_debug_types ? dwp_file->tus : dwp_file->cus;
12621   bfd *dbfd = dwp_file->dbfd.get ();
12622   uint32_t mask = dwp_htab->nr_slots - 1;
12623   uint32_t hash = signature & mask;
12624   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12625   unsigned int i;
12626   void **slot;
12627   struct dwo_unit find_dwo_cu;
12628
12629   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12630   find_dwo_cu.signature = signature;
12631   slot = htab_find_slot (is_debug_types
12632                          ? dwp_file->loaded_tus
12633                          : dwp_file->loaded_cus,
12634                          &find_dwo_cu, INSERT);
12635
12636   if (*slot != NULL)
12637     return (struct dwo_unit *) *slot;
12638
12639   /* Use a for loop so that we don't loop forever on bad debug info.  */
12640   for (i = 0; i < dwp_htab->nr_slots; ++i)
12641     {
12642       ULONGEST signature_in_table;
12643
12644       signature_in_table =
12645         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12646       if (signature_in_table == signature)
12647         {
12648           uint32_t unit_index =
12649             read_4_bytes (dbfd,
12650                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12651
12652           if (dwp_file->version == 1)
12653             {
12654               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12655                                                  dwp_file, unit_index,
12656                                                  comp_dir, signature,
12657                                                  is_debug_types);
12658             }
12659           else
12660             {
12661               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12662                                                  dwp_file, unit_index,
12663                                                  comp_dir, signature,
12664                                                  is_debug_types);
12665             }
12666           return (struct dwo_unit *) *slot;
12667         }
12668       if (signature_in_table == 0)
12669         return NULL;
12670       hash = (hash + hash2) & mask;
12671     }
12672
12673   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12674            " [in module %s]"),
12675          dwp_file->name);
12676 }
12677
12678 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12679    Open the file specified by FILE_NAME and hand it off to BFD for
12680    preliminary analysis.  Return a newly initialized bfd *, which
12681    includes a canonicalized copy of FILE_NAME.
12682    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12683    SEARCH_CWD is true if the current directory is to be searched.
12684    It will be searched before debug-file-directory.
12685    If successful, the file is added to the bfd include table of the
12686    objfile's bfd (see gdb_bfd_record_inclusion).
12687    If unable to find/open the file, return NULL.
12688    NOTE: This function is derived from symfile_bfd_open.  */
12689
12690 static gdb_bfd_ref_ptr
12691 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12692                     const char *file_name, int is_dwp, int search_cwd)
12693 {
12694   int desc;
12695   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12696      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12697      to debug_file_directory.  */
12698   const char *search_path;
12699   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12700
12701   gdb::unique_xmalloc_ptr<char> search_path_holder;
12702   if (search_cwd)
12703     {
12704       if (*debug_file_directory != '\0')
12705         {
12706           search_path_holder.reset (concat (".", dirname_separator_string,
12707                                             debug_file_directory,
12708                                             (char *) NULL));
12709           search_path = search_path_holder.get ();
12710         }
12711       else
12712         search_path = ".";
12713     }
12714   else
12715     search_path = debug_file_directory;
12716
12717   openp_flags flags = OPF_RETURN_REALPATH;
12718   if (is_dwp)
12719     flags |= OPF_SEARCH_IN_PATH;
12720
12721   gdb::unique_xmalloc_ptr<char> absolute_name;
12722   desc = openp (search_path, flags, file_name,
12723                 O_RDONLY | O_BINARY, &absolute_name);
12724   if (desc < 0)
12725     return NULL;
12726
12727   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12728                                          gnutarget, desc));
12729   if (sym_bfd == NULL)
12730     return NULL;
12731   bfd_set_cacheable (sym_bfd.get (), 1);
12732
12733   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12734     return NULL;
12735
12736   /* Success.  Record the bfd as having been included by the objfile's bfd.
12737      This is important because things like demangled_names_hash lives in the
12738      objfile's per_bfd space and may have references to things like symbol
12739      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12740   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12741
12742   return sym_bfd;
12743 }
12744
12745 /* Try to open DWO file FILE_NAME.
12746    COMP_DIR is the DW_AT_comp_dir attribute.
12747    The result is the bfd handle of the file.
12748    If there is a problem finding or opening the file, return NULL.
12749    Upon success, the canonicalized path of the file is stored in the bfd,
12750    same as symfile_bfd_open.  */
12751
12752 static gdb_bfd_ref_ptr
12753 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12754                const char *file_name, const char *comp_dir)
12755 {
12756   if (IS_ABSOLUTE_PATH (file_name))
12757     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12758                                0 /*is_dwp*/, 0 /*search_cwd*/);
12759
12760   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12761
12762   if (comp_dir != NULL)
12763     {
12764       char *path_to_try = concat (comp_dir, SLASH_STRING,
12765                                   file_name, (char *) NULL);
12766
12767       /* NOTE: If comp_dir is a relative path, this will also try the
12768          search path, which seems useful.  */
12769       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12770                                                 path_to_try,
12771                                                 0 /*is_dwp*/,
12772                                                 1 /*search_cwd*/));
12773       xfree (path_to_try);
12774       if (abfd != NULL)
12775         return abfd;
12776     }
12777
12778   /* That didn't work, try debug-file-directory, which, despite its name,
12779      is a list of paths.  */
12780
12781   if (*debug_file_directory == '\0')
12782     return NULL;
12783
12784   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12785                              0 /*is_dwp*/, 1 /*search_cwd*/);
12786 }
12787
12788 /* This function is mapped across the sections and remembers the offset and
12789    size of each of the DWO debugging sections we are interested in.  */
12790
12791 static void
12792 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12793 {
12794   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12795   const struct dwop_section_names *names = &dwop_section_names;
12796
12797   if (section_is_p (sectp->name, &names->abbrev_dwo))
12798     {
12799       dwo_sections->abbrev.s.section = sectp;
12800       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12801     }
12802   else if (section_is_p (sectp->name, &names->info_dwo))
12803     {
12804       dwo_sections->info.s.section = sectp;
12805       dwo_sections->info.size = bfd_get_section_size (sectp);
12806     }
12807   else if (section_is_p (sectp->name, &names->line_dwo))
12808     {
12809       dwo_sections->line.s.section = sectp;
12810       dwo_sections->line.size = bfd_get_section_size (sectp);
12811     }
12812   else if (section_is_p (sectp->name, &names->loc_dwo))
12813     {
12814       dwo_sections->loc.s.section = sectp;
12815       dwo_sections->loc.size = bfd_get_section_size (sectp);
12816     }
12817   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12818     {
12819       dwo_sections->macinfo.s.section = sectp;
12820       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12821     }
12822   else if (section_is_p (sectp->name, &names->macro_dwo))
12823     {
12824       dwo_sections->macro.s.section = sectp;
12825       dwo_sections->macro.size = bfd_get_section_size (sectp);
12826     }
12827   else if (section_is_p (sectp->name, &names->str_dwo))
12828     {
12829       dwo_sections->str.s.section = sectp;
12830       dwo_sections->str.size = bfd_get_section_size (sectp);
12831     }
12832   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12833     {
12834       dwo_sections->str_offsets.s.section = sectp;
12835       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12836     }
12837   else if (section_is_p (sectp->name, &names->types_dwo))
12838     {
12839       struct dwarf2_section_info type_section;
12840
12841       memset (&type_section, 0, sizeof (type_section));
12842       type_section.s.section = sectp;
12843       type_section.size = bfd_get_section_size (sectp);
12844       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12845                      &type_section);
12846     }
12847 }
12848
12849 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12850    by PER_CU.  This is for the non-DWP case.
12851    The result is NULL if DWO_NAME can't be found.  */
12852
12853 static struct dwo_file *
12854 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12855                         const char *dwo_name, const char *comp_dir)
12856 {
12857   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12858   struct objfile *objfile = dwarf2_per_objfile->objfile;
12859
12860   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12861   if (dbfd == NULL)
12862     {
12863       if (dwarf_read_debug)
12864         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12865       return NULL;
12866     }
12867
12868   /* We use a unique pointer here, despite the obstack allocation,
12869      because a dwo_file needs some cleanup if it is abandoned.  */
12870   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12871                                         struct dwo_file));
12872   dwo_file->dwo_name = dwo_name;
12873   dwo_file->comp_dir = comp_dir;
12874   dwo_file->dbfd = dbfd.release ();
12875
12876   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12877                          &dwo_file->sections);
12878
12879   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12880                          dwo_file->cus);
12881
12882   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12883                                  dwo_file->sections.types, dwo_file->tus);
12884
12885   if (dwarf_read_debug)
12886     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12887
12888   return dwo_file.release ();
12889 }
12890
12891 /* This function is mapped across the sections and remembers the offset and
12892    size of each of the DWP debugging sections common to version 1 and 2 that
12893    we are interested in.  */
12894
12895 static void
12896 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12897                                    void *dwp_file_ptr)
12898 {
12899   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12900   const struct dwop_section_names *names = &dwop_section_names;
12901   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12902
12903   /* Record the ELF section number for later lookup: this is what the
12904      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12905   gdb_assert (elf_section_nr < dwp_file->num_sections);
12906   dwp_file->elf_sections[elf_section_nr] = sectp;
12907
12908   /* Look for specific sections that we need.  */
12909   if (section_is_p (sectp->name, &names->str_dwo))
12910     {
12911       dwp_file->sections.str.s.section = sectp;
12912       dwp_file->sections.str.size = bfd_get_section_size (sectp);
12913     }
12914   else if (section_is_p (sectp->name, &names->cu_index))
12915     {
12916       dwp_file->sections.cu_index.s.section = sectp;
12917       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
12918     }
12919   else if (section_is_p (sectp->name, &names->tu_index))
12920     {
12921       dwp_file->sections.tu_index.s.section = sectp;
12922       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
12923     }
12924 }
12925
12926 /* This function is mapped across the sections and remembers the offset and
12927    size of each of the DWP version 2 debugging sections that we are interested
12928    in.  This is split into a separate function because we don't know if we
12929    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12930
12931 static void
12932 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12933 {
12934   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12935   const struct dwop_section_names *names = &dwop_section_names;
12936   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12937
12938   /* Record the ELF section number for later lookup: this is what the
12939      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12940   gdb_assert (elf_section_nr < dwp_file->num_sections);
12941   dwp_file->elf_sections[elf_section_nr] = sectp;
12942
12943   /* Look for specific sections that we need.  */
12944   if (section_is_p (sectp->name, &names->abbrev_dwo))
12945     {
12946       dwp_file->sections.abbrev.s.section = sectp;
12947       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
12948     }
12949   else if (section_is_p (sectp->name, &names->info_dwo))
12950     {
12951       dwp_file->sections.info.s.section = sectp;
12952       dwp_file->sections.info.size = bfd_get_section_size (sectp);
12953     }
12954   else if (section_is_p (sectp->name, &names->line_dwo))
12955     {
12956       dwp_file->sections.line.s.section = sectp;
12957       dwp_file->sections.line.size = bfd_get_section_size (sectp);
12958     }
12959   else if (section_is_p (sectp->name, &names->loc_dwo))
12960     {
12961       dwp_file->sections.loc.s.section = sectp;
12962       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
12963     }
12964   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12965     {
12966       dwp_file->sections.macinfo.s.section = sectp;
12967       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
12968     }
12969   else if (section_is_p (sectp->name, &names->macro_dwo))
12970     {
12971       dwp_file->sections.macro.s.section = sectp;
12972       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
12973     }
12974   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12975     {
12976       dwp_file->sections.str_offsets.s.section = sectp;
12977       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
12978     }
12979   else if (section_is_p (sectp->name, &names->types_dwo))
12980     {
12981       dwp_file->sections.types.s.section = sectp;
12982       dwp_file->sections.types.size = bfd_get_section_size (sectp);
12983     }
12984 }
12985
12986 /* Hash function for dwp_file loaded CUs/TUs.  */
12987
12988 static hashval_t
12989 hash_dwp_loaded_cutus (const void *item)
12990 {
12991   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
12992
12993   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
12994   return dwo_unit->signature;
12995 }
12996
12997 /* Equality function for dwp_file loaded CUs/TUs.  */
12998
12999 static int
13000 eq_dwp_loaded_cutus (const void *a, const void *b)
13001 {
13002   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13003   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13004
13005   return dua->signature == dub->signature;
13006 }
13007
13008 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13009
13010 static htab_t
13011 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13012 {
13013   return htab_create_alloc_ex (3,
13014                                hash_dwp_loaded_cutus,
13015                                eq_dwp_loaded_cutus,
13016                                NULL,
13017                                &objfile->objfile_obstack,
13018                                hashtab_obstack_allocate,
13019                                dummy_obstack_deallocate);
13020 }
13021
13022 /* Try to open DWP file FILE_NAME.
13023    The result is the bfd handle of the file.
13024    If there is a problem finding or opening the file, return NULL.
13025    Upon success, the canonicalized path of the file is stored in the bfd,
13026    same as symfile_bfd_open.  */
13027
13028 static gdb_bfd_ref_ptr
13029 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13030                const char *file_name)
13031 {
13032   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13033                                             1 /*is_dwp*/,
13034                                             1 /*search_cwd*/));
13035   if (abfd != NULL)
13036     return abfd;
13037
13038   /* Work around upstream bug 15652.
13039      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13040      [Whether that's a "bug" is debatable, but it is getting in our way.]
13041      We have no real idea where the dwp file is, because gdb's realpath-ing
13042      of the executable's path may have discarded the needed info.
13043      [IWBN if the dwp file name was recorded in the executable, akin to
13044      .gnu_debuglink, but that doesn't exist yet.]
13045      Strip the directory from FILE_NAME and search again.  */
13046   if (*debug_file_directory != '\0')
13047     {
13048       /* Don't implicitly search the current directory here.
13049          If the user wants to search "." to handle this case,
13050          it must be added to debug-file-directory.  */
13051       return try_open_dwop_file (dwarf2_per_objfile,
13052                                  lbasename (file_name), 1 /*is_dwp*/,
13053                                  0 /*search_cwd*/);
13054     }
13055
13056   return NULL;
13057 }
13058
13059 /* Initialize the use of the DWP file for the current objfile.
13060    By convention the name of the DWP file is ${objfile}.dwp.
13061    The result is NULL if it can't be found.  */
13062
13063 static std::unique_ptr<struct dwp_file>
13064 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13065 {
13066   struct objfile *objfile = dwarf2_per_objfile->objfile;
13067
13068   /* Try to find first .dwp for the binary file before any symbolic links
13069      resolving.  */
13070
13071   /* If the objfile is a debug file, find the name of the real binary
13072      file and get the name of dwp file from there.  */
13073   std::string dwp_name;
13074   if (objfile->separate_debug_objfile_backlink != NULL)
13075     {
13076       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13077       const char *backlink_basename = lbasename (backlink->original_name);
13078
13079       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13080     }
13081   else
13082     dwp_name = objfile->original_name;
13083
13084   dwp_name += ".dwp";
13085
13086   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13087   if (dbfd == NULL
13088       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13089     {
13090       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13091       dwp_name = objfile_name (objfile);
13092       dwp_name += ".dwp";
13093       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13094     }
13095
13096   if (dbfd == NULL)
13097     {
13098       if (dwarf_read_debug)
13099         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13100       return std::unique_ptr<dwp_file> ();
13101     }
13102
13103   const char *name = bfd_get_filename (dbfd.get ());
13104   std::unique_ptr<struct dwp_file> dwp_file
13105     (new struct dwp_file (name, std::move (dbfd)));
13106
13107   /* +1: section 0 is unused */
13108   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13109   dwp_file->elf_sections =
13110     OBSTACK_CALLOC (&objfile->objfile_obstack,
13111                     dwp_file->num_sections, asection *);
13112
13113   bfd_map_over_sections (dwp_file->dbfd.get (),
13114                          dwarf2_locate_common_dwp_sections,
13115                          dwp_file.get ());
13116
13117   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13118                                          0);
13119
13120   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13121                                          1);
13122
13123   /* The DWP file version is stored in the hash table.  Oh well.  */
13124   if (dwp_file->cus && dwp_file->tus
13125       && dwp_file->cus->version != dwp_file->tus->version)
13126     {
13127       /* Technically speaking, we should try to limp along, but this is
13128          pretty bizarre.  We use pulongest here because that's the established
13129          portability solution (e.g, we cannot use %u for uint32_t).  */
13130       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13131                " TU version %s [in DWP file %s]"),
13132              pulongest (dwp_file->cus->version),
13133              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13134     }
13135
13136   if (dwp_file->cus)
13137     dwp_file->version = dwp_file->cus->version;
13138   else if (dwp_file->tus)
13139     dwp_file->version = dwp_file->tus->version;
13140   else
13141     dwp_file->version = 2;
13142
13143   if (dwp_file->version == 2)
13144     bfd_map_over_sections (dwp_file->dbfd.get (),
13145                            dwarf2_locate_v2_dwp_sections,
13146                            dwp_file.get ());
13147
13148   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13149   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13150
13151   if (dwarf_read_debug)
13152     {
13153       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13154       fprintf_unfiltered (gdb_stdlog,
13155                           "    %s CUs, %s TUs\n",
13156                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13157                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13158     }
13159
13160   return dwp_file;
13161 }
13162
13163 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13164
13165 static struct dwp_file *
13166 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13167 {
13168   if (! dwarf2_per_objfile->dwp_checked)
13169     {
13170       dwarf2_per_objfile->dwp_file
13171         = open_and_init_dwp_file (dwarf2_per_objfile);
13172       dwarf2_per_objfile->dwp_checked = 1;
13173     }
13174   return dwarf2_per_objfile->dwp_file.get ();
13175 }
13176
13177 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13178    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13179    or in the DWP file for the objfile, referenced by THIS_UNIT.
13180    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13181    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13182
13183    This is called, for example, when wanting to read a variable with a
13184    complex location.  Therefore we don't want to do file i/o for every call.
13185    Therefore we don't want to look for a DWO file on every call.
13186    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13187    then we check if we've already seen DWO_NAME, and only THEN do we check
13188    for a DWO file.
13189
13190    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13191    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13192
13193 static struct dwo_unit *
13194 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13195                  const char *dwo_name, const char *comp_dir,
13196                  ULONGEST signature, int is_debug_types)
13197 {
13198   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13199   struct objfile *objfile = dwarf2_per_objfile->objfile;
13200   const char *kind = is_debug_types ? "TU" : "CU";
13201   void **dwo_file_slot;
13202   struct dwo_file *dwo_file;
13203   struct dwp_file *dwp_file;
13204
13205   /* First see if there's a DWP file.
13206      If we have a DWP file but didn't find the DWO inside it, don't
13207      look for the original DWO file.  It makes gdb behave differently
13208      depending on whether one is debugging in the build tree.  */
13209
13210   dwp_file = get_dwp_file (dwarf2_per_objfile);
13211   if (dwp_file != NULL)
13212     {
13213       const struct dwp_hash_table *dwp_htab =
13214         is_debug_types ? dwp_file->tus : dwp_file->cus;
13215
13216       if (dwp_htab != NULL)
13217         {
13218           struct dwo_unit *dwo_cutu =
13219             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13220                                     signature, is_debug_types);
13221
13222           if (dwo_cutu != NULL)
13223             {
13224               if (dwarf_read_debug)
13225                 {
13226                   fprintf_unfiltered (gdb_stdlog,
13227                                       "Virtual DWO %s %s found: @%s\n",
13228                                       kind, hex_string (signature),
13229                                       host_address_to_string (dwo_cutu));
13230                 }
13231               return dwo_cutu;
13232             }
13233         }
13234     }
13235   else
13236     {
13237       /* No DWP file, look for the DWO file.  */
13238
13239       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13240                                             dwo_name, comp_dir);
13241       if (*dwo_file_slot == NULL)
13242         {
13243           /* Read in the file and build a table of the CUs/TUs it contains.  */
13244           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13245         }
13246       /* NOTE: This will be NULL if unable to open the file.  */
13247       dwo_file = (struct dwo_file *) *dwo_file_slot;
13248
13249       if (dwo_file != NULL)
13250         {
13251           struct dwo_unit *dwo_cutu = NULL;
13252
13253           if (is_debug_types && dwo_file->tus)
13254             {
13255               struct dwo_unit find_dwo_cutu;
13256
13257               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13258               find_dwo_cutu.signature = signature;
13259               dwo_cutu
13260                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13261             }
13262           else if (!is_debug_types && dwo_file->cus)
13263             {
13264               struct dwo_unit find_dwo_cutu;
13265
13266               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13267               find_dwo_cutu.signature = signature;
13268               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13269                                                        &find_dwo_cutu);
13270             }
13271
13272           if (dwo_cutu != NULL)
13273             {
13274               if (dwarf_read_debug)
13275                 {
13276                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13277                                       kind, dwo_name, hex_string (signature),
13278                                       host_address_to_string (dwo_cutu));
13279                 }
13280               return dwo_cutu;
13281             }
13282         }
13283     }
13284
13285   /* We didn't find it.  This could mean a dwo_id mismatch, or
13286      someone deleted the DWO/DWP file, or the search path isn't set up
13287      correctly to find the file.  */
13288
13289   if (dwarf_read_debug)
13290     {
13291       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13292                           kind, dwo_name, hex_string (signature));
13293     }
13294
13295   /* This is a warning and not a complaint because it can be caused by
13296      pilot error (e.g., user accidentally deleting the DWO).  */
13297   {
13298     /* Print the name of the DWP file if we looked there, helps the user
13299        better diagnose the problem.  */
13300     std::string dwp_text;
13301
13302     if (dwp_file != NULL)
13303       dwp_text = string_printf (" [in DWP file %s]",
13304                                 lbasename (dwp_file->name));
13305
13306     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13307                " [in module %s]"),
13308              kind, dwo_name, hex_string (signature),
13309              dwp_text.c_str (),
13310              this_unit->is_debug_types ? "TU" : "CU",
13311              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13312   }
13313   return NULL;
13314 }
13315
13316 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13317    See lookup_dwo_cutu_unit for details.  */
13318
13319 static struct dwo_unit *
13320 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13321                       const char *dwo_name, const char *comp_dir,
13322                       ULONGEST signature)
13323 {
13324   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13325 }
13326
13327 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13328    See lookup_dwo_cutu_unit for details.  */
13329
13330 static struct dwo_unit *
13331 lookup_dwo_type_unit (struct signatured_type *this_tu,
13332                       const char *dwo_name, const char *comp_dir)
13333 {
13334   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13335 }
13336
13337 /* Traversal function for queue_and_load_all_dwo_tus.  */
13338
13339 static int
13340 queue_and_load_dwo_tu (void **slot, void *info)
13341 {
13342   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13343   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13344   ULONGEST signature = dwo_unit->signature;
13345   struct signatured_type *sig_type =
13346     lookup_dwo_signatured_type (per_cu->cu, signature);
13347
13348   if (sig_type != NULL)
13349     {
13350       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13351
13352       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13353          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13354          while processing PER_CU.  */
13355       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13356         load_full_type_unit (sig_cu);
13357       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13358     }
13359
13360   return 1;
13361 }
13362
13363 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13364    The DWO may have the only definition of the type, though it may not be
13365    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13366    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13367
13368 static void
13369 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13370 {
13371   struct dwo_unit *dwo_unit;
13372   struct dwo_file *dwo_file;
13373
13374   gdb_assert (!per_cu->is_debug_types);
13375   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13376   gdb_assert (per_cu->cu != NULL);
13377
13378   dwo_unit = per_cu->cu->dwo_unit;
13379   gdb_assert (dwo_unit != NULL);
13380
13381   dwo_file = dwo_unit->dwo_file;
13382   if (dwo_file->tus != NULL)
13383     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13384 }
13385
13386 /* Free all resources associated with DWO_FILE.
13387    Close the DWO file and munmap the sections.  */
13388
13389 static void
13390 free_dwo_file (struct dwo_file *dwo_file)
13391 {
13392   /* Note: dbfd is NULL for virtual DWO files.  */
13393   gdb_bfd_unref (dwo_file->dbfd);
13394
13395   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13396 }
13397
13398 /* Traversal function for free_dwo_files.  */
13399
13400 static int
13401 free_dwo_file_from_slot (void **slot, void *info)
13402 {
13403   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13404
13405   free_dwo_file (dwo_file);
13406
13407   return 1;
13408 }
13409
13410 /* Free all resources associated with DWO_FILES.  */
13411
13412 static void
13413 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13414 {
13415   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13416 }
13417 \f
13418 /* Read in various DIEs.  */
13419
13420 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13421    Inherit only the children of the DW_AT_abstract_origin DIE not being
13422    already referenced by DW_AT_abstract_origin from the children of the
13423    current DIE.  */
13424
13425 static void
13426 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13427 {
13428   struct die_info *child_die;
13429   sect_offset *offsetp;
13430   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13431   struct die_info *origin_die;
13432   /* Iterator of the ORIGIN_DIE children.  */
13433   struct die_info *origin_child_die;
13434   struct attribute *attr;
13435   struct dwarf2_cu *origin_cu;
13436   struct pending **origin_previous_list_in_scope;
13437
13438   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13439   if (!attr)
13440     return;
13441
13442   /* Note that following die references may follow to a die in a
13443      different cu.  */
13444
13445   origin_cu = cu;
13446   origin_die = follow_die_ref (die, attr, &origin_cu);
13447
13448   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13449      symbols in.  */
13450   origin_previous_list_in_scope = origin_cu->list_in_scope;
13451   origin_cu->list_in_scope = cu->list_in_scope;
13452
13453   if (die->tag != origin_die->tag
13454       && !(die->tag == DW_TAG_inlined_subroutine
13455            && origin_die->tag == DW_TAG_subprogram))
13456     complaint (_("DIE %s and its abstract origin %s have different tags"),
13457                sect_offset_str (die->sect_off),
13458                sect_offset_str (origin_die->sect_off));
13459
13460   std::vector<sect_offset> offsets;
13461
13462   for (child_die = die->child;
13463        child_die && child_die->tag;
13464        child_die = sibling_die (child_die))
13465     {
13466       struct die_info *child_origin_die;
13467       struct dwarf2_cu *child_origin_cu;
13468
13469       /* We are trying to process concrete instance entries:
13470          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13471          it's not relevant to our analysis here. i.e. detecting DIEs that are
13472          present in the abstract instance but not referenced in the concrete
13473          one.  */
13474       if (child_die->tag == DW_TAG_call_site
13475           || child_die->tag == DW_TAG_GNU_call_site)
13476         continue;
13477
13478       /* For each CHILD_DIE, find the corresponding child of
13479          ORIGIN_DIE.  If there is more than one layer of
13480          DW_AT_abstract_origin, follow them all; there shouldn't be,
13481          but GCC versions at least through 4.4 generate this (GCC PR
13482          40573).  */
13483       child_origin_die = child_die;
13484       child_origin_cu = cu;
13485       while (1)
13486         {
13487           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13488                               child_origin_cu);
13489           if (attr == NULL)
13490             break;
13491           child_origin_die = follow_die_ref (child_origin_die, attr,
13492                                              &child_origin_cu);
13493         }
13494
13495       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13496          counterpart may exist.  */
13497       if (child_origin_die != child_die)
13498         {
13499           if (child_die->tag != child_origin_die->tag
13500               && !(child_die->tag == DW_TAG_inlined_subroutine
13501                    && child_origin_die->tag == DW_TAG_subprogram))
13502             complaint (_("Child DIE %s and its abstract origin %s have "
13503                          "different tags"),
13504                        sect_offset_str (child_die->sect_off),
13505                        sect_offset_str (child_origin_die->sect_off));
13506           if (child_origin_die->parent != origin_die)
13507             complaint (_("Child DIE %s and its abstract origin %s have "
13508                          "different parents"),
13509                        sect_offset_str (child_die->sect_off),
13510                        sect_offset_str (child_origin_die->sect_off));
13511           else
13512             offsets.push_back (child_origin_die->sect_off);
13513         }
13514     }
13515   std::sort (offsets.begin (), offsets.end ());
13516   sect_offset *offsets_end = offsets.data () + offsets.size ();
13517   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13518     if (offsetp[-1] == *offsetp)
13519       complaint (_("Multiple children of DIE %s refer "
13520                    "to DIE %s as their abstract origin"),
13521                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13522
13523   offsetp = offsets.data ();
13524   origin_child_die = origin_die->child;
13525   while (origin_child_die && origin_child_die->tag)
13526     {
13527       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13528       while (offsetp < offsets_end
13529              && *offsetp < origin_child_die->sect_off)
13530         offsetp++;
13531       if (offsetp >= offsets_end
13532           || *offsetp > origin_child_die->sect_off)
13533         {
13534           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13535              Check whether we're already processing ORIGIN_CHILD_DIE.
13536              This can happen with mutually referenced abstract_origins.
13537              PR 16581.  */
13538           if (!origin_child_die->in_process)
13539             process_die (origin_child_die, origin_cu);
13540         }
13541       origin_child_die = sibling_die (origin_child_die);
13542     }
13543   origin_cu->list_in_scope = origin_previous_list_in_scope;
13544 }
13545
13546 static void
13547 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13548 {
13549   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13550   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13551   struct context_stack *newobj;
13552   CORE_ADDR lowpc;
13553   CORE_ADDR highpc;
13554   struct die_info *child_die;
13555   struct attribute *attr, *call_line, *call_file;
13556   const char *name;
13557   CORE_ADDR baseaddr;
13558   struct block *block;
13559   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13560   std::vector<struct symbol *> template_args;
13561   struct template_symbol *templ_func = NULL;
13562
13563   if (inlined_func)
13564     {
13565       /* If we do not have call site information, we can't show the
13566          caller of this inlined function.  That's too confusing, so
13567          only use the scope for local variables.  */
13568       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13569       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13570       if (call_line == NULL || call_file == NULL)
13571         {
13572           read_lexical_block_scope (die, cu);
13573           return;
13574         }
13575     }
13576
13577   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13578
13579   name = dwarf2_name (die, cu);
13580
13581   /* Ignore functions with missing or empty names.  These are actually
13582      illegal according to the DWARF standard.  */
13583   if (name == NULL)
13584     {
13585       complaint (_("missing name for subprogram DIE at %s"),
13586                  sect_offset_str (die->sect_off));
13587       return;
13588     }
13589
13590   /* Ignore functions with missing or invalid low and high pc attributes.  */
13591   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13592       <= PC_BOUNDS_INVALID)
13593     {
13594       attr = dwarf2_attr (die, DW_AT_external, cu);
13595       if (!attr || !DW_UNSND (attr))
13596         complaint (_("cannot get low and high bounds "
13597                      "for subprogram DIE at %s"),
13598                    sect_offset_str (die->sect_off));
13599       return;
13600     }
13601
13602   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13603   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13604
13605   /* If we have any template arguments, then we must allocate a
13606      different sort of symbol.  */
13607   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13608     {
13609       if (child_die->tag == DW_TAG_template_type_param
13610           || child_die->tag == DW_TAG_template_value_param)
13611         {
13612           templ_func = allocate_template_symbol (objfile);
13613           templ_func->subclass = SYMBOL_TEMPLATE;
13614           break;
13615         }
13616     }
13617
13618   newobj = push_context (0, lowpc);
13619   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13620                              (struct symbol *) templ_func);
13621
13622   /* If there is a location expression for DW_AT_frame_base, record
13623      it.  */
13624   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13625   if (attr)
13626     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13627
13628   /* If there is a location for the static link, record it.  */
13629   newobj->static_link = NULL;
13630   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13631   if (attr)
13632     {
13633       newobj->static_link
13634         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13635       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13636     }
13637
13638   cu->list_in_scope = &local_symbols;
13639
13640   if (die->child != NULL)
13641     {
13642       child_die = die->child;
13643       while (child_die && child_die->tag)
13644         {
13645           if (child_die->tag == DW_TAG_template_type_param
13646               || child_die->tag == DW_TAG_template_value_param)
13647             {
13648               struct symbol *arg = new_symbol (child_die, NULL, cu);
13649
13650               if (arg != NULL)
13651                 template_args.push_back (arg);
13652             }
13653           else
13654             process_die (child_die, cu);
13655           child_die = sibling_die (child_die);
13656         }
13657     }
13658
13659   inherit_abstract_dies (die, cu);
13660
13661   /* If we have a DW_AT_specification, we might need to import using
13662      directives from the context of the specification DIE.  See the
13663      comment in determine_prefix.  */
13664   if (cu->language == language_cplus
13665       && dwarf2_attr (die, DW_AT_specification, cu))
13666     {
13667       struct dwarf2_cu *spec_cu = cu;
13668       struct die_info *spec_die = die_specification (die, &spec_cu);
13669
13670       while (spec_die)
13671         {
13672           child_die = spec_die->child;
13673           while (child_die && child_die->tag)
13674             {
13675               if (child_die->tag == DW_TAG_imported_module)
13676                 process_die (child_die, spec_cu);
13677               child_die = sibling_die (child_die);
13678             }
13679
13680           /* In some cases, GCC generates specification DIEs that
13681              themselves contain DW_AT_specification attributes.  */
13682           spec_die = die_specification (spec_die, &spec_cu);
13683         }
13684     }
13685
13686   newobj = pop_context ();
13687   /* Make a block for the local symbols within.  */
13688   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
13689                         newobj->static_link, lowpc, highpc);
13690
13691   /* For C++, set the block's scope.  */
13692   if ((cu->language == language_cplus
13693        || cu->language == language_fortran
13694        || cu->language == language_d
13695        || cu->language == language_rust)
13696       && cu->processing_has_namespace_info)
13697     block_set_scope (block, determine_prefix (die, cu),
13698                      &objfile->objfile_obstack);
13699
13700   /* If we have address ranges, record them.  */
13701   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13702
13703   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
13704
13705   /* Attach template arguments to function.  */
13706   if (!template_args.empty ())
13707     {
13708       gdb_assert (templ_func != NULL);
13709
13710       templ_func->n_template_arguments = template_args.size ();
13711       templ_func->template_arguments
13712         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13713                      templ_func->n_template_arguments);
13714       memcpy (templ_func->template_arguments,
13715               template_args.data (),
13716               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13717     }
13718
13719   /* In C++, we can have functions nested inside functions (e.g., when
13720      a function declares a class that has methods).  This means that
13721      when we finish processing a function scope, we may need to go
13722      back to building a containing block's symbol lists.  */
13723   local_symbols = newobj->locals;
13724   local_using_directives = newobj->local_using_directives;
13725
13726   /* If we've finished processing a top-level function, subsequent
13727      symbols go in the file symbol list.  */
13728   if (outermost_context_p ())
13729     cu->list_in_scope = &file_symbols;
13730 }
13731
13732 /* Process all the DIES contained within a lexical block scope.  Start
13733    a new scope, process the dies, and then close the scope.  */
13734
13735 static void
13736 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13737 {
13738   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13739   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13740   struct context_stack *newobj;
13741   CORE_ADDR lowpc, highpc;
13742   struct die_info *child_die;
13743   CORE_ADDR baseaddr;
13744
13745   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13746
13747   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13748   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13749      as multiple lexical blocks?  Handling children in a sane way would
13750      be nasty.  Might be easier to properly extend generic blocks to
13751      describe ranges.  */
13752   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13753     {
13754     case PC_BOUNDS_NOT_PRESENT:
13755       /* DW_TAG_lexical_block has no attributes, process its children as if
13756          there was no wrapping by that DW_TAG_lexical_block.
13757          GCC does no longer produces such DWARF since GCC r224161.  */
13758       for (child_die = die->child;
13759            child_die != NULL && child_die->tag;
13760            child_die = sibling_die (child_die))
13761         process_die (child_die, cu);
13762       return;
13763     case PC_BOUNDS_INVALID:
13764       return;
13765     }
13766   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13767   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13768
13769   push_context (0, lowpc);
13770   if (die->child != NULL)
13771     {
13772       child_die = die->child;
13773       while (child_die && child_die->tag)
13774         {
13775           process_die (child_die, cu);
13776           child_die = sibling_die (child_die);
13777         }
13778     }
13779   inherit_abstract_dies (die, cu);
13780   newobj = pop_context ();
13781
13782   if (local_symbols != NULL || local_using_directives != NULL)
13783     {
13784       struct block *block
13785         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
13786                         newobj->start_addr, highpc);
13787
13788       /* Note that recording ranges after traversing children, as we
13789          do here, means that recording a parent's ranges entails
13790          walking across all its children's ranges as they appear in
13791          the address map, which is quadratic behavior.
13792
13793          It would be nicer to record the parent's ranges before
13794          traversing its children, simply overriding whatever you find
13795          there.  But since we don't even decide whether to create a
13796          block until after we've traversed its children, that's hard
13797          to do.  */
13798       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13799     }
13800   local_symbols = newobj->locals;
13801   local_using_directives = newobj->local_using_directives;
13802 }
13803
13804 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13805
13806 static void
13807 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13808 {
13809   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13810   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13811   CORE_ADDR pc, baseaddr;
13812   struct attribute *attr;
13813   struct call_site *call_site, call_site_local;
13814   void **slot;
13815   int nparams;
13816   struct die_info *child_die;
13817
13818   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13819
13820   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13821   if (attr == NULL)
13822     {
13823       /* This was a pre-DWARF-5 GNU extension alias
13824          for DW_AT_call_return_pc.  */
13825       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13826     }
13827   if (!attr)
13828     {
13829       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13830                    "DIE %s [in module %s]"),
13831                  sect_offset_str (die->sect_off), objfile_name (objfile));
13832       return;
13833     }
13834   pc = attr_value_as_address (attr) + baseaddr;
13835   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13836
13837   if (cu->call_site_htab == NULL)
13838     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13839                                                NULL, &objfile->objfile_obstack,
13840                                                hashtab_obstack_allocate, NULL);
13841   call_site_local.pc = pc;
13842   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13843   if (*slot != NULL)
13844     {
13845       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13846                    "DIE %s [in module %s]"),
13847                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13848                  objfile_name (objfile));
13849       return;
13850     }
13851
13852   /* Count parameters at the caller.  */
13853
13854   nparams = 0;
13855   for (child_die = die->child; child_die && child_die->tag;
13856        child_die = sibling_die (child_die))
13857     {
13858       if (child_die->tag != DW_TAG_call_site_parameter
13859           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13860         {
13861           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13862                        "DW_TAG_call_site child DIE %s [in module %s]"),
13863                      child_die->tag, sect_offset_str (child_die->sect_off),
13864                      objfile_name (objfile));
13865           continue;
13866         }
13867
13868       nparams++;
13869     }
13870
13871   call_site
13872     = ((struct call_site *)
13873        obstack_alloc (&objfile->objfile_obstack,
13874                       sizeof (*call_site)
13875                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13876   *slot = call_site;
13877   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13878   call_site->pc = pc;
13879
13880   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13881       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13882     {
13883       struct die_info *func_die;
13884
13885       /* Skip also over DW_TAG_inlined_subroutine.  */
13886       for (func_die = die->parent;
13887            func_die && func_die->tag != DW_TAG_subprogram
13888            && func_die->tag != DW_TAG_subroutine_type;
13889            func_die = func_die->parent);
13890
13891       /* DW_AT_call_all_calls is a superset
13892          of DW_AT_call_all_tail_calls.  */
13893       if (func_die
13894           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13895           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13896           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13897           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13898         {
13899           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13900              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13901              both the initial caller containing the real return address PC and
13902              the final callee containing the current PC of a chain of tail
13903              calls do not need to have the tail call list complete.  But any
13904              function candidate for a virtual tail call frame searched via
13905              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13906              determined unambiguously.  */
13907         }
13908       else
13909         {
13910           struct type *func_type = NULL;
13911
13912           if (func_die)
13913             func_type = get_die_type (func_die, cu);
13914           if (func_type != NULL)
13915             {
13916               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13917
13918               /* Enlist this call site to the function.  */
13919               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13920               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13921             }
13922           else
13923             complaint (_("Cannot find function owning DW_TAG_call_site "
13924                          "DIE %s [in module %s]"),
13925                        sect_offset_str (die->sect_off), objfile_name (objfile));
13926         }
13927     }
13928
13929   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13930   if (attr == NULL)
13931     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13932   if (attr == NULL)
13933     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13934   if (attr == NULL)
13935     {
13936       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13937       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13938     }
13939   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13940   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
13941     /* Keep NULL DWARF_BLOCK.  */;
13942   else if (attr_form_is_block (attr))
13943     {
13944       struct dwarf2_locexpr_baton *dlbaton;
13945
13946       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13947       dlbaton->data = DW_BLOCK (attr)->data;
13948       dlbaton->size = DW_BLOCK (attr)->size;
13949       dlbaton->per_cu = cu->per_cu;
13950
13951       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13952     }
13953   else if (attr_form_is_ref (attr))
13954     {
13955       struct dwarf2_cu *target_cu = cu;
13956       struct die_info *target_die;
13957
13958       target_die = follow_die_ref (die, attr, &target_cu);
13959       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
13960       if (die_is_declaration (target_die, target_cu))
13961         {
13962           const char *target_physname;
13963
13964           /* Prefer the mangled name; otherwise compute the demangled one.  */
13965           target_physname = dw2_linkage_name (target_die, target_cu);
13966           if (target_physname == NULL)
13967             target_physname = dwarf2_physname (NULL, target_die, target_cu);
13968           if (target_physname == NULL)
13969             complaint (_("DW_AT_call_target target DIE has invalid "
13970                          "physname, for referencing DIE %s [in module %s]"),
13971                        sect_offset_str (die->sect_off), objfile_name (objfile));
13972           else
13973             SET_FIELD_PHYSNAME (call_site->target, target_physname);
13974         }
13975       else
13976         {
13977           CORE_ADDR lowpc;
13978
13979           /* DW_AT_entry_pc should be preferred.  */
13980           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
13981               <= PC_BOUNDS_INVALID)
13982             complaint (_("DW_AT_call_target target DIE has invalid "
13983                          "low pc, for referencing DIE %s [in module %s]"),
13984                        sect_offset_str (die->sect_off), objfile_name (objfile));
13985           else
13986             {
13987               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13988               SET_FIELD_PHYSADDR (call_site->target, lowpc);
13989             }
13990         }
13991     }
13992   else
13993     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
13994                  "block nor reference, for DIE %s [in module %s]"),
13995                sect_offset_str (die->sect_off), objfile_name (objfile));
13996
13997   call_site->per_cu = cu->per_cu;
13998
13999   for (child_die = die->child;
14000        child_die && child_die->tag;
14001        child_die = sibling_die (child_die))
14002     {
14003       struct call_site_parameter *parameter;
14004       struct attribute *loc, *origin;
14005
14006       if (child_die->tag != DW_TAG_call_site_parameter
14007           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14008         {
14009           /* Already printed the complaint above.  */
14010           continue;
14011         }
14012
14013       gdb_assert (call_site->parameter_count < nparams);
14014       parameter = &call_site->parameter[call_site->parameter_count];
14015
14016       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14017          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14018          register is contained in DW_AT_call_value.  */
14019
14020       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14021       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14022       if (origin == NULL)
14023         {
14024           /* This was a pre-DWARF-5 GNU extension alias
14025              for DW_AT_call_parameter.  */
14026           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14027         }
14028       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14029         {
14030           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14031
14032           sect_offset sect_off
14033             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14034           if (!offset_in_cu_p (&cu->header, sect_off))
14035             {
14036               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14037                  binding can be done only inside one CU.  Such referenced DIE
14038                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14039               complaint (_("DW_AT_call_parameter offset is not in CU for "
14040                            "DW_TAG_call_site child DIE %s [in module %s]"),
14041                          sect_offset_str (child_die->sect_off),
14042                          objfile_name (objfile));
14043               continue;
14044             }
14045           parameter->u.param_cu_off
14046             = (cu_offset) (sect_off - cu->header.sect_off);
14047         }
14048       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14049         {
14050           complaint (_("No DW_FORM_block* DW_AT_location for "
14051                        "DW_TAG_call_site child DIE %s [in module %s]"),
14052                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14053           continue;
14054         }
14055       else
14056         {
14057           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14058             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14059           if (parameter->u.dwarf_reg != -1)
14060             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14061           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14062                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14063                                              &parameter->u.fb_offset))
14064             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14065           else
14066             {
14067               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14068                            "for DW_FORM_block* DW_AT_location is supported for "
14069                            "DW_TAG_call_site child DIE %s "
14070                            "[in module %s]"),
14071                          sect_offset_str (child_die->sect_off),
14072                          objfile_name (objfile));
14073               continue;
14074             }
14075         }
14076
14077       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14078       if (attr == NULL)
14079         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14080       if (!attr_form_is_block (attr))
14081         {
14082           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14083                        "DW_TAG_call_site child DIE %s [in module %s]"),
14084                      sect_offset_str (child_die->sect_off),
14085                      objfile_name (objfile));
14086           continue;
14087         }
14088       parameter->value = DW_BLOCK (attr)->data;
14089       parameter->value_size = DW_BLOCK (attr)->size;
14090
14091       /* Parameters are not pre-cleared by memset above.  */
14092       parameter->data_value = NULL;
14093       parameter->data_value_size = 0;
14094       call_site->parameter_count++;
14095
14096       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14097       if (attr == NULL)
14098         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14099       if (attr)
14100         {
14101           if (!attr_form_is_block (attr))
14102             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14103                          "DW_TAG_call_site child DIE %s [in module %s]"),
14104                        sect_offset_str (child_die->sect_off),
14105                        objfile_name (objfile));
14106           else
14107             {
14108               parameter->data_value = DW_BLOCK (attr)->data;
14109               parameter->data_value_size = DW_BLOCK (attr)->size;
14110             }
14111         }
14112     }
14113 }
14114
14115 /* Helper function for read_variable.  If DIE represents a virtual
14116    table, then return the type of the concrete object that is
14117    associated with the virtual table.  Otherwise, return NULL.  */
14118
14119 static struct type *
14120 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14121 {
14122   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14123   if (attr == NULL)
14124     return NULL;
14125
14126   /* Find the type DIE.  */
14127   struct die_info *type_die = NULL;
14128   struct dwarf2_cu *type_cu = cu;
14129
14130   if (attr_form_is_ref (attr))
14131     type_die = follow_die_ref (die, attr, &type_cu);
14132   if (type_die == NULL)
14133     return NULL;
14134
14135   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14136     return NULL;
14137   return die_containing_type (type_die, type_cu);
14138 }
14139
14140 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14141
14142 static void
14143 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14144 {
14145   struct rust_vtable_symbol *storage = NULL;
14146
14147   if (cu->language == language_rust)
14148     {
14149       struct type *containing_type = rust_containing_type (die, cu);
14150
14151       if (containing_type != NULL)
14152         {
14153           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14154
14155           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14156                                     struct rust_vtable_symbol);
14157           initialize_objfile_symbol (storage);
14158           storage->concrete_type = containing_type;
14159           storage->subclass = SYMBOL_RUST_VTABLE;
14160         }
14161     }
14162
14163   new_symbol (die, NULL, cu, storage);
14164 }
14165
14166 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14167    reading .debug_rnglists.
14168    Callback's type should be:
14169     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14170    Return true if the attributes are present and valid, otherwise,
14171    return false.  */
14172
14173 template <typename Callback>
14174 static bool
14175 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14176                          Callback &&callback)
14177 {
14178   struct dwarf2_per_objfile *dwarf2_per_objfile
14179     = cu->per_cu->dwarf2_per_objfile;
14180   struct objfile *objfile = dwarf2_per_objfile->objfile;
14181   bfd *obfd = objfile->obfd;
14182   /* Base address selection entry.  */
14183   CORE_ADDR base;
14184   int found_base;
14185   const gdb_byte *buffer;
14186   CORE_ADDR baseaddr;
14187   bool overflow = false;
14188
14189   found_base = cu->base_known;
14190   base = cu->base_address;
14191
14192   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14193   if (offset >= dwarf2_per_objfile->rnglists.size)
14194     {
14195       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14196                  offset);
14197       return false;
14198     }
14199   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14200
14201   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14202
14203   while (1)
14204     {
14205       /* Initialize it due to a false compiler warning.  */
14206       CORE_ADDR range_beginning = 0, range_end = 0;
14207       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14208                                  + dwarf2_per_objfile->rnglists.size);
14209       unsigned int bytes_read;
14210
14211       if (buffer == buf_end)
14212         {
14213           overflow = true;
14214           break;
14215         }
14216       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14217       switch (rlet)
14218         {
14219         case DW_RLE_end_of_list:
14220           break;
14221         case DW_RLE_base_address:
14222           if (buffer + cu->header.addr_size > buf_end)
14223             {
14224               overflow = true;
14225               break;
14226             }
14227           base = read_address (obfd, buffer, cu, &bytes_read);
14228           found_base = 1;
14229           buffer += bytes_read;
14230           break;
14231         case DW_RLE_start_length:
14232           if (buffer + cu->header.addr_size > buf_end)
14233             {
14234               overflow = true;
14235               break;
14236             }
14237           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14238           buffer += bytes_read;
14239           range_end = (range_beginning
14240                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14241           buffer += bytes_read;
14242           if (buffer > buf_end)
14243             {
14244               overflow = true;
14245               break;
14246             }
14247           break;
14248         case DW_RLE_offset_pair:
14249           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14250           buffer += bytes_read;
14251           if (buffer > buf_end)
14252             {
14253               overflow = true;
14254               break;
14255             }
14256           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14257           buffer += bytes_read;
14258           if (buffer > buf_end)
14259             {
14260               overflow = true;
14261               break;
14262             }
14263           break;
14264         case DW_RLE_start_end:
14265           if (buffer + 2 * cu->header.addr_size > buf_end)
14266             {
14267               overflow = true;
14268               break;
14269             }
14270           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14271           buffer += bytes_read;
14272           range_end = read_address (obfd, buffer, cu, &bytes_read);
14273           buffer += bytes_read;
14274           break;
14275         default:
14276           complaint (_("Invalid .debug_rnglists data (no base address)"));
14277           return false;
14278         }
14279       if (rlet == DW_RLE_end_of_list || overflow)
14280         break;
14281       if (rlet == DW_RLE_base_address)
14282         continue;
14283
14284       if (!found_base)
14285         {
14286           /* We have no valid base address for the ranges
14287              data.  */
14288           complaint (_("Invalid .debug_rnglists data (no base address)"));
14289           return false;
14290         }
14291
14292       if (range_beginning > range_end)
14293         {
14294           /* Inverted range entries are invalid.  */
14295           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14296           return false;
14297         }
14298
14299       /* Empty range entries have no effect.  */
14300       if (range_beginning == range_end)
14301         continue;
14302
14303       range_beginning += base;
14304       range_end += base;
14305
14306       /* A not-uncommon case of bad debug info.
14307          Don't pollute the addrmap with bad data.  */
14308       if (range_beginning + baseaddr == 0
14309           && !dwarf2_per_objfile->has_section_at_zero)
14310         {
14311           complaint (_(".debug_rnglists entry has start address of zero"
14312                        " [in module %s]"), objfile_name (objfile));
14313           continue;
14314         }
14315
14316       callback (range_beginning, range_end);
14317     }
14318
14319   if (overflow)
14320     {
14321       complaint (_("Offset %d is not terminated "
14322                    "for DW_AT_ranges attribute"),
14323                  offset);
14324       return false;
14325     }
14326
14327   return true;
14328 }
14329
14330 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14331    Callback's type should be:
14332     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14333    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14334
14335 template <typename Callback>
14336 static int
14337 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14338                        Callback &&callback)
14339 {
14340   struct dwarf2_per_objfile *dwarf2_per_objfile
14341       = cu->per_cu->dwarf2_per_objfile;
14342   struct objfile *objfile = dwarf2_per_objfile->objfile;
14343   struct comp_unit_head *cu_header = &cu->header;
14344   bfd *obfd = objfile->obfd;
14345   unsigned int addr_size = cu_header->addr_size;
14346   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14347   /* Base address selection entry.  */
14348   CORE_ADDR base;
14349   int found_base;
14350   unsigned int dummy;
14351   const gdb_byte *buffer;
14352   CORE_ADDR baseaddr;
14353
14354   if (cu_header->version >= 5)
14355     return dwarf2_rnglists_process (offset, cu, callback);
14356
14357   found_base = cu->base_known;
14358   base = cu->base_address;
14359
14360   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14361   if (offset >= dwarf2_per_objfile->ranges.size)
14362     {
14363       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14364                  offset);
14365       return 0;
14366     }
14367   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14368
14369   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14370
14371   while (1)
14372     {
14373       CORE_ADDR range_beginning, range_end;
14374
14375       range_beginning = read_address (obfd, buffer, cu, &dummy);
14376       buffer += addr_size;
14377       range_end = read_address (obfd, buffer, cu, &dummy);
14378       buffer += addr_size;
14379       offset += 2 * addr_size;
14380
14381       /* An end of list marker is a pair of zero addresses.  */
14382       if (range_beginning == 0 && range_end == 0)
14383         /* Found the end of list entry.  */
14384         break;
14385
14386       /* Each base address selection entry is a pair of 2 values.
14387          The first is the largest possible address, the second is
14388          the base address.  Check for a base address here.  */
14389       if ((range_beginning & mask) == mask)
14390         {
14391           /* If we found the largest possible address, then we already
14392              have the base address in range_end.  */
14393           base = range_end;
14394           found_base = 1;
14395           continue;
14396         }
14397
14398       if (!found_base)
14399         {
14400           /* We have no valid base address for the ranges
14401              data.  */
14402           complaint (_("Invalid .debug_ranges data (no base address)"));
14403           return 0;
14404         }
14405
14406       if (range_beginning > range_end)
14407         {
14408           /* Inverted range entries are invalid.  */
14409           complaint (_("Invalid .debug_ranges data (inverted range)"));
14410           return 0;
14411         }
14412
14413       /* Empty range entries have no effect.  */
14414       if (range_beginning == range_end)
14415         continue;
14416
14417       range_beginning += base;
14418       range_end += base;
14419
14420       /* A not-uncommon case of bad debug info.
14421          Don't pollute the addrmap with bad data.  */
14422       if (range_beginning + baseaddr == 0
14423           && !dwarf2_per_objfile->has_section_at_zero)
14424         {
14425           complaint (_(".debug_ranges entry has start address of zero"
14426                        " [in module %s]"), objfile_name (objfile));
14427           continue;
14428         }
14429
14430       callback (range_beginning, range_end);
14431     }
14432
14433   return 1;
14434 }
14435
14436 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14437    Return 1 if the attributes are present and valid, otherwise, return 0.
14438    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14439
14440 static int
14441 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14442                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14443                     struct partial_symtab *ranges_pst)
14444 {
14445   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14446   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14447   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14448                                        SECT_OFF_TEXT (objfile));
14449   int low_set = 0;
14450   CORE_ADDR low = 0;
14451   CORE_ADDR high = 0;
14452   int retval;
14453
14454   retval = dwarf2_ranges_process (offset, cu,
14455     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14456     {
14457       if (ranges_pst != NULL)
14458         {
14459           CORE_ADDR lowpc;
14460           CORE_ADDR highpc;
14461
14462           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14463                                               range_beginning + baseaddr);
14464           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14465                                                range_end + baseaddr);
14466           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14467                              ranges_pst);
14468         }
14469
14470       /* FIXME: This is recording everything as a low-high
14471          segment of consecutive addresses.  We should have a
14472          data structure for discontiguous block ranges
14473          instead.  */
14474       if (! low_set)
14475         {
14476           low = range_beginning;
14477           high = range_end;
14478           low_set = 1;
14479         }
14480       else
14481         {
14482           if (range_beginning < low)
14483             low = range_beginning;
14484           if (range_end > high)
14485             high = range_end;
14486         }
14487     });
14488   if (!retval)
14489     return 0;
14490
14491   if (! low_set)
14492     /* If the first entry is an end-of-list marker, the range
14493        describes an empty scope, i.e. no instructions.  */
14494     return 0;
14495
14496   if (low_return)
14497     *low_return = low;
14498   if (high_return)
14499     *high_return = high;
14500   return 1;
14501 }
14502
14503 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14504    definition for the return value.  *LOWPC and *HIGHPC are set iff
14505    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14506
14507 static enum pc_bounds_kind
14508 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14509                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14510                       struct partial_symtab *pst)
14511 {
14512   struct dwarf2_per_objfile *dwarf2_per_objfile
14513     = cu->per_cu->dwarf2_per_objfile;
14514   struct attribute *attr;
14515   struct attribute *attr_high;
14516   CORE_ADDR low = 0;
14517   CORE_ADDR high = 0;
14518   enum pc_bounds_kind ret;
14519
14520   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14521   if (attr_high)
14522     {
14523       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14524       if (attr)
14525         {
14526           low = attr_value_as_address (attr);
14527           high = attr_value_as_address (attr_high);
14528           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14529             high += low;
14530         }
14531       else
14532         /* Found high w/o low attribute.  */
14533         return PC_BOUNDS_INVALID;
14534
14535       /* Found consecutive range of addresses.  */
14536       ret = PC_BOUNDS_HIGH_LOW;
14537     }
14538   else
14539     {
14540       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14541       if (attr != NULL)
14542         {
14543           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14544              We take advantage of the fact that DW_AT_ranges does not appear
14545              in DW_TAG_compile_unit of DWO files.  */
14546           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14547           unsigned int ranges_offset = (DW_UNSND (attr)
14548                                         + (need_ranges_base
14549                                            ? cu->ranges_base
14550                                            : 0));
14551
14552           /* Value of the DW_AT_ranges attribute is the offset in the
14553              .debug_ranges section.  */
14554           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14555             return PC_BOUNDS_INVALID;
14556           /* Found discontinuous range of addresses.  */
14557           ret = PC_BOUNDS_RANGES;
14558         }
14559       else
14560         return PC_BOUNDS_NOT_PRESENT;
14561     }
14562
14563   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14564   if (high <= low)
14565     return PC_BOUNDS_INVALID;
14566
14567   /* When using the GNU linker, .gnu.linkonce. sections are used to
14568      eliminate duplicate copies of functions and vtables and such.
14569      The linker will arbitrarily choose one and discard the others.
14570      The AT_*_pc values for such functions refer to local labels in
14571      these sections.  If the section from that file was discarded, the
14572      labels are not in the output, so the relocs get a value of 0.
14573      If this is a discarded function, mark the pc bounds as invalid,
14574      so that GDB will ignore it.  */
14575   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14576     return PC_BOUNDS_INVALID;
14577
14578   *lowpc = low;
14579   if (highpc)
14580     *highpc = high;
14581   return ret;
14582 }
14583
14584 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14585    its low and high PC addresses.  Do nothing if these addresses could not
14586    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14587    and HIGHPC to the high address if greater than HIGHPC.  */
14588
14589 static void
14590 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14591                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14592                                  struct dwarf2_cu *cu)
14593 {
14594   CORE_ADDR low, high;
14595   struct die_info *child = die->child;
14596
14597   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14598     {
14599       *lowpc = std::min (*lowpc, low);
14600       *highpc = std::max (*highpc, high);
14601     }
14602
14603   /* If the language does not allow nested subprograms (either inside
14604      subprograms or lexical blocks), we're done.  */
14605   if (cu->language != language_ada)
14606     return;
14607
14608   /* Check all the children of the given DIE.  If it contains nested
14609      subprograms, then check their pc bounds.  Likewise, we need to
14610      check lexical blocks as well, as they may also contain subprogram
14611      definitions.  */
14612   while (child && child->tag)
14613     {
14614       if (child->tag == DW_TAG_subprogram
14615           || child->tag == DW_TAG_lexical_block)
14616         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14617       child = sibling_die (child);
14618     }
14619 }
14620
14621 /* Get the low and high pc's represented by the scope DIE, and store
14622    them in *LOWPC and *HIGHPC.  If the correct values can't be
14623    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14624
14625 static void
14626 get_scope_pc_bounds (struct die_info *die,
14627                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14628                      struct dwarf2_cu *cu)
14629 {
14630   CORE_ADDR best_low = (CORE_ADDR) -1;
14631   CORE_ADDR best_high = (CORE_ADDR) 0;
14632   CORE_ADDR current_low, current_high;
14633
14634   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14635       >= PC_BOUNDS_RANGES)
14636     {
14637       best_low = current_low;
14638       best_high = current_high;
14639     }
14640   else
14641     {
14642       struct die_info *child = die->child;
14643
14644       while (child && child->tag)
14645         {
14646           switch (child->tag) {
14647           case DW_TAG_subprogram:
14648             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14649             break;
14650           case DW_TAG_namespace:
14651           case DW_TAG_module:
14652             /* FIXME: carlton/2004-01-16: Should we do this for
14653                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14654                that current GCC's always emit the DIEs corresponding
14655                to definitions of methods of classes as children of a
14656                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14657                the DIEs giving the declarations, which could be
14658                anywhere).  But I don't see any reason why the
14659                standards says that they have to be there.  */
14660             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14661
14662             if (current_low != ((CORE_ADDR) -1))
14663               {
14664                 best_low = std::min (best_low, current_low);
14665                 best_high = std::max (best_high, current_high);
14666               }
14667             break;
14668           default:
14669             /* Ignore.  */
14670             break;
14671           }
14672
14673           child = sibling_die (child);
14674         }
14675     }
14676
14677   *lowpc = best_low;
14678   *highpc = best_high;
14679 }
14680
14681 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14682    in DIE.  */
14683
14684 static void
14685 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14686                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14687 {
14688   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14689   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14690   struct attribute *attr;
14691   struct attribute *attr_high;
14692
14693   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14694   if (attr_high)
14695     {
14696       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14697       if (attr)
14698         {
14699           CORE_ADDR low = attr_value_as_address (attr);
14700           CORE_ADDR high = attr_value_as_address (attr_high);
14701
14702           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14703             high += low;
14704
14705           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14706           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14707           record_block_range (block, low, high - 1);
14708         }
14709     }
14710
14711   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14712   if (attr)
14713     {
14714       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14715          We take advantage of the fact that DW_AT_ranges does not appear
14716          in DW_TAG_compile_unit of DWO files.  */
14717       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14718
14719       /* The value of the DW_AT_ranges attribute is the offset of the
14720          address range list in the .debug_ranges section.  */
14721       unsigned long offset = (DW_UNSND (attr)
14722                               + (need_ranges_base ? cu->ranges_base : 0));
14723
14724       dwarf2_ranges_process (offset, cu,
14725         [&] (CORE_ADDR start, CORE_ADDR end)
14726         {
14727           start += baseaddr;
14728           end += baseaddr;
14729           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14730           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14731           record_block_range (block, start, end - 1);
14732         });
14733     }
14734 }
14735
14736 /* Check whether the producer field indicates either of GCC < 4.6, or the
14737    Intel C/C++ compiler, and cache the result in CU.  */
14738
14739 static void
14740 check_producer (struct dwarf2_cu *cu)
14741 {
14742   int major, minor;
14743
14744   if (cu->producer == NULL)
14745     {
14746       /* For unknown compilers expect their behavior is DWARF version
14747          compliant.
14748
14749          GCC started to support .debug_types sections by -gdwarf-4 since
14750          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14751          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14752          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14753          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14754     }
14755   else if (producer_is_gcc (cu->producer, &major, &minor))
14756     {
14757       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14758       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14759     }
14760   else if (producer_is_icc (cu->producer, &major, &minor))
14761     cu->producer_is_icc_lt_14 = major < 14;
14762   else
14763     {
14764       /* For other non-GCC compilers, expect their behavior is DWARF version
14765          compliant.  */
14766     }
14767
14768   cu->checked_producer = 1;
14769 }
14770
14771 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14772    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14773    during 4.6.0 experimental.  */
14774
14775 static int
14776 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14777 {
14778   if (!cu->checked_producer)
14779     check_producer (cu);
14780
14781   return cu->producer_is_gxx_lt_4_6;
14782 }
14783
14784 /* Return the default accessibility type if it is not overriden by
14785    DW_AT_accessibility.  */
14786
14787 static enum dwarf_access_attribute
14788 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14789 {
14790   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14791     {
14792       /* The default DWARF 2 accessibility for members is public, the default
14793          accessibility for inheritance is private.  */
14794
14795       if (die->tag != DW_TAG_inheritance)
14796         return DW_ACCESS_public;
14797       else
14798         return DW_ACCESS_private;
14799     }
14800   else
14801     {
14802       /* DWARF 3+ defines the default accessibility a different way.  The same
14803          rules apply now for DW_TAG_inheritance as for the members and it only
14804          depends on the container kind.  */
14805
14806       if (die->parent->tag == DW_TAG_class_type)
14807         return DW_ACCESS_private;
14808       else
14809         return DW_ACCESS_public;
14810     }
14811 }
14812
14813 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14814    offset.  If the attribute was not found return 0, otherwise return
14815    1.  If it was found but could not properly be handled, set *OFFSET
14816    to 0.  */
14817
14818 static int
14819 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14820                              LONGEST *offset)
14821 {
14822   struct attribute *attr;
14823
14824   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14825   if (attr != NULL)
14826     {
14827       *offset = 0;
14828
14829       /* Note that we do not check for a section offset first here.
14830          This is because DW_AT_data_member_location is new in DWARF 4,
14831          so if we see it, we can assume that a constant form is really
14832          a constant and not a section offset.  */
14833       if (attr_form_is_constant (attr))
14834         *offset = dwarf2_get_attr_constant_value (attr, 0);
14835       else if (attr_form_is_section_offset (attr))
14836         dwarf2_complex_location_expr_complaint ();
14837       else if (attr_form_is_block (attr))
14838         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14839       else
14840         dwarf2_complex_location_expr_complaint ();
14841
14842       return 1;
14843     }
14844
14845   return 0;
14846 }
14847
14848 /* Add an aggregate field to the field list.  */
14849
14850 static void
14851 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14852                   struct dwarf2_cu *cu)
14853 {
14854   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14855   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14856   struct nextfield *new_field;
14857   struct attribute *attr;
14858   struct field *fp;
14859   const char *fieldname = "";
14860
14861   if (die->tag == DW_TAG_inheritance)
14862     {
14863       fip->baseclasses.emplace_back ();
14864       new_field = &fip->baseclasses.back ();
14865     }
14866   else
14867     {
14868       fip->fields.emplace_back ();
14869       new_field = &fip->fields.back ();
14870     }
14871
14872   fip->nfields++;
14873
14874   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14875   if (attr)
14876     new_field->accessibility = DW_UNSND (attr);
14877   else
14878     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14879   if (new_field->accessibility != DW_ACCESS_public)
14880     fip->non_public_fields = 1;
14881
14882   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14883   if (attr)
14884     new_field->virtuality = DW_UNSND (attr);
14885   else
14886     new_field->virtuality = DW_VIRTUALITY_none;
14887
14888   fp = &new_field->field;
14889
14890   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14891     {
14892       LONGEST offset;
14893
14894       /* Data member other than a C++ static data member.  */
14895
14896       /* Get type of field.  */
14897       fp->type = die_type (die, cu);
14898
14899       SET_FIELD_BITPOS (*fp, 0);
14900
14901       /* Get bit size of field (zero if none).  */
14902       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14903       if (attr)
14904         {
14905           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14906         }
14907       else
14908         {
14909           FIELD_BITSIZE (*fp) = 0;
14910         }
14911
14912       /* Get bit offset of field.  */
14913       if (handle_data_member_location (die, cu, &offset))
14914         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14915       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14916       if (attr)
14917         {
14918           if (gdbarch_bits_big_endian (gdbarch))
14919             {
14920               /* For big endian bits, the DW_AT_bit_offset gives the
14921                  additional bit offset from the MSB of the containing
14922                  anonymous object to the MSB of the field.  We don't
14923                  have to do anything special since we don't need to
14924                  know the size of the anonymous object.  */
14925               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
14926             }
14927           else
14928             {
14929               /* For little endian bits, compute the bit offset to the
14930                  MSB of the anonymous object, subtract off the number of
14931                  bits from the MSB of the field to the MSB of the
14932                  object, and then subtract off the number of bits of
14933                  the field itself.  The result is the bit offset of
14934                  the LSB of the field.  */
14935               int anonymous_size;
14936               int bit_offset = DW_UNSND (attr);
14937
14938               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14939               if (attr)
14940                 {
14941                   /* The size of the anonymous object containing
14942                      the bit field is explicit, so use the
14943                      indicated size (in bytes).  */
14944                   anonymous_size = DW_UNSND (attr);
14945                 }
14946               else
14947                 {
14948                   /* The size of the anonymous object containing
14949                      the bit field must be inferred from the type
14950                      attribute of the data member containing the
14951                      bit field.  */
14952                   anonymous_size = TYPE_LENGTH (fp->type);
14953                 }
14954               SET_FIELD_BITPOS (*fp,
14955                                 (FIELD_BITPOS (*fp)
14956                                  + anonymous_size * bits_per_byte
14957                                  - bit_offset - FIELD_BITSIZE (*fp)));
14958             }
14959         }
14960       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
14961       if (attr != NULL)
14962         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14963                                 + dwarf2_get_attr_constant_value (attr, 0)));
14964
14965       /* Get name of field.  */
14966       fieldname = dwarf2_name (die, cu);
14967       if (fieldname == NULL)
14968         fieldname = "";
14969
14970       /* The name is already allocated along with this objfile, so we don't
14971          need to duplicate it for the type.  */
14972       fp->name = fieldname;
14973
14974       /* Change accessibility for artificial fields (e.g. virtual table
14975          pointer or virtual base class pointer) to private.  */
14976       if (dwarf2_attr (die, DW_AT_artificial, cu))
14977         {
14978           FIELD_ARTIFICIAL (*fp) = 1;
14979           new_field->accessibility = DW_ACCESS_private;
14980           fip->non_public_fields = 1;
14981         }
14982     }
14983   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
14984     {
14985       /* C++ static member.  */
14986
14987       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
14988          is a declaration, but all versions of G++ as of this writing
14989          (so through at least 3.2.1) incorrectly generate
14990          DW_TAG_variable tags.  */
14991
14992       const char *physname;
14993
14994       /* Get name of field.  */
14995       fieldname = dwarf2_name (die, cu);
14996       if (fieldname == NULL)
14997         return;
14998
14999       attr = dwarf2_attr (die, DW_AT_const_value, cu);
15000       if (attr
15001           /* Only create a symbol if this is an external value.
15002              new_symbol checks this and puts the value in the global symbol
15003              table, which we want.  If it is not external, new_symbol
15004              will try to put the value in cu->list_in_scope which is wrong.  */
15005           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15006         {
15007           /* A static const member, not much different than an enum as far as
15008              we're concerned, except that we can support more types.  */
15009           new_symbol (die, NULL, cu);
15010         }
15011
15012       /* Get physical name.  */
15013       physname = dwarf2_physname (fieldname, die, cu);
15014
15015       /* The name is already allocated along with this objfile, so we don't
15016          need to duplicate it for the type.  */
15017       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15018       FIELD_TYPE (*fp) = die_type (die, cu);
15019       FIELD_NAME (*fp) = fieldname;
15020     }
15021   else if (die->tag == DW_TAG_inheritance)
15022     {
15023       LONGEST offset;
15024
15025       /* C++ base class field.  */
15026       if (handle_data_member_location (die, cu, &offset))
15027         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15028       FIELD_BITSIZE (*fp) = 0;
15029       FIELD_TYPE (*fp) = die_type (die, cu);
15030       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15031     }
15032   else if (die->tag == DW_TAG_variant_part)
15033     {
15034       /* process_structure_scope will treat this DIE as a union.  */
15035       process_structure_scope (die, cu);
15036
15037       /* The variant part is relative to the start of the enclosing
15038          structure.  */
15039       SET_FIELD_BITPOS (*fp, 0);
15040       fp->type = get_die_type (die, cu);
15041       fp->artificial = 1;
15042       fp->name = "<<variant>>";
15043     }
15044   else
15045     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15046 }
15047
15048 /* Can the type given by DIE define another type?  */
15049
15050 static bool
15051 type_can_define_types (const struct die_info *die)
15052 {
15053   switch (die->tag)
15054     {
15055     case DW_TAG_typedef:
15056     case DW_TAG_class_type:
15057     case DW_TAG_structure_type:
15058     case DW_TAG_union_type:
15059     case DW_TAG_enumeration_type:
15060       return true;
15061
15062     default:
15063       return false;
15064     }
15065 }
15066
15067 /* Add a type definition defined in the scope of the FIP's class.  */
15068
15069 static void
15070 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15071                       struct dwarf2_cu *cu)
15072 {
15073   struct decl_field fp;
15074   memset (&fp, 0, sizeof (fp));
15075
15076   gdb_assert (type_can_define_types (die));
15077
15078   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15079   fp.name = dwarf2_name (die, cu);
15080   fp.type = read_type_die (die, cu);
15081
15082   /* Save accessibility.  */
15083   enum dwarf_access_attribute accessibility;
15084   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15085   if (attr != NULL)
15086     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15087   else
15088     accessibility = dwarf2_default_access_attribute (die, cu);
15089   switch (accessibility)
15090     {
15091     case DW_ACCESS_public:
15092       /* The assumed value if neither private nor protected.  */
15093       break;
15094     case DW_ACCESS_private:
15095       fp.is_private = 1;
15096       break;
15097     case DW_ACCESS_protected:
15098       fp.is_protected = 1;
15099       break;
15100     default:
15101       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15102     }
15103
15104   if (die->tag == DW_TAG_typedef)
15105     fip->typedef_field_list.push_back (fp);
15106   else
15107     fip->nested_types_list.push_back (fp);
15108 }
15109
15110 /* Create the vector of fields, and attach it to the type.  */
15111
15112 static void
15113 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15114                               struct dwarf2_cu *cu)
15115 {
15116   int nfields = fip->nfields;
15117
15118   /* Record the field count, allocate space for the array of fields,
15119      and create blank accessibility bitfields if necessary.  */
15120   TYPE_NFIELDS (type) = nfields;
15121   TYPE_FIELDS (type) = (struct field *)
15122     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15123
15124   if (fip->non_public_fields && cu->language != language_ada)
15125     {
15126       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15127
15128       TYPE_FIELD_PRIVATE_BITS (type) =
15129         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15130       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15131
15132       TYPE_FIELD_PROTECTED_BITS (type) =
15133         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15134       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15135
15136       TYPE_FIELD_IGNORE_BITS (type) =
15137         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15138       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15139     }
15140
15141   /* If the type has baseclasses, allocate and clear a bit vector for
15142      TYPE_FIELD_VIRTUAL_BITS.  */
15143   if (!fip->baseclasses.empty () && cu->language != language_ada)
15144     {
15145       int num_bytes = B_BYTES (fip->baseclasses.size ());
15146       unsigned char *pointer;
15147
15148       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15149       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15150       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15151       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15152       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15153     }
15154
15155   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15156     {
15157       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15158
15159       for (int index = 0; index < nfields; ++index)
15160         {
15161           struct nextfield &field = fip->fields[index];
15162
15163           if (field.variant.is_discriminant)
15164             di->discriminant_index = index;
15165           else if (field.variant.default_branch)
15166             di->default_index = index;
15167           else
15168             di->discriminants[index] = field.variant.discriminant_value;
15169         }
15170     }
15171
15172   /* Copy the saved-up fields into the field vector.  */
15173   for (int i = 0; i < nfields; ++i)
15174     {
15175       struct nextfield &field
15176         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15177            : fip->fields[i - fip->baseclasses.size ()]);
15178
15179       TYPE_FIELD (type, i) = field.field;
15180       switch (field.accessibility)
15181         {
15182         case DW_ACCESS_private:
15183           if (cu->language != language_ada)
15184             SET_TYPE_FIELD_PRIVATE (type, i);
15185           break;
15186
15187         case DW_ACCESS_protected:
15188           if (cu->language != language_ada)
15189             SET_TYPE_FIELD_PROTECTED (type, i);
15190           break;
15191
15192         case DW_ACCESS_public:
15193           break;
15194
15195         default:
15196           /* Unknown accessibility.  Complain and treat it as public.  */
15197           {
15198             complaint (_("unsupported accessibility %d"),
15199                        field.accessibility);
15200           }
15201           break;
15202         }
15203       if (i < fip->baseclasses.size ())
15204         {
15205           switch (field.virtuality)
15206             {
15207             case DW_VIRTUALITY_virtual:
15208             case DW_VIRTUALITY_pure_virtual:
15209               if (cu->language == language_ada)
15210                 error (_("unexpected virtuality in component of Ada type"));
15211               SET_TYPE_FIELD_VIRTUAL (type, i);
15212               break;
15213             }
15214         }
15215     }
15216 }
15217
15218 /* Return true if this member function is a constructor, false
15219    otherwise.  */
15220
15221 static int
15222 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15223 {
15224   const char *fieldname;
15225   const char *type_name;
15226   int len;
15227
15228   if (die->parent == NULL)
15229     return 0;
15230
15231   if (die->parent->tag != DW_TAG_structure_type
15232       && die->parent->tag != DW_TAG_union_type
15233       && die->parent->tag != DW_TAG_class_type)
15234     return 0;
15235
15236   fieldname = dwarf2_name (die, cu);
15237   type_name = dwarf2_name (die->parent, cu);
15238   if (fieldname == NULL || type_name == NULL)
15239     return 0;
15240
15241   len = strlen (fieldname);
15242   return (strncmp (fieldname, type_name, len) == 0
15243           && (type_name[len] == '\0' || type_name[len] == '<'));
15244 }
15245
15246 /* Add a member function to the proper fieldlist.  */
15247
15248 static void
15249 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15250                       struct type *type, struct dwarf2_cu *cu)
15251 {
15252   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15253   struct attribute *attr;
15254   int i;
15255   struct fnfieldlist *flp = nullptr;
15256   struct fn_field *fnp;
15257   const char *fieldname;
15258   struct type *this_type;
15259   enum dwarf_access_attribute accessibility;
15260
15261   if (cu->language == language_ada)
15262     error (_("unexpected member function in Ada type"));
15263
15264   /* Get name of member function.  */
15265   fieldname = dwarf2_name (die, cu);
15266   if (fieldname == NULL)
15267     return;
15268
15269   /* Look up member function name in fieldlist.  */
15270   for (i = 0; i < fip->fnfieldlists.size (); i++)
15271     {
15272       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15273         {
15274           flp = &fip->fnfieldlists[i];
15275           break;
15276         }
15277     }
15278
15279   /* Create a new fnfieldlist if necessary.  */
15280   if (flp == nullptr)
15281     {
15282       fip->fnfieldlists.emplace_back ();
15283       flp = &fip->fnfieldlists.back ();
15284       flp->name = fieldname;
15285       i = fip->fnfieldlists.size () - 1;
15286     }
15287
15288   /* Create a new member function field and add it to the vector of
15289      fnfieldlists.  */
15290   flp->fnfields.emplace_back ();
15291   fnp = &flp->fnfields.back ();
15292
15293   /* Delay processing of the physname until later.  */
15294   if (cu->language == language_cplus)
15295     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15296                         die, cu);
15297   else
15298     {
15299       const char *physname = dwarf2_physname (fieldname, die, cu);
15300       fnp->physname = physname ? physname : "";
15301     }
15302
15303   fnp->type = alloc_type (objfile);
15304   this_type = read_type_die (die, cu);
15305   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15306     {
15307       int nparams = TYPE_NFIELDS (this_type);
15308
15309       /* TYPE is the domain of this method, and THIS_TYPE is the type
15310            of the method itself (TYPE_CODE_METHOD).  */
15311       smash_to_method_type (fnp->type, type,
15312                             TYPE_TARGET_TYPE (this_type),
15313                             TYPE_FIELDS (this_type),
15314                             TYPE_NFIELDS (this_type),
15315                             TYPE_VARARGS (this_type));
15316
15317       /* Handle static member functions.
15318          Dwarf2 has no clean way to discern C++ static and non-static
15319          member functions.  G++ helps GDB by marking the first
15320          parameter for non-static member functions (which is the this
15321          pointer) as artificial.  We obtain this information from
15322          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15323       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15324         fnp->voffset = VOFFSET_STATIC;
15325     }
15326   else
15327     complaint (_("member function type missing for '%s'"),
15328                dwarf2_full_name (fieldname, die, cu));
15329
15330   /* Get fcontext from DW_AT_containing_type if present.  */
15331   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15332     fnp->fcontext = die_containing_type (die, cu);
15333
15334   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15335      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15336
15337   /* Get accessibility.  */
15338   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15339   if (attr)
15340     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15341   else
15342     accessibility = dwarf2_default_access_attribute (die, cu);
15343   switch (accessibility)
15344     {
15345     case DW_ACCESS_private:
15346       fnp->is_private = 1;
15347       break;
15348     case DW_ACCESS_protected:
15349       fnp->is_protected = 1;
15350       break;
15351     }
15352
15353   /* Check for artificial methods.  */
15354   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15355   if (attr && DW_UNSND (attr) != 0)
15356     fnp->is_artificial = 1;
15357
15358   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15359
15360   /* Get index in virtual function table if it is a virtual member
15361      function.  For older versions of GCC, this is an offset in the
15362      appropriate virtual table, as specified by DW_AT_containing_type.
15363      For everyone else, it is an expression to be evaluated relative
15364      to the object address.  */
15365
15366   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15367   if (attr)
15368     {
15369       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15370         {
15371           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15372             {
15373               /* Old-style GCC.  */
15374               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15375             }
15376           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15377                    || (DW_BLOCK (attr)->size > 1
15378                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15379                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15380             {
15381               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15382               if ((fnp->voffset % cu->header.addr_size) != 0)
15383                 dwarf2_complex_location_expr_complaint ();
15384               else
15385                 fnp->voffset /= cu->header.addr_size;
15386               fnp->voffset += 2;
15387             }
15388           else
15389             dwarf2_complex_location_expr_complaint ();
15390
15391           if (!fnp->fcontext)
15392             {
15393               /* If there is no `this' field and no DW_AT_containing_type,
15394                  we cannot actually find a base class context for the
15395                  vtable!  */
15396               if (TYPE_NFIELDS (this_type) == 0
15397                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15398                 {
15399                   complaint (_("cannot determine context for virtual member "
15400                                "function \"%s\" (offset %s)"),
15401                              fieldname, sect_offset_str (die->sect_off));
15402                 }
15403               else
15404                 {
15405                   fnp->fcontext
15406                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15407                 }
15408             }
15409         }
15410       else if (attr_form_is_section_offset (attr))
15411         {
15412           dwarf2_complex_location_expr_complaint ();
15413         }
15414       else
15415         {
15416           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15417                                                  fieldname);
15418         }
15419     }
15420   else
15421     {
15422       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15423       if (attr && DW_UNSND (attr))
15424         {
15425           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15426           complaint (_("Member function \"%s\" (offset %s) is virtual "
15427                        "but the vtable offset is not specified"),
15428                      fieldname, sect_offset_str (die->sect_off));
15429           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15430           TYPE_CPLUS_DYNAMIC (type) = 1;
15431         }
15432     }
15433 }
15434
15435 /* Create the vector of member function fields, and attach it to the type.  */
15436
15437 static void
15438 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15439                                  struct dwarf2_cu *cu)
15440 {
15441   if (cu->language == language_ada)
15442     error (_("unexpected member functions in Ada type"));
15443
15444   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15445   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15446     TYPE_ALLOC (type,
15447                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15448
15449   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15450     {
15451       struct fnfieldlist &nf = fip->fnfieldlists[i];
15452       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15453
15454       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15455       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15456       fn_flp->fn_fields = (struct fn_field *)
15457         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15458
15459       for (int k = 0; k < nf.fnfields.size (); ++k)
15460         fn_flp->fn_fields[k] = nf.fnfields[k];
15461     }
15462
15463   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15464 }
15465
15466 /* Returns non-zero if NAME is the name of a vtable member in CU's
15467    language, zero otherwise.  */
15468 static int
15469 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15470 {
15471   static const char vptr[] = "_vptr";
15472
15473   /* Look for the C++ form of the vtable.  */
15474   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15475     return 1;
15476
15477   return 0;
15478 }
15479
15480 /* GCC outputs unnamed structures that are really pointers to member
15481    functions, with the ABI-specified layout.  If TYPE describes
15482    such a structure, smash it into a member function type.
15483
15484    GCC shouldn't do this; it should just output pointer to member DIEs.
15485    This is GCC PR debug/28767.  */
15486
15487 static void
15488 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15489 {
15490   struct type *pfn_type, *self_type, *new_type;
15491
15492   /* Check for a structure with no name and two children.  */
15493   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15494     return;
15495
15496   /* Check for __pfn and __delta members.  */
15497   if (TYPE_FIELD_NAME (type, 0) == NULL
15498       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15499       || TYPE_FIELD_NAME (type, 1) == NULL
15500       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15501     return;
15502
15503   /* Find the type of the method.  */
15504   pfn_type = TYPE_FIELD_TYPE (type, 0);
15505   if (pfn_type == NULL
15506       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15507       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15508     return;
15509
15510   /* Look for the "this" argument.  */
15511   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15512   if (TYPE_NFIELDS (pfn_type) == 0
15513       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15514       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15515     return;
15516
15517   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15518   new_type = alloc_type (objfile);
15519   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15520                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15521                         TYPE_VARARGS (pfn_type));
15522   smash_to_methodptr_type (type, new_type);
15523 }
15524
15525 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15526    appropriate error checking and issuing complaints if there is a
15527    problem.  */
15528
15529 static ULONGEST
15530 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15531 {
15532   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15533
15534   if (attr == nullptr)
15535     return 0;
15536
15537   if (!attr_form_is_constant (attr))
15538     {
15539       complaint (_("DW_AT_alignment must have constant form"
15540                    " - DIE at %s [in module %s]"),
15541                  sect_offset_str (die->sect_off),
15542                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15543       return 0;
15544     }
15545
15546   ULONGEST align;
15547   if (attr->form == DW_FORM_sdata)
15548     {
15549       LONGEST val = DW_SND (attr);
15550       if (val < 0)
15551         {
15552           complaint (_("DW_AT_alignment value must not be negative"
15553                        " - DIE at %s [in module %s]"),
15554                      sect_offset_str (die->sect_off),
15555                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15556           return 0;
15557         }
15558       align = val;
15559     }
15560   else
15561     align = DW_UNSND (attr);
15562
15563   if (align == 0)
15564     {
15565       complaint (_("DW_AT_alignment value must not be zero"
15566                    " - DIE at %s [in module %s]"),
15567                  sect_offset_str (die->sect_off),
15568                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15569       return 0;
15570     }
15571   if ((align & (align - 1)) != 0)
15572     {
15573       complaint (_("DW_AT_alignment value must be a power of 2"
15574                    " - DIE at %s [in module %s]"),
15575                  sect_offset_str (die->sect_off),
15576                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15577       return 0;
15578     }
15579
15580   return align;
15581 }
15582
15583 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15584    the alignment for TYPE.  */
15585
15586 static void
15587 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15588                      struct type *type)
15589 {
15590   if (!set_type_align (type, get_alignment (cu, die)))
15591     complaint (_("DW_AT_alignment value too large"
15592                  " - DIE at %s [in module %s]"),
15593                sect_offset_str (die->sect_off),
15594                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15595 }
15596
15597 /* Called when we find the DIE that starts a structure or union scope
15598    (definition) to create a type for the structure or union.  Fill in
15599    the type's name and general properties; the members will not be
15600    processed until process_structure_scope.  A symbol table entry for
15601    the type will also not be done until process_structure_scope (assuming
15602    the type has a name).
15603
15604    NOTE: we need to call these functions regardless of whether or not the
15605    DIE has a DW_AT_name attribute, since it might be an anonymous
15606    structure or union.  This gets the type entered into our set of
15607    user defined types.  */
15608
15609 static struct type *
15610 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15611 {
15612   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15613   struct type *type;
15614   struct attribute *attr;
15615   const char *name;
15616
15617   /* If the definition of this type lives in .debug_types, read that type.
15618      Don't follow DW_AT_specification though, that will take us back up
15619      the chain and we want to go down.  */
15620   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15621   if (attr)
15622     {
15623       type = get_DW_AT_signature_type (die, attr, cu);
15624
15625       /* The type's CU may not be the same as CU.
15626          Ensure TYPE is recorded with CU in die_type_hash.  */
15627       return set_die_type (die, type, cu);
15628     }
15629
15630   type = alloc_type (objfile);
15631   INIT_CPLUS_SPECIFIC (type);
15632
15633   name = dwarf2_name (die, cu);
15634   if (name != NULL)
15635     {
15636       if (cu->language == language_cplus
15637           || cu->language == language_d
15638           || cu->language == language_rust)
15639         {
15640           const char *full_name = dwarf2_full_name (name, die, cu);
15641
15642           /* dwarf2_full_name might have already finished building the DIE's
15643              type.  If so, there is no need to continue.  */
15644           if (get_die_type (die, cu) != NULL)
15645             return get_die_type (die, cu);
15646
15647           TYPE_NAME (type) = full_name;
15648         }
15649       else
15650         {
15651           /* The name is already allocated along with this objfile, so
15652              we don't need to duplicate it for the type.  */
15653           TYPE_NAME (type) = name;
15654         }
15655     }
15656
15657   if (die->tag == DW_TAG_structure_type)
15658     {
15659       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15660     }
15661   else if (die->tag == DW_TAG_union_type)
15662     {
15663       TYPE_CODE (type) = TYPE_CODE_UNION;
15664     }
15665   else if (die->tag == DW_TAG_variant_part)
15666     {
15667       TYPE_CODE (type) = TYPE_CODE_UNION;
15668       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15669     }
15670   else
15671     {
15672       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15673     }
15674
15675   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15676     TYPE_DECLARED_CLASS (type) = 1;
15677
15678   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15679   if (attr)
15680     {
15681       if (attr_form_is_constant (attr))
15682         TYPE_LENGTH (type) = DW_UNSND (attr);
15683       else
15684         {
15685           /* For the moment, dynamic type sizes are not supported
15686              by GDB's struct type.  The actual size is determined
15687              on-demand when resolving the type of a given object,
15688              so set the type's length to zero for now.  Otherwise,
15689              we record an expression as the length, and that expression
15690              could lead to a very large value, which could eventually
15691              lead to us trying to allocate that much memory when creating
15692              a value of that type.  */
15693           TYPE_LENGTH (type) = 0;
15694         }
15695     }
15696   else
15697     {
15698       TYPE_LENGTH (type) = 0;
15699     }
15700
15701   maybe_set_alignment (cu, die, type);
15702
15703   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15704     {
15705       /* ICC<14 does not output the required DW_AT_declaration on
15706          incomplete types, but gives them a size of zero.  */
15707       TYPE_STUB (type) = 1;
15708     }
15709   else
15710     TYPE_STUB_SUPPORTED (type) = 1;
15711
15712   if (die_is_declaration (die, cu))
15713     TYPE_STUB (type) = 1;
15714   else if (attr == NULL && die->child == NULL
15715            && producer_is_realview (cu->producer))
15716     /* RealView does not output the required DW_AT_declaration
15717        on incomplete types.  */
15718     TYPE_STUB (type) = 1;
15719
15720   /* We need to add the type field to the die immediately so we don't
15721      infinitely recurse when dealing with pointers to the structure
15722      type within the structure itself.  */
15723   set_die_type (die, type, cu);
15724
15725   /* set_die_type should be already done.  */
15726   set_descriptive_type (type, die, cu);
15727
15728   return type;
15729 }
15730
15731 /* A helper for process_structure_scope that handles a single member
15732    DIE.  */
15733
15734 static void
15735 handle_struct_member_die (struct die_info *child_die, struct type *type,
15736                           struct field_info *fi,
15737                           std::vector<struct symbol *> *template_args,
15738                           struct dwarf2_cu *cu)
15739 {
15740   if (child_die->tag == DW_TAG_member
15741       || child_die->tag == DW_TAG_variable
15742       || child_die->tag == DW_TAG_variant_part)
15743     {
15744       /* NOTE: carlton/2002-11-05: A C++ static data member
15745          should be a DW_TAG_member that is a declaration, but
15746          all versions of G++ as of this writing (so through at
15747          least 3.2.1) incorrectly generate DW_TAG_variable
15748          tags for them instead.  */
15749       dwarf2_add_field (fi, child_die, cu);
15750     }
15751   else if (child_die->tag == DW_TAG_subprogram)
15752     {
15753       /* Rust doesn't have member functions in the C++ sense.
15754          However, it does emit ordinary functions as children
15755          of a struct DIE.  */
15756       if (cu->language == language_rust)
15757         read_func_scope (child_die, cu);
15758       else
15759         {
15760           /* C++ member function.  */
15761           dwarf2_add_member_fn (fi, child_die, type, cu);
15762         }
15763     }
15764   else if (child_die->tag == DW_TAG_inheritance)
15765     {
15766       /* C++ base class field.  */
15767       dwarf2_add_field (fi, child_die, cu);
15768     }
15769   else if (type_can_define_types (child_die))
15770     dwarf2_add_type_defn (fi, child_die, cu);
15771   else if (child_die->tag == DW_TAG_template_type_param
15772            || child_die->tag == DW_TAG_template_value_param)
15773     {
15774       struct symbol *arg = new_symbol (child_die, NULL, cu);
15775
15776       if (arg != NULL)
15777         template_args->push_back (arg);
15778     }
15779   else if (child_die->tag == DW_TAG_variant)
15780     {
15781       /* In a variant we want to get the discriminant and also add a
15782          field for our sole member child.  */
15783       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15784
15785       for (struct die_info *variant_child = child_die->child;
15786            variant_child != NULL;
15787            variant_child = sibling_die (variant_child))
15788         {
15789           if (variant_child->tag == DW_TAG_member)
15790             {
15791               handle_struct_member_die (variant_child, type, fi,
15792                                         template_args, cu);
15793               /* Only handle the one.  */
15794               break;
15795             }
15796         }
15797
15798       /* We don't handle this but we might as well report it if we see
15799          it.  */
15800       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15801           complaint (_("DW_AT_discr_list is not supported yet"
15802                        " - DIE at %s [in module %s]"),
15803                      sect_offset_str (child_die->sect_off),
15804                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15805
15806       /* The first field was just added, so we can stash the
15807          discriminant there.  */
15808       gdb_assert (!fi->fields.empty ());
15809       if (discr == NULL)
15810         fi->fields.back ().variant.default_branch = true;
15811       else
15812         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15813     }
15814 }
15815
15816 /* Finish creating a structure or union type, including filling in
15817    its members and creating a symbol for it.  */
15818
15819 static void
15820 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15821 {
15822   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15823   struct die_info *child_die;
15824   struct type *type;
15825
15826   type = get_die_type (die, cu);
15827   if (type == NULL)
15828     type = read_structure_type (die, cu);
15829
15830   /* When reading a DW_TAG_variant_part, we need to notice when we
15831      read the discriminant member, so we can record it later in the
15832      discriminant_info.  */
15833   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15834   sect_offset discr_offset;
15835
15836   if (is_variant_part)
15837     {
15838       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15839       if (discr == NULL)
15840         {
15841           /* Maybe it's a univariant form, an extension we support.
15842              In this case arrange not to check the offset.  */
15843           is_variant_part = false;
15844         }
15845       else if (attr_form_is_ref (discr))
15846         {
15847           struct dwarf2_cu *target_cu = cu;
15848           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15849
15850           discr_offset = target_die->sect_off;
15851         }
15852       else
15853         {
15854           complaint (_("DW_AT_discr does not have DIE reference form"
15855                        " - DIE at %s [in module %s]"),
15856                      sect_offset_str (die->sect_off),
15857                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15858           is_variant_part = false;
15859         }
15860     }
15861
15862   if (die->child != NULL && ! die_is_declaration (die, cu))
15863     {
15864       struct field_info fi;
15865       std::vector<struct symbol *> template_args;
15866
15867       child_die = die->child;
15868
15869       while (child_die && child_die->tag)
15870         {
15871           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15872
15873           if (is_variant_part && discr_offset == child_die->sect_off)
15874             fi.fields.back ().variant.is_discriminant = true;
15875
15876           child_die = sibling_die (child_die);
15877         }
15878
15879       /* Attach template arguments to type.  */
15880       if (!template_args.empty ())
15881         {
15882           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15883           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15884           TYPE_TEMPLATE_ARGUMENTS (type)
15885             = XOBNEWVEC (&objfile->objfile_obstack,
15886                          struct symbol *,
15887                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15888           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15889                   template_args.data (),
15890                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15891                    * sizeof (struct symbol *)));
15892         }
15893
15894       /* Attach fields and member functions to the type.  */
15895       if (fi.nfields)
15896         dwarf2_attach_fields_to_type (&fi, type, cu);
15897       if (!fi.fnfieldlists.empty ())
15898         {
15899           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15900
15901           /* Get the type which refers to the base class (possibly this
15902              class itself) which contains the vtable pointer for the current
15903              class from the DW_AT_containing_type attribute.  This use of
15904              DW_AT_containing_type is a GNU extension.  */
15905
15906           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15907             {
15908               struct type *t = die_containing_type (die, cu);
15909
15910               set_type_vptr_basetype (type, t);
15911               if (type == t)
15912                 {
15913                   int i;
15914
15915                   /* Our own class provides vtbl ptr.  */
15916                   for (i = TYPE_NFIELDS (t) - 1;
15917                        i >= TYPE_N_BASECLASSES (t);
15918                        --i)
15919                     {
15920                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15921
15922                       if (is_vtable_name (fieldname, cu))
15923                         {
15924                           set_type_vptr_fieldno (type, i);
15925                           break;
15926                         }
15927                     }
15928
15929                   /* Complain if virtual function table field not found.  */
15930                   if (i < TYPE_N_BASECLASSES (t))
15931                     complaint (_("virtual function table pointer "
15932                                  "not found when defining class '%s'"),
15933                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
15934                 }
15935               else
15936                 {
15937                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15938                 }
15939             }
15940           else if (cu->producer
15941                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15942             {
15943               /* The IBM XLC compiler does not provide direct indication
15944                  of the containing type, but the vtable pointer is
15945                  always named __vfp.  */
15946
15947               int i;
15948
15949               for (i = TYPE_NFIELDS (type) - 1;
15950                    i >= TYPE_N_BASECLASSES (type);
15951                    --i)
15952                 {
15953                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15954                     {
15955                       set_type_vptr_fieldno (type, i);
15956                       set_type_vptr_basetype (type, type);
15957                       break;
15958                     }
15959                 }
15960             }
15961         }
15962
15963       /* Copy fi.typedef_field_list linked list elements content into the
15964          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15965       if (!fi.typedef_field_list.empty ())
15966         {
15967           int count = fi.typedef_field_list.size ();
15968
15969           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15970           TYPE_TYPEDEF_FIELD_ARRAY (type)
15971             = ((struct decl_field *)
15972                TYPE_ALLOC (type,
15973                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
15974           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
15975
15976           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
15977             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
15978         }
15979
15980       /* Copy fi.nested_types_list linked list elements content into the
15981          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
15982       if (!fi.nested_types_list.empty () && cu->language != language_ada)
15983         {
15984           int count = fi.nested_types_list.size ();
15985
15986           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15987           TYPE_NESTED_TYPES_ARRAY (type)
15988             = ((struct decl_field *)
15989                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
15990           TYPE_NESTED_TYPES_COUNT (type) = count;
15991
15992           for (int i = 0; i < fi.nested_types_list.size (); ++i)
15993             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
15994         }
15995     }
15996
15997   quirk_gcc_member_function_pointer (type, objfile);
15998   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
15999     cu->rust_unions.push_back (type);
16000
16001   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
16002      snapshots) has been known to create a die giving a declaration
16003      for a class that has, as a child, a die giving a definition for a
16004      nested class.  So we have to process our children even if the
16005      current die is a declaration.  Normally, of course, a declaration
16006      won't have any children at all.  */
16007
16008   child_die = die->child;
16009
16010   while (child_die != NULL && child_die->tag)
16011     {
16012       if (child_die->tag == DW_TAG_member
16013           || child_die->tag == DW_TAG_variable
16014           || child_die->tag == DW_TAG_inheritance
16015           || child_die->tag == DW_TAG_template_value_param
16016           || child_die->tag == DW_TAG_template_type_param)
16017         {
16018           /* Do nothing.  */
16019         }
16020       else
16021         process_die (child_die, cu);
16022
16023       child_die = sibling_die (child_die);
16024     }
16025
16026   /* Do not consider external references.  According to the DWARF standard,
16027      these DIEs are identified by the fact that they have no byte_size
16028      attribute, and a declaration attribute.  */
16029   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16030       || !die_is_declaration (die, cu))
16031     new_symbol (die, type, cu);
16032 }
16033
16034 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16035    update TYPE using some information only available in DIE's children.  */
16036
16037 static void
16038 update_enumeration_type_from_children (struct die_info *die,
16039                                        struct type *type,
16040                                        struct dwarf2_cu *cu)
16041 {
16042   struct die_info *child_die;
16043   int unsigned_enum = 1;
16044   int flag_enum = 1;
16045   ULONGEST mask = 0;
16046
16047   auto_obstack obstack;
16048
16049   for (child_die = die->child;
16050        child_die != NULL && child_die->tag;
16051        child_die = sibling_die (child_die))
16052     {
16053       struct attribute *attr;
16054       LONGEST value;
16055       const gdb_byte *bytes;
16056       struct dwarf2_locexpr_baton *baton;
16057       const char *name;
16058
16059       if (child_die->tag != DW_TAG_enumerator)
16060         continue;
16061
16062       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16063       if (attr == NULL)
16064         continue;
16065
16066       name = dwarf2_name (child_die, cu);
16067       if (name == NULL)
16068         name = "<anonymous enumerator>";
16069
16070       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16071                                &value, &bytes, &baton);
16072       if (value < 0)
16073         {
16074           unsigned_enum = 0;
16075           flag_enum = 0;
16076         }
16077       else if ((mask & value) != 0)
16078         flag_enum = 0;
16079       else
16080         mask |= value;
16081
16082       /* If we already know that the enum type is neither unsigned, nor
16083          a flag type, no need to look at the rest of the enumerates.  */
16084       if (!unsigned_enum && !flag_enum)
16085         break;
16086     }
16087
16088   if (unsigned_enum)
16089     TYPE_UNSIGNED (type) = 1;
16090   if (flag_enum)
16091     TYPE_FLAG_ENUM (type) = 1;
16092 }
16093
16094 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16095    complete the type's fields yet, or create any symbols.  */
16096
16097 static struct type *
16098 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16099 {
16100   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16101   struct type *type;
16102   struct attribute *attr;
16103   const char *name;
16104
16105   /* If the definition of this type lives in .debug_types, read that type.
16106      Don't follow DW_AT_specification though, that will take us back up
16107      the chain and we want to go down.  */
16108   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16109   if (attr)
16110     {
16111       type = get_DW_AT_signature_type (die, attr, cu);
16112
16113       /* The type's CU may not be the same as CU.
16114          Ensure TYPE is recorded with CU in die_type_hash.  */
16115       return set_die_type (die, type, cu);
16116     }
16117
16118   type = alloc_type (objfile);
16119
16120   TYPE_CODE (type) = TYPE_CODE_ENUM;
16121   name = dwarf2_full_name (NULL, die, cu);
16122   if (name != NULL)
16123     TYPE_NAME (type) = name;
16124
16125   attr = dwarf2_attr (die, DW_AT_type, cu);
16126   if (attr != NULL)
16127     {
16128       struct type *underlying_type = die_type (die, cu);
16129
16130       TYPE_TARGET_TYPE (type) = underlying_type;
16131     }
16132
16133   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16134   if (attr)
16135     {
16136       TYPE_LENGTH (type) = DW_UNSND (attr);
16137     }
16138   else
16139     {
16140       TYPE_LENGTH (type) = 0;
16141     }
16142
16143   maybe_set_alignment (cu, die, type);
16144
16145   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16146      declared as private in the package spec, and then defined only
16147      inside the package body.  Such types are known as Taft Amendment
16148      Types.  When another package uses such a type, an incomplete DIE
16149      may be generated by the compiler.  */
16150   if (die_is_declaration (die, cu))
16151     TYPE_STUB (type) = 1;
16152
16153   /* Finish the creation of this type by using the enum's children.
16154      We must call this even when the underlying type has been provided
16155      so that we can determine if we're looking at a "flag" enum.  */
16156   update_enumeration_type_from_children (die, type, cu);
16157
16158   /* If this type has an underlying type that is not a stub, then we
16159      may use its attributes.  We always use the "unsigned" attribute
16160      in this situation, because ordinarily we guess whether the type
16161      is unsigned -- but the guess can be wrong and the underlying type
16162      can tell us the reality.  However, we defer to a local size
16163      attribute if one exists, because this lets the compiler override
16164      the underlying type if needed.  */
16165   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16166     {
16167       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16168       if (TYPE_LENGTH (type) == 0)
16169         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16170       if (TYPE_RAW_ALIGN (type) == 0
16171           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16172         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16173     }
16174
16175   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16176
16177   return set_die_type (die, type, cu);
16178 }
16179
16180 /* Given a pointer to a die which begins an enumeration, process all
16181    the dies that define the members of the enumeration, and create the
16182    symbol for the enumeration type.
16183
16184    NOTE: We reverse the order of the element list.  */
16185
16186 static void
16187 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16188 {
16189   struct type *this_type;
16190
16191   this_type = get_die_type (die, cu);
16192   if (this_type == NULL)
16193     this_type = read_enumeration_type (die, cu);
16194
16195   if (die->child != NULL)
16196     {
16197       struct die_info *child_die;
16198       struct symbol *sym;
16199       struct field *fields = NULL;
16200       int num_fields = 0;
16201       const char *name;
16202
16203       child_die = die->child;
16204       while (child_die && child_die->tag)
16205         {
16206           if (child_die->tag != DW_TAG_enumerator)
16207             {
16208               process_die (child_die, cu);
16209             }
16210           else
16211             {
16212               name = dwarf2_name (child_die, cu);
16213               if (name)
16214                 {
16215                   sym = new_symbol (child_die, this_type, cu);
16216
16217                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16218                     {
16219                       fields = (struct field *)
16220                         xrealloc (fields,
16221                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16222                                   * sizeof (struct field));
16223                     }
16224
16225                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16226                   FIELD_TYPE (fields[num_fields]) = NULL;
16227                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16228                   FIELD_BITSIZE (fields[num_fields]) = 0;
16229
16230                   num_fields++;
16231                 }
16232             }
16233
16234           child_die = sibling_die (child_die);
16235         }
16236
16237       if (num_fields)
16238         {
16239           TYPE_NFIELDS (this_type) = num_fields;
16240           TYPE_FIELDS (this_type) = (struct field *)
16241             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16242           memcpy (TYPE_FIELDS (this_type), fields,
16243                   sizeof (struct field) * num_fields);
16244           xfree (fields);
16245         }
16246     }
16247
16248   /* If we are reading an enum from a .debug_types unit, and the enum
16249      is a declaration, and the enum is not the signatured type in the
16250      unit, then we do not want to add a symbol for it.  Adding a
16251      symbol would in some cases obscure the true definition of the
16252      enum, giving users an incomplete type when the definition is
16253      actually available.  Note that we do not want to do this for all
16254      enums which are just declarations, because C++0x allows forward
16255      enum declarations.  */
16256   if (cu->per_cu->is_debug_types
16257       && die_is_declaration (die, cu))
16258     {
16259       struct signatured_type *sig_type;
16260
16261       sig_type = (struct signatured_type *) cu->per_cu;
16262       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16263       if (sig_type->type_offset_in_section != die->sect_off)
16264         return;
16265     }
16266
16267   new_symbol (die, this_type, cu);
16268 }
16269
16270 /* Extract all information from a DW_TAG_array_type DIE and put it in
16271    the DIE's type field.  For now, this only handles one dimensional
16272    arrays.  */
16273
16274 static struct type *
16275 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16276 {
16277   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16278   struct die_info *child_die;
16279   struct type *type;
16280   struct type *element_type, *range_type, *index_type;
16281   struct attribute *attr;
16282   const char *name;
16283   struct dynamic_prop *byte_stride_prop = NULL;
16284   unsigned int bit_stride = 0;
16285
16286   element_type = die_type (die, cu);
16287
16288   /* The die_type call above may have already set the type for this DIE.  */
16289   type = get_die_type (die, cu);
16290   if (type)
16291     return type;
16292
16293   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16294   if (attr != NULL)
16295     {
16296       int stride_ok;
16297
16298       byte_stride_prop
16299         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16300       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16301       if (!stride_ok)
16302         {
16303           complaint (_("unable to read array DW_AT_byte_stride "
16304                        " - DIE at %s [in module %s]"),
16305                      sect_offset_str (die->sect_off),
16306                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16307           /* Ignore this attribute.  We will likely not be able to print
16308              arrays of this type correctly, but there is little we can do
16309              to help if we cannot read the attribute's value.  */
16310           byte_stride_prop = NULL;
16311         }
16312     }
16313
16314   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16315   if (attr != NULL)
16316     bit_stride = DW_UNSND (attr);
16317
16318   /* Irix 6.2 native cc creates array types without children for
16319      arrays with unspecified length.  */
16320   if (die->child == NULL)
16321     {
16322       index_type = objfile_type (objfile)->builtin_int;
16323       range_type = create_static_range_type (NULL, index_type, 0, -1);
16324       type = create_array_type_with_stride (NULL, element_type, range_type,
16325                                             byte_stride_prop, bit_stride);
16326       return set_die_type (die, type, cu);
16327     }
16328
16329   std::vector<struct type *> range_types;
16330   child_die = die->child;
16331   while (child_die && child_die->tag)
16332     {
16333       if (child_die->tag == DW_TAG_subrange_type)
16334         {
16335           struct type *child_type = read_type_die (child_die, cu);
16336
16337           if (child_type != NULL)
16338             {
16339               /* The range type was succesfully read.  Save it for the
16340                  array type creation.  */
16341               range_types.push_back (child_type);
16342             }
16343         }
16344       child_die = sibling_die (child_die);
16345     }
16346
16347   /* Dwarf2 dimensions are output from left to right, create the
16348      necessary array types in backwards order.  */
16349
16350   type = element_type;
16351
16352   if (read_array_order (die, cu) == DW_ORD_col_major)
16353     {
16354       int i = 0;
16355
16356       while (i < range_types.size ())
16357         type = create_array_type_with_stride (NULL, type, range_types[i++],
16358                                               byte_stride_prop, bit_stride);
16359     }
16360   else
16361     {
16362       size_t ndim = range_types.size ();
16363       while (ndim-- > 0)
16364         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16365                                               byte_stride_prop, bit_stride);
16366     }
16367
16368   /* Understand Dwarf2 support for vector types (like they occur on
16369      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16370      array type.  This is not part of the Dwarf2/3 standard yet, but a
16371      custom vendor extension.  The main difference between a regular
16372      array and the vector variant is that vectors are passed by value
16373      to functions.  */
16374   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16375   if (attr)
16376     make_vector_type (type);
16377
16378   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16379      implementation may choose to implement triple vectors using this
16380      attribute.  */
16381   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16382   if (attr)
16383     {
16384       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16385         TYPE_LENGTH (type) = DW_UNSND (attr);
16386       else
16387         complaint (_("DW_AT_byte_size for array type smaller "
16388                      "than the total size of elements"));
16389     }
16390
16391   name = dwarf2_name (die, cu);
16392   if (name)
16393     TYPE_NAME (type) = name;
16394
16395   maybe_set_alignment (cu, die, type);
16396
16397   /* Install the type in the die.  */
16398   set_die_type (die, type, cu);
16399
16400   /* set_die_type should be already done.  */
16401   set_descriptive_type (type, die, cu);
16402
16403   return type;
16404 }
16405
16406 static enum dwarf_array_dim_ordering
16407 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16408 {
16409   struct attribute *attr;
16410
16411   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16412
16413   if (attr)
16414     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16415
16416   /* GNU F77 is a special case, as at 08/2004 array type info is the
16417      opposite order to the dwarf2 specification, but data is still
16418      laid out as per normal fortran.
16419
16420      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16421      version checking.  */
16422
16423   if (cu->language == language_fortran
16424       && cu->producer && strstr (cu->producer, "GNU F77"))
16425     {
16426       return DW_ORD_row_major;
16427     }
16428
16429   switch (cu->language_defn->la_array_ordering)
16430     {
16431     case array_column_major:
16432       return DW_ORD_col_major;
16433     case array_row_major:
16434     default:
16435       return DW_ORD_row_major;
16436     };
16437 }
16438
16439 /* Extract all information from a DW_TAG_set_type DIE and put it in
16440    the DIE's type field.  */
16441
16442 static struct type *
16443 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16444 {
16445   struct type *domain_type, *set_type;
16446   struct attribute *attr;
16447
16448   domain_type = die_type (die, cu);
16449
16450   /* The die_type call above may have already set the type for this DIE.  */
16451   set_type = get_die_type (die, cu);
16452   if (set_type)
16453     return set_type;
16454
16455   set_type = create_set_type (NULL, domain_type);
16456
16457   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16458   if (attr)
16459     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16460
16461   maybe_set_alignment (cu, die, set_type);
16462
16463   return set_die_type (die, set_type, cu);
16464 }
16465
16466 /* A helper for read_common_block that creates a locexpr baton.
16467    SYM is the symbol which we are marking as computed.
16468    COMMON_DIE is the DIE for the common block.
16469    COMMON_LOC is the location expression attribute for the common
16470    block itself.
16471    MEMBER_LOC is the location expression attribute for the particular
16472    member of the common block that we are processing.
16473    CU is the CU from which the above come.  */
16474
16475 static void
16476 mark_common_block_symbol_computed (struct symbol *sym,
16477                                    struct die_info *common_die,
16478                                    struct attribute *common_loc,
16479                                    struct attribute *member_loc,
16480                                    struct dwarf2_cu *cu)
16481 {
16482   struct dwarf2_per_objfile *dwarf2_per_objfile
16483     = cu->per_cu->dwarf2_per_objfile;
16484   struct objfile *objfile = dwarf2_per_objfile->objfile;
16485   struct dwarf2_locexpr_baton *baton;
16486   gdb_byte *ptr;
16487   unsigned int cu_off;
16488   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16489   LONGEST offset = 0;
16490
16491   gdb_assert (common_loc && member_loc);
16492   gdb_assert (attr_form_is_block (common_loc));
16493   gdb_assert (attr_form_is_block (member_loc)
16494               || attr_form_is_constant (member_loc));
16495
16496   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16497   baton->per_cu = cu->per_cu;
16498   gdb_assert (baton->per_cu);
16499
16500   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16501
16502   if (attr_form_is_constant (member_loc))
16503     {
16504       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16505       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16506     }
16507   else
16508     baton->size += DW_BLOCK (member_loc)->size;
16509
16510   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16511   baton->data = ptr;
16512
16513   *ptr++ = DW_OP_call4;
16514   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16515   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16516   ptr += 4;
16517
16518   if (attr_form_is_constant (member_loc))
16519     {
16520       *ptr++ = DW_OP_addr;
16521       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16522       ptr += cu->header.addr_size;
16523     }
16524   else
16525     {
16526       /* We have to copy the data here, because DW_OP_call4 will only
16527          use a DW_AT_location attribute.  */
16528       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16529       ptr += DW_BLOCK (member_loc)->size;
16530     }
16531
16532   *ptr++ = DW_OP_plus;
16533   gdb_assert (ptr - baton->data == baton->size);
16534
16535   SYMBOL_LOCATION_BATON (sym) = baton;
16536   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16537 }
16538
16539 /* Create appropriate locally-scoped variables for all the
16540    DW_TAG_common_block entries.  Also create a struct common_block
16541    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16542    is used to sepate the common blocks name namespace from regular
16543    variable names.  */
16544
16545 static void
16546 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16547 {
16548   struct attribute *attr;
16549
16550   attr = dwarf2_attr (die, DW_AT_location, cu);
16551   if (attr)
16552     {
16553       /* Support the .debug_loc offsets.  */
16554       if (attr_form_is_block (attr))
16555         {
16556           /* Ok.  */
16557         }
16558       else if (attr_form_is_section_offset (attr))
16559         {
16560           dwarf2_complex_location_expr_complaint ();
16561           attr = NULL;
16562         }
16563       else
16564         {
16565           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16566                                                  "common block member");
16567           attr = NULL;
16568         }
16569     }
16570
16571   if (die->child != NULL)
16572     {
16573       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16574       struct die_info *child_die;
16575       size_t n_entries = 0, size;
16576       struct common_block *common_block;
16577       struct symbol *sym;
16578
16579       for (child_die = die->child;
16580            child_die && child_die->tag;
16581            child_die = sibling_die (child_die))
16582         ++n_entries;
16583
16584       size = (sizeof (struct common_block)
16585               + (n_entries - 1) * sizeof (struct symbol *));
16586       common_block
16587         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16588                                                  size);
16589       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16590       common_block->n_entries = 0;
16591
16592       for (child_die = die->child;
16593            child_die && child_die->tag;
16594            child_die = sibling_die (child_die))
16595         {
16596           /* Create the symbol in the DW_TAG_common_block block in the current
16597              symbol scope.  */
16598           sym = new_symbol (child_die, NULL, cu);
16599           if (sym != NULL)
16600             {
16601               struct attribute *member_loc;
16602
16603               common_block->contents[common_block->n_entries++] = sym;
16604
16605               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16606                                         cu);
16607               if (member_loc)
16608                 {
16609                   /* GDB has handled this for a long time, but it is
16610                      not specified by DWARF.  It seems to have been
16611                      emitted by gfortran at least as recently as:
16612                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16613                   complaint (_("Variable in common block has "
16614                                "DW_AT_data_member_location "
16615                                "- DIE at %s [in module %s]"),
16616                                sect_offset_str (child_die->sect_off),
16617                              objfile_name (objfile));
16618
16619                   if (attr_form_is_section_offset (member_loc))
16620                     dwarf2_complex_location_expr_complaint ();
16621                   else if (attr_form_is_constant (member_loc)
16622                            || attr_form_is_block (member_loc))
16623                     {
16624                       if (attr)
16625                         mark_common_block_symbol_computed (sym, die, attr,
16626                                                            member_loc, cu);
16627                     }
16628                   else
16629                     dwarf2_complex_location_expr_complaint ();
16630                 }
16631             }
16632         }
16633
16634       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16635       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16636     }
16637 }
16638
16639 /* Create a type for a C++ namespace.  */
16640
16641 static struct type *
16642 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16643 {
16644   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16645   const char *previous_prefix, *name;
16646   int is_anonymous;
16647   struct type *type;
16648
16649   /* For extensions, reuse the type of the original namespace.  */
16650   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16651     {
16652       struct die_info *ext_die;
16653       struct dwarf2_cu *ext_cu = cu;
16654
16655       ext_die = dwarf2_extension (die, &ext_cu);
16656       type = read_type_die (ext_die, ext_cu);
16657
16658       /* EXT_CU may not be the same as CU.
16659          Ensure TYPE is recorded with CU in die_type_hash.  */
16660       return set_die_type (die, type, cu);
16661     }
16662
16663   name = namespace_name (die, &is_anonymous, cu);
16664
16665   /* Now build the name of the current namespace.  */
16666
16667   previous_prefix = determine_prefix (die, cu);
16668   if (previous_prefix[0] != '\0')
16669     name = typename_concat (&objfile->objfile_obstack,
16670                             previous_prefix, name, 0, cu);
16671
16672   /* Create the type.  */
16673   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16674
16675   return set_die_type (die, type, cu);
16676 }
16677
16678 /* Read a namespace scope.  */
16679
16680 static void
16681 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16682 {
16683   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16684   int is_anonymous;
16685
16686   /* Add a symbol associated to this if we haven't seen the namespace
16687      before.  Also, add a using directive if it's an anonymous
16688      namespace.  */
16689
16690   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16691     {
16692       struct type *type;
16693
16694       type = read_type_die (die, cu);
16695       new_symbol (die, type, cu);
16696
16697       namespace_name (die, &is_anonymous, cu);
16698       if (is_anonymous)
16699         {
16700           const char *previous_prefix = determine_prefix (die, cu);
16701
16702           std::vector<const char *> excludes;
16703           add_using_directive (using_directives (cu->language),
16704                                previous_prefix, TYPE_NAME (type), NULL,
16705                                NULL, excludes, 0, &objfile->objfile_obstack);
16706         }
16707     }
16708
16709   if (die->child != NULL)
16710     {
16711       struct die_info *child_die = die->child;
16712
16713       while (child_die && child_die->tag)
16714         {
16715           process_die (child_die, cu);
16716           child_die = sibling_die (child_die);
16717         }
16718     }
16719 }
16720
16721 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16722    imported module.  Still we need that type as local Fortran "use ... only"
16723    declaration imports depend on the created type in determine_prefix.  */
16724
16725 static struct type *
16726 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16727 {
16728   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16729   const char *module_name;
16730   struct type *type;
16731
16732   module_name = dwarf2_name (die, cu);
16733   if (!module_name)
16734     complaint (_("DW_TAG_module has no name, offset %s"),
16735                sect_offset_str (die->sect_off));
16736   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16737
16738   return set_die_type (die, type, cu);
16739 }
16740
16741 /* Read a Fortran module.  */
16742
16743 static void
16744 read_module (struct die_info *die, struct dwarf2_cu *cu)
16745 {
16746   struct die_info *child_die = die->child;
16747   struct type *type;
16748
16749   type = read_type_die (die, cu);
16750   new_symbol (die, type, cu);
16751
16752   while (child_die && child_die->tag)
16753     {
16754       process_die (child_die, cu);
16755       child_die = sibling_die (child_die);
16756     }
16757 }
16758
16759 /* Return the name of the namespace represented by DIE.  Set
16760    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16761    namespace.  */
16762
16763 static const char *
16764 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16765 {
16766   struct die_info *current_die;
16767   const char *name = NULL;
16768
16769   /* Loop through the extensions until we find a name.  */
16770
16771   for (current_die = die;
16772        current_die != NULL;
16773        current_die = dwarf2_extension (die, &cu))
16774     {
16775       /* We don't use dwarf2_name here so that we can detect the absence
16776          of a name -> anonymous namespace.  */
16777       name = dwarf2_string_attr (die, DW_AT_name, cu);
16778
16779       if (name != NULL)
16780         break;
16781     }
16782
16783   /* Is it an anonymous namespace?  */
16784
16785   *is_anonymous = (name == NULL);
16786   if (*is_anonymous)
16787     name = CP_ANONYMOUS_NAMESPACE_STR;
16788
16789   return name;
16790 }
16791
16792 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16793    the user defined type vector.  */
16794
16795 static struct type *
16796 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16797 {
16798   struct gdbarch *gdbarch
16799     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16800   struct comp_unit_head *cu_header = &cu->header;
16801   struct type *type;
16802   struct attribute *attr_byte_size;
16803   struct attribute *attr_address_class;
16804   int byte_size, addr_class;
16805   struct type *target_type;
16806
16807   target_type = die_type (die, cu);
16808
16809   /* The die_type call above may have already set the type for this DIE.  */
16810   type = get_die_type (die, cu);
16811   if (type)
16812     return type;
16813
16814   type = lookup_pointer_type (target_type);
16815
16816   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16817   if (attr_byte_size)
16818     byte_size = DW_UNSND (attr_byte_size);
16819   else
16820     byte_size = cu_header->addr_size;
16821
16822   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16823   if (attr_address_class)
16824     addr_class = DW_UNSND (attr_address_class);
16825   else
16826     addr_class = DW_ADDR_none;
16827
16828   ULONGEST alignment = get_alignment (cu, die);
16829
16830   /* If the pointer size, alignment, or address class is different
16831      than the default, create a type variant marked as such and set
16832      the length accordingly.  */
16833   if (TYPE_LENGTH (type) != byte_size
16834       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16835           && alignment != TYPE_RAW_ALIGN (type))
16836       || addr_class != DW_ADDR_none)
16837     {
16838       if (gdbarch_address_class_type_flags_p (gdbarch))
16839         {
16840           int type_flags;
16841
16842           type_flags = gdbarch_address_class_type_flags
16843                          (gdbarch, byte_size, addr_class);
16844           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16845                       == 0);
16846           type = make_type_with_address_space (type, type_flags);
16847         }
16848       else if (TYPE_LENGTH (type) != byte_size)
16849         {
16850           complaint (_("invalid pointer size %d"), byte_size);
16851         }
16852       else if (TYPE_RAW_ALIGN (type) != alignment)
16853         {
16854           complaint (_("Invalid DW_AT_alignment"
16855                        " - DIE at %s [in module %s]"),
16856                      sect_offset_str (die->sect_off),
16857                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16858         }
16859       else
16860         {
16861           /* Should we also complain about unhandled address classes?  */
16862         }
16863     }
16864
16865   TYPE_LENGTH (type) = byte_size;
16866   set_type_align (type, alignment);
16867   return set_die_type (die, type, cu);
16868 }
16869
16870 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16871    the user defined type vector.  */
16872
16873 static struct type *
16874 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16875 {
16876   struct type *type;
16877   struct type *to_type;
16878   struct type *domain;
16879
16880   to_type = die_type (die, cu);
16881   domain = die_containing_type (die, cu);
16882
16883   /* The calls above may have already set the type for this DIE.  */
16884   type = get_die_type (die, cu);
16885   if (type)
16886     return type;
16887
16888   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16889     type = lookup_methodptr_type (to_type);
16890   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16891     {
16892       struct type *new_type
16893         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16894
16895       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16896                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16897                             TYPE_VARARGS (to_type));
16898       type = lookup_methodptr_type (new_type);
16899     }
16900   else
16901     type = lookup_memberptr_type (to_type, domain);
16902
16903   return set_die_type (die, type, cu);
16904 }
16905
16906 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16907    the user defined type vector.  */
16908
16909 static struct type *
16910 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16911                           enum type_code refcode)
16912 {
16913   struct comp_unit_head *cu_header = &cu->header;
16914   struct type *type, *target_type;
16915   struct attribute *attr;
16916
16917   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16918
16919   target_type = die_type (die, cu);
16920
16921   /* The die_type call above may have already set the type for this DIE.  */
16922   type = get_die_type (die, cu);
16923   if (type)
16924     return type;
16925
16926   type = lookup_reference_type (target_type, refcode);
16927   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16928   if (attr)
16929     {
16930       TYPE_LENGTH (type) = DW_UNSND (attr);
16931     }
16932   else
16933     {
16934       TYPE_LENGTH (type) = cu_header->addr_size;
16935     }
16936   maybe_set_alignment (cu, die, type);
16937   return set_die_type (die, type, cu);
16938 }
16939
16940 /* Add the given cv-qualifiers to the element type of the array.  GCC
16941    outputs DWARF type qualifiers that apply to an array, not the
16942    element type.  But GDB relies on the array element type to carry
16943    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16944    specification.  */
16945
16946 static struct type *
16947 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16948                    struct type *base_type, int cnst, int voltl)
16949 {
16950   struct type *el_type, *inner_array;
16951
16952   base_type = copy_type (base_type);
16953   inner_array = base_type;
16954
16955   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16956     {
16957       TYPE_TARGET_TYPE (inner_array) =
16958         copy_type (TYPE_TARGET_TYPE (inner_array));
16959       inner_array = TYPE_TARGET_TYPE (inner_array);
16960     }
16961
16962   el_type = TYPE_TARGET_TYPE (inner_array);
16963   cnst |= TYPE_CONST (el_type);
16964   voltl |= TYPE_VOLATILE (el_type);
16965   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16966
16967   return set_die_type (die, base_type, cu);
16968 }
16969
16970 static struct type *
16971 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
16972 {
16973   struct type *base_type, *cv_type;
16974
16975   base_type = die_type (die, cu);
16976
16977   /* The die_type call above may have already set the type for this DIE.  */
16978   cv_type = get_die_type (die, cu);
16979   if (cv_type)
16980     return cv_type;
16981
16982   /* In case the const qualifier is applied to an array type, the element type
16983      is so qualified, not the array type (section 6.7.3 of C99).  */
16984   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16985     return add_array_cv_type (die, cu, base_type, 1, 0);
16986
16987   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
16988   return set_die_type (die, cv_type, cu);
16989 }
16990
16991 static struct type *
16992 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
16993 {
16994   struct type *base_type, *cv_type;
16995
16996   base_type = die_type (die, cu);
16997
16998   /* The die_type call above may have already set the type for this DIE.  */
16999   cv_type = get_die_type (die, cu);
17000   if (cv_type)
17001     return cv_type;
17002
17003   /* In case the volatile qualifier is applied to an array type, the
17004      element type is so qualified, not the array type (section 6.7.3
17005      of C99).  */
17006   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17007     return add_array_cv_type (die, cu, base_type, 0, 1);
17008
17009   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17010   return set_die_type (die, cv_type, cu);
17011 }
17012
17013 /* Handle DW_TAG_restrict_type.  */
17014
17015 static struct type *
17016 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17017 {
17018   struct type *base_type, *cv_type;
17019
17020   base_type = die_type (die, cu);
17021
17022   /* The die_type call above may have already set the type for this DIE.  */
17023   cv_type = get_die_type (die, cu);
17024   if (cv_type)
17025     return cv_type;
17026
17027   cv_type = make_restrict_type (base_type);
17028   return set_die_type (die, cv_type, cu);
17029 }
17030
17031 /* Handle DW_TAG_atomic_type.  */
17032
17033 static struct type *
17034 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17035 {
17036   struct type *base_type, *cv_type;
17037
17038   base_type = die_type (die, cu);
17039
17040   /* The die_type call above may have already set the type for this DIE.  */
17041   cv_type = get_die_type (die, cu);
17042   if (cv_type)
17043     return cv_type;
17044
17045   cv_type = make_atomic_type (base_type);
17046   return set_die_type (die, cv_type, cu);
17047 }
17048
17049 /* Extract all information from a DW_TAG_string_type DIE and add to
17050    the user defined type vector.  It isn't really a user defined type,
17051    but it behaves like one, with other DIE's using an AT_user_def_type
17052    attribute to reference it.  */
17053
17054 static struct type *
17055 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17056 {
17057   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17058   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17059   struct type *type, *range_type, *index_type, *char_type;
17060   struct attribute *attr;
17061   unsigned int length;
17062
17063   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17064   if (attr)
17065     {
17066       length = DW_UNSND (attr);
17067     }
17068   else
17069     {
17070       /* Check for the DW_AT_byte_size attribute.  */
17071       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17072       if (attr)
17073         {
17074           length = DW_UNSND (attr);
17075         }
17076       else
17077         {
17078           length = 1;
17079         }
17080     }
17081
17082   index_type = objfile_type (objfile)->builtin_int;
17083   range_type = create_static_range_type (NULL, index_type, 1, length);
17084   char_type = language_string_char_type (cu->language_defn, gdbarch);
17085   type = create_string_type (NULL, char_type, range_type);
17086
17087   return set_die_type (die, type, cu);
17088 }
17089
17090 /* Assuming that DIE corresponds to a function, returns nonzero
17091    if the function is prototyped.  */
17092
17093 static int
17094 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17095 {
17096   struct attribute *attr;
17097
17098   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17099   if (attr && (DW_UNSND (attr) != 0))
17100     return 1;
17101
17102   /* The DWARF standard implies that the DW_AT_prototyped attribute
17103      is only meaninful for C, but the concept also extends to other
17104      languages that allow unprototyped functions (Eg: Objective C).
17105      For all other languages, assume that functions are always
17106      prototyped.  */
17107   if (cu->language != language_c
17108       && cu->language != language_objc
17109       && cu->language != language_opencl)
17110     return 1;
17111
17112   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17113      prototyped and unprototyped functions; default to prototyped,
17114      since that is more common in modern code (and RealView warns
17115      about unprototyped functions).  */
17116   if (producer_is_realview (cu->producer))
17117     return 1;
17118
17119   return 0;
17120 }
17121
17122 /* Handle DIES due to C code like:
17123
17124    struct foo
17125    {
17126    int (*funcp)(int a, long l);
17127    int b;
17128    };
17129
17130    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17131
17132 static struct type *
17133 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17134 {
17135   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17136   struct type *type;            /* Type that this function returns.  */
17137   struct type *ftype;           /* Function that returns above type.  */
17138   struct attribute *attr;
17139
17140   type = die_type (die, cu);
17141
17142   /* The die_type call above may have already set the type for this DIE.  */
17143   ftype = get_die_type (die, cu);
17144   if (ftype)
17145     return ftype;
17146
17147   ftype = lookup_function_type (type);
17148
17149   if (prototyped_function_p (die, cu))
17150     TYPE_PROTOTYPED (ftype) = 1;
17151
17152   /* Store the calling convention in the type if it's available in
17153      the subroutine die.  Otherwise set the calling convention to
17154      the default value DW_CC_normal.  */
17155   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17156   if (attr)
17157     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17158   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17159     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17160   else
17161     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17162
17163   /* Record whether the function returns normally to its caller or not
17164      if the DWARF producer set that information.  */
17165   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17166   if (attr && (DW_UNSND (attr) != 0))
17167     TYPE_NO_RETURN (ftype) = 1;
17168
17169   /* We need to add the subroutine type to the die immediately so
17170      we don't infinitely recurse when dealing with parameters
17171      declared as the same subroutine type.  */
17172   set_die_type (die, ftype, cu);
17173
17174   if (die->child != NULL)
17175     {
17176       struct type *void_type = objfile_type (objfile)->builtin_void;
17177       struct die_info *child_die;
17178       int nparams, iparams;
17179
17180       /* Count the number of parameters.
17181          FIXME: GDB currently ignores vararg functions, but knows about
17182          vararg member functions.  */
17183       nparams = 0;
17184       child_die = die->child;
17185       while (child_die && child_die->tag)
17186         {
17187           if (child_die->tag == DW_TAG_formal_parameter)
17188             nparams++;
17189           else if (child_die->tag == DW_TAG_unspecified_parameters)
17190             TYPE_VARARGS (ftype) = 1;
17191           child_die = sibling_die (child_die);
17192         }
17193
17194       /* Allocate storage for parameters and fill them in.  */
17195       TYPE_NFIELDS (ftype) = nparams;
17196       TYPE_FIELDS (ftype) = (struct field *)
17197         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17198
17199       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17200          even if we error out during the parameters reading below.  */
17201       for (iparams = 0; iparams < nparams; iparams++)
17202         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17203
17204       iparams = 0;
17205       child_die = die->child;
17206       while (child_die && child_die->tag)
17207         {
17208           if (child_die->tag == DW_TAG_formal_parameter)
17209             {
17210               struct type *arg_type;
17211
17212               /* DWARF version 2 has no clean way to discern C++
17213                  static and non-static member functions.  G++ helps
17214                  GDB by marking the first parameter for non-static
17215                  member functions (which is the this pointer) as
17216                  artificial.  We pass this information to
17217                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17218
17219                  DWARF version 3 added DW_AT_object_pointer, which GCC
17220                  4.5 does not yet generate.  */
17221               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17222               if (attr)
17223                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17224               else
17225                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17226               arg_type = die_type (child_die, cu);
17227
17228               /* RealView does not mark THIS as const, which the testsuite
17229                  expects.  GCC marks THIS as const in method definitions,
17230                  but not in the class specifications (GCC PR 43053).  */
17231               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17232                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17233                 {
17234                   int is_this = 0;
17235                   struct dwarf2_cu *arg_cu = cu;
17236                   const char *name = dwarf2_name (child_die, cu);
17237
17238                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17239                   if (attr)
17240                     {
17241                       /* If the compiler emits this, use it.  */
17242                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17243                         is_this = 1;
17244                     }
17245                   else if (name && strcmp (name, "this") == 0)
17246                     /* Function definitions will have the argument names.  */
17247                     is_this = 1;
17248                   else if (name == NULL && iparams == 0)
17249                     /* Declarations may not have the names, so like
17250                        elsewhere in GDB, assume an artificial first
17251                        argument is "this".  */
17252                     is_this = 1;
17253
17254                   if (is_this)
17255                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17256                                              arg_type, 0);
17257                 }
17258
17259               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17260               iparams++;
17261             }
17262           child_die = sibling_die (child_die);
17263         }
17264     }
17265
17266   return ftype;
17267 }
17268
17269 static struct type *
17270 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17271 {
17272   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17273   const char *name = NULL;
17274   struct type *this_type, *target_type;
17275
17276   name = dwarf2_full_name (NULL, die, cu);
17277   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17278   TYPE_TARGET_STUB (this_type) = 1;
17279   set_die_type (die, this_type, cu);
17280   target_type = die_type (die, cu);
17281   if (target_type != this_type)
17282     TYPE_TARGET_TYPE (this_type) = target_type;
17283   else
17284     {
17285       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17286          spec and cause infinite loops in GDB.  */
17287       complaint (_("Self-referential DW_TAG_typedef "
17288                    "- DIE at %s [in module %s]"),
17289                  sect_offset_str (die->sect_off), objfile_name (objfile));
17290       TYPE_TARGET_TYPE (this_type) = NULL;
17291     }
17292   return this_type;
17293 }
17294
17295 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17296    (which may be different from NAME) to the architecture back-end to allow
17297    it to guess the correct format if necessary.  */
17298
17299 static struct type *
17300 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17301                         const char *name_hint)
17302 {
17303   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17304   const struct floatformat **format;
17305   struct type *type;
17306
17307   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17308   if (format)
17309     type = init_float_type (objfile, bits, name, format);
17310   else
17311     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17312
17313   return type;
17314 }
17315
17316 /* Find a representation of a given base type and install
17317    it in the TYPE field of the die.  */
17318
17319 static struct type *
17320 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17321 {
17322   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17323   struct type *type;
17324   struct attribute *attr;
17325   int encoding = 0, bits = 0;
17326   const char *name;
17327
17328   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17329   if (attr)
17330     {
17331       encoding = DW_UNSND (attr);
17332     }
17333   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17334   if (attr)
17335     {
17336       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17337     }
17338   name = dwarf2_name (die, cu);
17339   if (!name)
17340     {
17341       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17342     }
17343
17344   switch (encoding)
17345     {
17346       case DW_ATE_address:
17347         /* Turn DW_ATE_address into a void * pointer.  */
17348         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17349         type = init_pointer_type (objfile, bits, name, type);
17350         break;
17351       case DW_ATE_boolean:
17352         type = init_boolean_type (objfile, bits, 1, name);
17353         break;
17354       case DW_ATE_complex_float:
17355         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17356         type = init_complex_type (objfile, name, type);
17357         break;
17358       case DW_ATE_decimal_float:
17359         type = init_decfloat_type (objfile, bits, name);
17360         break;
17361       case DW_ATE_float:
17362         type = dwarf2_init_float_type (objfile, bits, name, name);
17363         break;
17364       case DW_ATE_signed:
17365         type = init_integer_type (objfile, bits, 0, name);
17366         break;
17367       case DW_ATE_unsigned:
17368         if (cu->language == language_fortran
17369             && name
17370             && startswith (name, "character("))
17371           type = init_character_type (objfile, bits, 1, name);
17372         else
17373           type = init_integer_type (objfile, bits, 1, name);
17374         break;
17375       case DW_ATE_signed_char:
17376         if (cu->language == language_ada || cu->language == language_m2
17377             || cu->language == language_pascal
17378             || cu->language == language_fortran)
17379           type = init_character_type (objfile, bits, 0, name);
17380         else
17381           type = init_integer_type (objfile, bits, 0, name);
17382         break;
17383       case DW_ATE_unsigned_char:
17384         if (cu->language == language_ada || cu->language == language_m2
17385             || cu->language == language_pascal
17386             || cu->language == language_fortran
17387             || cu->language == language_rust)
17388           type = init_character_type (objfile, bits, 1, name);
17389         else
17390           type = init_integer_type (objfile, bits, 1, name);
17391         break;
17392       case DW_ATE_UTF:
17393         {
17394           gdbarch *arch = get_objfile_arch (objfile);
17395
17396           if (bits == 16)
17397             type = builtin_type (arch)->builtin_char16;
17398           else if (bits == 32)
17399             type = builtin_type (arch)->builtin_char32;
17400           else
17401             {
17402               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17403                          bits);
17404               type = init_integer_type (objfile, bits, 1, name);
17405             }
17406           return set_die_type (die, type, cu);
17407         }
17408         break;
17409
17410       default:
17411         complaint (_("unsupported DW_AT_encoding: '%s'"),
17412                    dwarf_type_encoding_name (encoding));
17413         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17414         break;
17415     }
17416
17417   if (name && strcmp (name, "char") == 0)
17418     TYPE_NOSIGN (type) = 1;
17419
17420   maybe_set_alignment (cu, die, type);
17421
17422   return set_die_type (die, type, cu);
17423 }
17424
17425 /* Parse dwarf attribute if it's a block, reference or constant and put the
17426    resulting value of the attribute into struct bound_prop.
17427    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17428
17429 static int
17430 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17431                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17432 {
17433   struct dwarf2_property_baton *baton;
17434   struct obstack *obstack
17435     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17436
17437   if (attr == NULL || prop == NULL)
17438     return 0;
17439
17440   if (attr_form_is_block (attr))
17441     {
17442       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17443       baton->referenced_type = NULL;
17444       baton->locexpr.per_cu = cu->per_cu;
17445       baton->locexpr.size = DW_BLOCK (attr)->size;
17446       baton->locexpr.data = DW_BLOCK (attr)->data;
17447       prop->data.baton = baton;
17448       prop->kind = PROP_LOCEXPR;
17449       gdb_assert (prop->data.baton != NULL);
17450     }
17451   else if (attr_form_is_ref (attr))
17452     {
17453       struct dwarf2_cu *target_cu = cu;
17454       struct die_info *target_die;
17455       struct attribute *target_attr;
17456
17457       target_die = follow_die_ref (die, attr, &target_cu);
17458       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17459       if (target_attr == NULL)
17460         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17461                                    target_cu);
17462       if (target_attr == NULL)
17463         return 0;
17464
17465       switch (target_attr->name)
17466         {
17467           case DW_AT_location:
17468             if (attr_form_is_section_offset (target_attr))
17469               {
17470                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17471                 baton->referenced_type = die_type (target_die, target_cu);
17472                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17473                 prop->data.baton = baton;
17474                 prop->kind = PROP_LOCLIST;
17475                 gdb_assert (prop->data.baton != NULL);
17476               }
17477             else if (attr_form_is_block (target_attr))
17478               {
17479                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17480                 baton->referenced_type = die_type (target_die, target_cu);
17481                 baton->locexpr.per_cu = cu->per_cu;
17482                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17483                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17484                 prop->data.baton = baton;
17485                 prop->kind = PROP_LOCEXPR;
17486                 gdb_assert (prop->data.baton != NULL);
17487               }
17488             else
17489               {
17490                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17491                                                        "dynamic property");
17492                 return 0;
17493               }
17494             break;
17495           case DW_AT_data_member_location:
17496             {
17497               LONGEST offset;
17498
17499               if (!handle_data_member_location (target_die, target_cu,
17500                                                 &offset))
17501                 return 0;
17502
17503               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17504               baton->referenced_type = read_type_die (target_die->parent,
17505                                                       target_cu);
17506               baton->offset_info.offset = offset;
17507               baton->offset_info.type = die_type (target_die, target_cu);
17508               prop->data.baton = baton;
17509               prop->kind = PROP_ADDR_OFFSET;
17510               break;
17511             }
17512         }
17513     }
17514   else if (attr_form_is_constant (attr))
17515     {
17516       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17517       prop->kind = PROP_CONST;
17518     }
17519   else
17520     {
17521       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17522                                              dwarf2_name (die, cu));
17523       return 0;
17524     }
17525
17526   return 1;
17527 }
17528
17529 /* Read the given DW_AT_subrange DIE.  */
17530
17531 static struct type *
17532 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17533 {
17534   struct type *base_type, *orig_base_type;
17535   struct type *range_type;
17536   struct attribute *attr;
17537   struct dynamic_prop low, high;
17538   int low_default_is_valid;
17539   int high_bound_is_count = 0;
17540   const char *name;
17541   LONGEST negative_mask;
17542
17543   orig_base_type = die_type (die, cu);
17544   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17545      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17546      creating the range type, but we use the result of check_typedef
17547      when examining properties of the type.  */
17548   base_type = check_typedef (orig_base_type);
17549
17550   /* The die_type call above may have already set the type for this DIE.  */
17551   range_type = get_die_type (die, cu);
17552   if (range_type)
17553     return range_type;
17554
17555   low.kind = PROP_CONST;
17556   high.kind = PROP_CONST;
17557   high.data.const_val = 0;
17558
17559   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17560      omitting DW_AT_lower_bound.  */
17561   switch (cu->language)
17562     {
17563     case language_c:
17564     case language_cplus:
17565       low.data.const_val = 0;
17566       low_default_is_valid = 1;
17567       break;
17568     case language_fortran:
17569       low.data.const_val = 1;
17570       low_default_is_valid = 1;
17571       break;
17572     case language_d:
17573     case language_objc:
17574     case language_rust:
17575       low.data.const_val = 0;
17576       low_default_is_valid = (cu->header.version >= 4);
17577       break;
17578     case language_ada:
17579     case language_m2:
17580     case language_pascal:
17581       low.data.const_val = 1;
17582       low_default_is_valid = (cu->header.version >= 4);
17583       break;
17584     default:
17585       low.data.const_val = 0;
17586       low_default_is_valid = 0;
17587       break;
17588     }
17589
17590   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17591   if (attr)
17592     attr_to_dynamic_prop (attr, die, cu, &low);
17593   else if (!low_default_is_valid)
17594     complaint (_("Missing DW_AT_lower_bound "
17595                                       "- DIE at %s [in module %s]"),
17596                sect_offset_str (die->sect_off),
17597                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17598
17599   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17600   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17601     {
17602       attr = dwarf2_attr (die, DW_AT_count, cu);
17603       if (attr_to_dynamic_prop (attr, die, cu, &high))
17604         {
17605           /* If bounds are constant do the final calculation here.  */
17606           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17607             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17608           else
17609             high_bound_is_count = 1;
17610         }
17611     }
17612
17613   /* Dwarf-2 specifications explicitly allows to create subrange types
17614      without specifying a base type.
17615      In that case, the base type must be set to the type of
17616      the lower bound, upper bound or count, in that order, if any of these
17617      three attributes references an object that has a type.
17618      If no base type is found, the Dwarf-2 specifications say that
17619      a signed integer type of size equal to the size of an address should
17620      be used.
17621      For the following C code: `extern char gdb_int [];'
17622      GCC produces an empty range DIE.
17623      FIXME: muller/2010-05-28: Possible references to object for low bound,
17624      high bound or count are not yet handled by this code.  */
17625   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17626     {
17627       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17628       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17629       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17630       struct type *int_type = objfile_type (objfile)->builtin_int;
17631
17632       /* Test "int", "long int", and "long long int" objfile types,
17633          and select the first one having a size above or equal to the
17634          architecture address size.  */
17635       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17636         base_type = int_type;
17637       else
17638         {
17639           int_type = objfile_type (objfile)->builtin_long;
17640           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17641             base_type = int_type;
17642           else
17643             {
17644               int_type = objfile_type (objfile)->builtin_long_long;
17645               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17646                 base_type = int_type;
17647             }
17648         }
17649     }
17650
17651   /* Normally, the DWARF producers are expected to use a signed
17652      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17653      But this is unfortunately not always the case, as witnessed
17654      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17655      is used instead.  To work around that ambiguity, we treat
17656      the bounds as signed, and thus sign-extend their values, when
17657      the base type is signed.  */
17658   negative_mask =
17659     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17660   if (low.kind == PROP_CONST
17661       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17662     low.data.const_val |= negative_mask;
17663   if (high.kind == PROP_CONST
17664       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17665     high.data.const_val |= negative_mask;
17666
17667   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17668
17669   if (high_bound_is_count)
17670     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17671
17672   /* Ada expects an empty array on no boundary attributes.  */
17673   if (attr == NULL && cu->language != language_ada)
17674     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17675
17676   name = dwarf2_name (die, cu);
17677   if (name)
17678     TYPE_NAME (range_type) = name;
17679
17680   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17681   if (attr)
17682     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17683
17684   maybe_set_alignment (cu, die, range_type);
17685
17686   set_die_type (die, range_type, cu);
17687
17688   /* set_die_type should be already done.  */
17689   set_descriptive_type (range_type, die, cu);
17690
17691   return range_type;
17692 }
17693
17694 static struct type *
17695 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17696 {
17697   struct type *type;
17698
17699   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17700                     NULL);
17701   TYPE_NAME (type) = dwarf2_name (die, cu);
17702
17703   /* In Ada, an unspecified type is typically used when the description
17704      of the type is defered to a different unit.  When encountering
17705      such a type, we treat it as a stub, and try to resolve it later on,
17706      when needed.  */
17707   if (cu->language == language_ada)
17708     TYPE_STUB (type) = 1;
17709
17710   return set_die_type (die, type, cu);
17711 }
17712
17713 /* Read a single die and all its descendents.  Set the die's sibling
17714    field to NULL; set other fields in the die correctly, and set all
17715    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17716    location of the info_ptr after reading all of those dies.  PARENT
17717    is the parent of the die in question.  */
17718
17719 static struct die_info *
17720 read_die_and_children (const struct die_reader_specs *reader,
17721                        const gdb_byte *info_ptr,
17722                        const gdb_byte **new_info_ptr,
17723                        struct die_info *parent)
17724 {
17725   struct die_info *die;
17726   const gdb_byte *cur_ptr;
17727   int has_children;
17728
17729   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17730   if (die == NULL)
17731     {
17732       *new_info_ptr = cur_ptr;
17733       return NULL;
17734     }
17735   store_in_ref_table (die, reader->cu);
17736
17737   if (has_children)
17738     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17739   else
17740     {
17741       die->child = NULL;
17742       *new_info_ptr = cur_ptr;
17743     }
17744
17745   die->sibling = NULL;
17746   die->parent = parent;
17747   return die;
17748 }
17749
17750 /* Read a die, all of its descendents, and all of its siblings; set
17751    all of the fields of all of the dies correctly.  Arguments are as
17752    in read_die_and_children.  */
17753
17754 static struct die_info *
17755 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17756                          const gdb_byte *info_ptr,
17757                          const gdb_byte **new_info_ptr,
17758                          struct die_info *parent)
17759 {
17760   struct die_info *first_die, *last_sibling;
17761   const gdb_byte *cur_ptr;
17762
17763   cur_ptr = info_ptr;
17764   first_die = last_sibling = NULL;
17765
17766   while (1)
17767     {
17768       struct die_info *die
17769         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17770
17771       if (die == NULL)
17772         {
17773           *new_info_ptr = cur_ptr;
17774           return first_die;
17775         }
17776
17777       if (!first_die)
17778         first_die = die;
17779       else
17780         last_sibling->sibling = die;
17781
17782       last_sibling = die;
17783     }
17784 }
17785
17786 /* Read a die, all of its descendents, and all of its siblings; set
17787    all of the fields of all of the dies correctly.  Arguments are as
17788    in read_die_and_children.
17789    This the main entry point for reading a DIE and all its children.  */
17790
17791 static struct die_info *
17792 read_die_and_siblings (const struct die_reader_specs *reader,
17793                        const gdb_byte *info_ptr,
17794                        const gdb_byte **new_info_ptr,
17795                        struct die_info *parent)
17796 {
17797   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17798                                                   new_info_ptr, parent);
17799
17800   if (dwarf_die_debug)
17801     {
17802       fprintf_unfiltered (gdb_stdlog,
17803                           "Read die from %s@0x%x of %s:\n",
17804                           get_section_name (reader->die_section),
17805                           (unsigned) (info_ptr - reader->die_section->buffer),
17806                           bfd_get_filename (reader->abfd));
17807       dump_die (die, dwarf_die_debug);
17808     }
17809
17810   return die;
17811 }
17812
17813 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17814    attributes.
17815    The caller is responsible for filling in the extra attributes
17816    and updating (*DIEP)->num_attrs.
17817    Set DIEP to point to a newly allocated die with its information,
17818    except for its child, sibling, and parent fields.
17819    Set HAS_CHILDREN to tell whether the die has children or not.  */
17820
17821 static const gdb_byte *
17822 read_full_die_1 (const struct die_reader_specs *reader,
17823                  struct die_info **diep, const gdb_byte *info_ptr,
17824                  int *has_children, int num_extra_attrs)
17825 {
17826   unsigned int abbrev_number, bytes_read, i;
17827   struct abbrev_info *abbrev;
17828   struct die_info *die;
17829   struct dwarf2_cu *cu = reader->cu;
17830   bfd *abfd = reader->abfd;
17831
17832   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17833   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17834   info_ptr += bytes_read;
17835   if (!abbrev_number)
17836     {
17837       *diep = NULL;
17838       *has_children = 0;
17839       return info_ptr;
17840     }
17841
17842   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17843   if (!abbrev)
17844     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17845            abbrev_number,
17846            bfd_get_filename (abfd));
17847
17848   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17849   die->sect_off = sect_off;
17850   die->tag = abbrev->tag;
17851   die->abbrev = abbrev_number;
17852
17853   /* Make the result usable.
17854      The caller needs to update num_attrs after adding the extra
17855      attributes.  */
17856   die->num_attrs = abbrev->num_attrs;
17857
17858   for (i = 0; i < abbrev->num_attrs; ++i)
17859     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17860                                info_ptr);
17861
17862   *diep = die;
17863   *has_children = abbrev->has_children;
17864   return info_ptr;
17865 }
17866
17867 /* Read a die and all its attributes.
17868    Set DIEP to point to a newly allocated die with its information,
17869    except for its child, sibling, and parent fields.
17870    Set HAS_CHILDREN to tell whether the die has children or not.  */
17871
17872 static const gdb_byte *
17873 read_full_die (const struct die_reader_specs *reader,
17874                struct die_info **diep, const gdb_byte *info_ptr,
17875                int *has_children)
17876 {
17877   const gdb_byte *result;
17878
17879   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17880
17881   if (dwarf_die_debug)
17882     {
17883       fprintf_unfiltered (gdb_stdlog,
17884                           "Read die from %s@0x%x of %s:\n",
17885                           get_section_name (reader->die_section),
17886                           (unsigned) (info_ptr - reader->die_section->buffer),
17887                           bfd_get_filename (reader->abfd));
17888       dump_die (*diep, dwarf_die_debug);
17889     }
17890
17891   return result;
17892 }
17893 \f
17894 /* Abbreviation tables.
17895
17896    In DWARF version 2, the description of the debugging information is
17897    stored in a separate .debug_abbrev section.  Before we read any
17898    dies from a section we read in all abbreviations and install them
17899    in a hash table.  */
17900
17901 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17902
17903 struct abbrev_info *
17904 abbrev_table::alloc_abbrev ()
17905 {
17906   struct abbrev_info *abbrev;
17907
17908   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
17909   memset (abbrev, 0, sizeof (struct abbrev_info));
17910
17911   return abbrev;
17912 }
17913
17914 /* Add an abbreviation to the table.  */
17915
17916 void
17917 abbrev_table::add_abbrev (unsigned int abbrev_number,
17918                           struct abbrev_info *abbrev)
17919 {
17920   unsigned int hash_number;
17921
17922   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17923   abbrev->next = m_abbrevs[hash_number];
17924   m_abbrevs[hash_number] = abbrev;
17925 }
17926
17927 /* Look up an abbrev in the table.
17928    Returns NULL if the abbrev is not found.  */
17929
17930 struct abbrev_info *
17931 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
17932 {
17933   unsigned int hash_number;
17934   struct abbrev_info *abbrev;
17935
17936   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17937   abbrev = m_abbrevs[hash_number];
17938
17939   while (abbrev)
17940     {
17941       if (abbrev->number == abbrev_number)
17942         return abbrev;
17943       abbrev = abbrev->next;
17944     }
17945   return NULL;
17946 }
17947
17948 /* Read in an abbrev table.  */
17949
17950 static abbrev_table_up
17951 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
17952                          struct dwarf2_section_info *section,
17953                          sect_offset sect_off)
17954 {
17955   struct objfile *objfile = dwarf2_per_objfile->objfile;
17956   bfd *abfd = get_section_bfd_owner (section);
17957   const gdb_byte *abbrev_ptr;
17958   struct abbrev_info *cur_abbrev;
17959   unsigned int abbrev_number, bytes_read, abbrev_name;
17960   unsigned int abbrev_form;
17961   struct attr_abbrev *cur_attrs;
17962   unsigned int allocated_attrs;
17963
17964   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
17965
17966   dwarf2_read_section (objfile, section);
17967   abbrev_ptr = section->buffer + to_underlying (sect_off);
17968   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17969   abbrev_ptr += bytes_read;
17970
17971   allocated_attrs = ATTR_ALLOC_CHUNK;
17972   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
17973
17974   /* Loop until we reach an abbrev number of 0.  */
17975   while (abbrev_number)
17976     {
17977       cur_abbrev = abbrev_table->alloc_abbrev ();
17978
17979       /* read in abbrev header */
17980       cur_abbrev->number = abbrev_number;
17981       cur_abbrev->tag
17982         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17983       abbrev_ptr += bytes_read;
17984       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
17985       abbrev_ptr += 1;
17986
17987       /* now read in declarations */
17988       for (;;)
17989         {
17990           LONGEST implicit_const;
17991
17992           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17993           abbrev_ptr += bytes_read;
17994           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17995           abbrev_ptr += bytes_read;
17996           if (abbrev_form == DW_FORM_implicit_const)
17997             {
17998               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
17999                                                    &bytes_read);
18000               abbrev_ptr += bytes_read;
18001             }
18002           else
18003             {
18004               /* Initialize it due to a false compiler warning.  */
18005               implicit_const = -1;
18006             }
18007
18008           if (abbrev_name == 0)
18009             break;
18010
18011           if (cur_abbrev->num_attrs == allocated_attrs)
18012             {
18013               allocated_attrs += ATTR_ALLOC_CHUNK;
18014               cur_attrs
18015                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18016             }
18017
18018           cur_attrs[cur_abbrev->num_attrs].name
18019             = (enum dwarf_attribute) abbrev_name;
18020           cur_attrs[cur_abbrev->num_attrs].form
18021             = (enum dwarf_form) abbrev_form;
18022           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18023           ++cur_abbrev->num_attrs;
18024         }
18025
18026       cur_abbrev->attrs =
18027         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18028                    cur_abbrev->num_attrs);
18029       memcpy (cur_abbrev->attrs, cur_attrs,
18030               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18031
18032       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18033
18034       /* Get next abbreviation.
18035          Under Irix6 the abbreviations for a compilation unit are not
18036          always properly terminated with an abbrev number of 0.
18037          Exit loop if we encounter an abbreviation which we have
18038          already read (which means we are about to read the abbreviations
18039          for the next compile unit) or if the end of the abbreviation
18040          table is reached.  */
18041       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18042         break;
18043       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18044       abbrev_ptr += bytes_read;
18045       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18046         break;
18047     }
18048
18049   xfree (cur_attrs);
18050   return abbrev_table;
18051 }
18052
18053 /* Returns nonzero if TAG represents a type that we might generate a partial
18054    symbol for.  */
18055
18056 static int
18057 is_type_tag_for_partial (int tag)
18058 {
18059   switch (tag)
18060     {
18061 #if 0
18062     /* Some types that would be reasonable to generate partial symbols for,
18063        that we don't at present.  */
18064     case DW_TAG_array_type:
18065     case DW_TAG_file_type:
18066     case DW_TAG_ptr_to_member_type:
18067     case DW_TAG_set_type:
18068     case DW_TAG_string_type:
18069     case DW_TAG_subroutine_type:
18070 #endif
18071     case DW_TAG_base_type:
18072     case DW_TAG_class_type:
18073     case DW_TAG_interface_type:
18074     case DW_TAG_enumeration_type:
18075     case DW_TAG_structure_type:
18076     case DW_TAG_subrange_type:
18077     case DW_TAG_typedef:
18078     case DW_TAG_union_type:
18079       return 1;
18080     default:
18081       return 0;
18082     }
18083 }
18084
18085 /* Load all DIEs that are interesting for partial symbols into memory.  */
18086
18087 static struct partial_die_info *
18088 load_partial_dies (const struct die_reader_specs *reader,
18089                    const gdb_byte *info_ptr, int building_psymtab)
18090 {
18091   struct dwarf2_cu *cu = reader->cu;
18092   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18093   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18094   unsigned int bytes_read;
18095   unsigned int load_all = 0;
18096   int nesting_level = 1;
18097
18098   parent_die = NULL;
18099   last_die = NULL;
18100
18101   gdb_assert (cu->per_cu != NULL);
18102   if (cu->per_cu->load_all_dies)
18103     load_all = 1;
18104
18105   cu->partial_dies
18106     = htab_create_alloc_ex (cu->header.length / 12,
18107                             partial_die_hash,
18108                             partial_die_eq,
18109                             NULL,
18110                             &cu->comp_unit_obstack,
18111                             hashtab_obstack_allocate,
18112                             dummy_obstack_deallocate);
18113
18114   while (1)
18115     {
18116       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18117
18118       /* A NULL abbrev means the end of a series of children.  */
18119       if (abbrev == NULL)
18120         {
18121           if (--nesting_level == 0)
18122             return first_die;
18123
18124           info_ptr += bytes_read;
18125           last_die = parent_die;
18126           parent_die = parent_die->die_parent;
18127           continue;
18128         }
18129
18130       /* Check for template arguments.  We never save these; if
18131          they're seen, we just mark the parent, and go on our way.  */
18132       if (parent_die != NULL
18133           && cu->language == language_cplus
18134           && (abbrev->tag == DW_TAG_template_type_param
18135               || abbrev->tag == DW_TAG_template_value_param))
18136         {
18137           parent_die->has_template_arguments = 1;
18138
18139           if (!load_all)
18140             {
18141               /* We don't need a partial DIE for the template argument.  */
18142               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18143               continue;
18144             }
18145         }
18146
18147       /* We only recurse into c++ subprograms looking for template arguments.
18148          Skip their other children.  */
18149       if (!load_all
18150           && cu->language == language_cplus
18151           && parent_die != NULL
18152           && parent_die->tag == DW_TAG_subprogram)
18153         {
18154           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18155           continue;
18156         }
18157
18158       /* Check whether this DIE is interesting enough to save.  Normally
18159          we would not be interested in members here, but there may be
18160          later variables referencing them via DW_AT_specification (for
18161          static members).  */
18162       if (!load_all
18163           && !is_type_tag_for_partial (abbrev->tag)
18164           && abbrev->tag != DW_TAG_constant
18165           && abbrev->tag != DW_TAG_enumerator
18166           && abbrev->tag != DW_TAG_subprogram
18167           && abbrev->tag != DW_TAG_inlined_subroutine
18168           && abbrev->tag != DW_TAG_lexical_block
18169           && abbrev->tag != DW_TAG_variable
18170           && abbrev->tag != DW_TAG_namespace
18171           && abbrev->tag != DW_TAG_module
18172           && abbrev->tag != DW_TAG_member
18173           && abbrev->tag != DW_TAG_imported_unit
18174           && abbrev->tag != DW_TAG_imported_declaration)
18175         {
18176           /* Otherwise we skip to the next sibling, if any.  */
18177           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18178           continue;
18179         }
18180
18181       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18182                                    abbrev);
18183
18184       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18185
18186       /* This two-pass algorithm for processing partial symbols has a
18187          high cost in cache pressure.  Thus, handle some simple cases
18188          here which cover the majority of C partial symbols.  DIEs
18189          which neither have specification tags in them, nor could have
18190          specification tags elsewhere pointing at them, can simply be
18191          processed and discarded.
18192
18193          This segment is also optional; scan_partial_symbols and
18194          add_partial_symbol will handle these DIEs if we chain
18195          them in normally.  When compilers which do not emit large
18196          quantities of duplicate debug information are more common,
18197          this code can probably be removed.  */
18198
18199       /* Any complete simple types at the top level (pretty much all
18200          of them, for a language without namespaces), can be processed
18201          directly.  */
18202       if (parent_die == NULL
18203           && pdi.has_specification == 0
18204           && pdi.is_declaration == 0
18205           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18206               || pdi.tag == DW_TAG_base_type
18207               || pdi.tag == DW_TAG_subrange_type))
18208         {
18209           if (building_psymtab && pdi.name != NULL)
18210             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18211                                  VAR_DOMAIN, LOC_TYPEDEF,
18212                                  &objfile->static_psymbols,
18213                                  0, cu->language, objfile);
18214           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18215           continue;
18216         }
18217
18218       /* The exception for DW_TAG_typedef with has_children above is
18219          a workaround of GCC PR debug/47510.  In the case of this complaint
18220          type_name_or_error will error on such types later.
18221
18222          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18223          it could not find the child DIEs referenced later, this is checked
18224          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18225
18226       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18227         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18228                      "- DIE at %s [in module %s]"),
18229                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18230
18231       /* If we're at the second level, and we're an enumerator, and
18232          our parent has no specification (meaning possibly lives in a
18233          namespace elsewhere), then we can add the partial symbol now
18234          instead of queueing it.  */
18235       if (pdi.tag == DW_TAG_enumerator
18236           && parent_die != NULL
18237           && parent_die->die_parent == NULL
18238           && parent_die->tag == DW_TAG_enumeration_type
18239           && parent_die->has_specification == 0)
18240         {
18241           if (pdi.name == NULL)
18242             complaint (_("malformed enumerator DIE ignored"));
18243           else if (building_psymtab)
18244             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18245                                  VAR_DOMAIN, LOC_CONST,
18246                                  cu->language == language_cplus
18247                                  ? &objfile->global_psymbols
18248                                  : &objfile->static_psymbols,
18249                                  0, cu->language, objfile);
18250
18251           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18252           continue;
18253         }
18254
18255       struct partial_die_info *part_die
18256         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18257
18258       /* We'll save this DIE so link it in.  */
18259       part_die->die_parent = parent_die;
18260       part_die->die_sibling = NULL;
18261       part_die->die_child = NULL;
18262
18263       if (last_die && last_die == parent_die)
18264         last_die->die_child = part_die;
18265       else if (last_die)
18266         last_die->die_sibling = part_die;
18267
18268       last_die = part_die;
18269
18270       if (first_die == NULL)
18271         first_die = part_die;
18272
18273       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18274          find interesting need to be in the hash table, because we
18275          also have the parent/sibling/child chains; only those that we
18276          might refer to by offset later during partial symbol reading.
18277
18278          For now this means things that might have be the target of a
18279          DW_AT_specification, DW_AT_abstract_origin, or
18280          DW_AT_extension.  DW_AT_extension will refer only to
18281          namespaces; DW_AT_abstract_origin refers to functions (and
18282          many things under the function DIE, but we do not recurse
18283          into function DIEs during partial symbol reading) and
18284          possibly variables as well; DW_AT_specification refers to
18285          declarations.  Declarations ought to have the DW_AT_declaration
18286          flag.  It happens that GCC forgets to put it in sometimes, but
18287          only for functions, not for types.
18288
18289          Adding more things than necessary to the hash table is harmless
18290          except for the performance cost.  Adding too few will result in
18291          wasted time in find_partial_die, when we reread the compilation
18292          unit with load_all_dies set.  */
18293
18294       if (load_all
18295           || abbrev->tag == DW_TAG_constant
18296           || abbrev->tag == DW_TAG_subprogram
18297           || abbrev->tag == DW_TAG_variable
18298           || abbrev->tag == DW_TAG_namespace
18299           || part_die->is_declaration)
18300         {
18301           void **slot;
18302
18303           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18304                                            to_underlying (part_die->sect_off),
18305                                            INSERT);
18306           *slot = part_die;
18307         }
18308
18309       /* For some DIEs we want to follow their children (if any).  For C
18310          we have no reason to follow the children of structures; for other
18311          languages we have to, so that we can get at method physnames
18312          to infer fully qualified class names, for DW_AT_specification,
18313          and for C++ template arguments.  For C++, we also look one level
18314          inside functions to find template arguments (if the name of the
18315          function does not already contain the template arguments).
18316
18317          For Ada, we need to scan the children of subprograms and lexical
18318          blocks as well because Ada allows the definition of nested
18319          entities that could be interesting for the debugger, such as
18320          nested subprograms for instance.  */
18321       if (last_die->has_children
18322           && (load_all
18323               || last_die->tag == DW_TAG_namespace
18324               || last_die->tag == DW_TAG_module
18325               || last_die->tag == DW_TAG_enumeration_type
18326               || (cu->language == language_cplus
18327                   && last_die->tag == DW_TAG_subprogram
18328                   && (last_die->name == NULL
18329                       || strchr (last_die->name, '<') == NULL))
18330               || (cu->language != language_c
18331                   && (last_die->tag == DW_TAG_class_type
18332                       || last_die->tag == DW_TAG_interface_type
18333                       || last_die->tag == DW_TAG_structure_type
18334                       || last_die->tag == DW_TAG_union_type))
18335               || (cu->language == language_ada
18336                   && (last_die->tag == DW_TAG_subprogram
18337                       || last_die->tag == DW_TAG_lexical_block))))
18338         {
18339           nesting_level++;
18340           parent_die = last_die;
18341           continue;
18342         }
18343
18344       /* Otherwise we skip to the next sibling, if any.  */
18345       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18346
18347       /* Back to the top, do it again.  */
18348     }
18349 }
18350
18351 partial_die_info::partial_die_info (sect_offset sect_off_,
18352                                     struct abbrev_info *abbrev)
18353   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18354 {
18355 }
18356
18357 /* Read a minimal amount of information into the minimal die structure.
18358    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18359
18360 const gdb_byte *
18361 partial_die_info::read (const struct die_reader_specs *reader,
18362                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18363 {
18364   struct dwarf2_cu *cu = reader->cu;
18365   struct dwarf2_per_objfile *dwarf2_per_objfile
18366     = cu->per_cu->dwarf2_per_objfile;
18367   unsigned int i;
18368   int has_low_pc_attr = 0;
18369   int has_high_pc_attr = 0;
18370   int high_pc_relative = 0;
18371
18372   for (i = 0; i < abbrev.num_attrs; ++i)
18373     {
18374       struct attribute attr;
18375
18376       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18377
18378       /* Store the data if it is of an attribute we want to keep in a
18379          partial symbol table.  */
18380       switch (attr.name)
18381         {
18382         case DW_AT_name:
18383           switch (tag)
18384             {
18385             case DW_TAG_compile_unit:
18386             case DW_TAG_partial_unit:
18387             case DW_TAG_type_unit:
18388               /* Compilation units have a DW_AT_name that is a filename, not
18389                  a source language identifier.  */
18390             case DW_TAG_enumeration_type:
18391             case DW_TAG_enumerator:
18392               /* These tags always have simple identifiers already; no need
18393                  to canonicalize them.  */
18394               name = DW_STRING (&attr);
18395               break;
18396             default:
18397               {
18398                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18399
18400                 name
18401                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18402                                               &objfile->per_bfd->storage_obstack);
18403               }
18404               break;
18405             }
18406           break;
18407         case DW_AT_linkage_name:
18408         case DW_AT_MIPS_linkage_name:
18409           /* Note that both forms of linkage name might appear.  We
18410              assume they will be the same, and we only store the last
18411              one we see.  */
18412           if (cu->language == language_ada)
18413             name = DW_STRING (&attr);
18414           linkage_name = DW_STRING (&attr);
18415           break;
18416         case DW_AT_low_pc:
18417           has_low_pc_attr = 1;
18418           lowpc = attr_value_as_address (&attr);
18419           break;
18420         case DW_AT_high_pc:
18421           has_high_pc_attr = 1;
18422           highpc = attr_value_as_address (&attr);
18423           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18424                 high_pc_relative = 1;
18425           break;
18426         case DW_AT_location:
18427           /* Support the .debug_loc offsets.  */
18428           if (attr_form_is_block (&attr))
18429             {
18430                d.locdesc = DW_BLOCK (&attr);
18431             }
18432           else if (attr_form_is_section_offset (&attr))
18433             {
18434               dwarf2_complex_location_expr_complaint ();
18435             }
18436           else
18437             {
18438               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18439                                                      "partial symbol information");
18440             }
18441           break;
18442         case DW_AT_external:
18443           is_external = DW_UNSND (&attr);
18444           break;
18445         case DW_AT_declaration:
18446           is_declaration = DW_UNSND (&attr);
18447           break;
18448         case DW_AT_type:
18449           has_type = 1;
18450           break;
18451         case DW_AT_abstract_origin:
18452         case DW_AT_specification:
18453         case DW_AT_extension:
18454           has_specification = 1;
18455           spec_offset = dwarf2_get_ref_die_offset (&attr);
18456           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18457                                    || cu->per_cu->is_dwz);
18458           break;
18459         case DW_AT_sibling:
18460           /* Ignore absolute siblings, they might point outside of
18461              the current compile unit.  */
18462           if (attr.form == DW_FORM_ref_addr)
18463             complaint (_("ignoring absolute DW_AT_sibling"));
18464           else
18465             {
18466               const gdb_byte *buffer = reader->buffer;
18467               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18468               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18469
18470               if (sibling_ptr < info_ptr)
18471                 complaint (_("DW_AT_sibling points backwards"));
18472               else if (sibling_ptr > reader->buffer_end)
18473                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18474               else
18475                 sibling = sibling_ptr;
18476             }
18477           break;
18478         case DW_AT_byte_size:
18479           has_byte_size = 1;
18480           break;
18481         case DW_AT_const_value:
18482           has_const_value = 1;
18483           break;
18484         case DW_AT_calling_convention:
18485           /* DWARF doesn't provide a way to identify a program's source-level
18486              entry point.  DW_AT_calling_convention attributes are only meant
18487              to describe functions' calling conventions.
18488
18489              However, because it's a necessary piece of information in
18490              Fortran, and before DWARF 4 DW_CC_program was the only
18491              piece of debugging information whose definition refers to
18492              a 'main program' at all, several compilers marked Fortran
18493              main programs with DW_CC_program --- even when those
18494              functions use the standard calling conventions.
18495
18496              Although DWARF now specifies a way to provide this
18497              information, we support this practice for backward
18498              compatibility.  */
18499           if (DW_UNSND (&attr) == DW_CC_program
18500               && cu->language == language_fortran)
18501             main_subprogram = 1;
18502           break;
18503         case DW_AT_inline:
18504           if (DW_UNSND (&attr) == DW_INL_inlined
18505               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18506             may_be_inlined = 1;
18507           break;
18508
18509         case DW_AT_import:
18510           if (tag == DW_TAG_imported_unit)
18511             {
18512               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18513               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18514                                   || cu->per_cu->is_dwz);
18515             }
18516           break;
18517
18518         case DW_AT_main_subprogram:
18519           main_subprogram = DW_UNSND (&attr);
18520           break;
18521
18522         default:
18523           break;
18524         }
18525     }
18526
18527   if (high_pc_relative)
18528     highpc += lowpc;
18529
18530   if (has_low_pc_attr && has_high_pc_attr)
18531     {
18532       /* When using the GNU linker, .gnu.linkonce. sections are used to
18533          eliminate duplicate copies of functions and vtables and such.
18534          The linker will arbitrarily choose one and discard the others.
18535          The AT_*_pc values for such functions refer to local labels in
18536          these sections.  If the section from that file was discarded, the
18537          labels are not in the output, so the relocs get a value of 0.
18538          If this is a discarded function, mark the pc bounds as invalid,
18539          so that GDB will ignore it.  */
18540       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18541         {
18542           struct objfile *objfile = dwarf2_per_objfile->objfile;
18543           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18544
18545           complaint (_("DW_AT_low_pc %s is zero "
18546                        "for DIE at %s [in module %s]"),
18547                      paddress (gdbarch, lowpc),
18548                      sect_offset_str (sect_off),
18549                      objfile_name (objfile));
18550         }
18551       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18552       else if (lowpc >= highpc)
18553         {
18554           struct objfile *objfile = dwarf2_per_objfile->objfile;
18555           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18556
18557           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18558                        "for DIE at %s [in module %s]"),
18559                      paddress (gdbarch, lowpc),
18560                      paddress (gdbarch, highpc),
18561                      sect_offset_str (sect_off),
18562                      objfile_name (objfile));
18563         }
18564       else
18565         has_pc_info = 1;
18566     }
18567
18568   return info_ptr;
18569 }
18570
18571 /* Find a cached partial DIE at OFFSET in CU.  */
18572
18573 struct partial_die_info *
18574 dwarf2_cu::find_partial_die (sect_offset sect_off)
18575 {
18576   struct partial_die_info *lookup_die = NULL;
18577   struct partial_die_info part_die (sect_off);
18578
18579   lookup_die = ((struct partial_die_info *)
18580                 htab_find_with_hash (partial_dies, &part_die,
18581                                      to_underlying (sect_off)));
18582
18583   return lookup_die;
18584 }
18585
18586 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18587    except in the case of .debug_types DIEs which do not reference
18588    outside their CU (they do however referencing other types via
18589    DW_FORM_ref_sig8).  */
18590
18591 static struct partial_die_info *
18592 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18593 {
18594   struct dwarf2_per_objfile *dwarf2_per_objfile
18595     = cu->per_cu->dwarf2_per_objfile;
18596   struct objfile *objfile = dwarf2_per_objfile->objfile;
18597   struct dwarf2_per_cu_data *per_cu = NULL;
18598   struct partial_die_info *pd = NULL;
18599
18600   if (offset_in_dwz == cu->per_cu->is_dwz
18601       && offset_in_cu_p (&cu->header, sect_off))
18602     {
18603       pd = cu->find_partial_die (sect_off);
18604       if (pd != NULL)
18605         return pd;
18606       /* We missed recording what we needed.
18607          Load all dies and try again.  */
18608       per_cu = cu->per_cu;
18609     }
18610   else
18611     {
18612       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18613       if (cu->per_cu->is_debug_types)
18614         {
18615           error (_("Dwarf Error: Type Unit at offset %s contains"
18616                    " external reference to offset %s [in module %s].\n"),
18617                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18618                  bfd_get_filename (objfile->obfd));
18619         }
18620       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18621                                                  dwarf2_per_objfile);
18622
18623       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18624         load_partial_comp_unit (per_cu);
18625
18626       per_cu->cu->last_used = 0;
18627       pd = per_cu->cu->find_partial_die (sect_off);
18628     }
18629
18630   /* If we didn't find it, and not all dies have been loaded,
18631      load them all and try again.  */
18632
18633   if (pd == NULL && per_cu->load_all_dies == 0)
18634     {
18635       per_cu->load_all_dies = 1;
18636
18637       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18638          THIS_CU->cu may already be in use.  So we can't just free it and
18639          replace its DIEs with the ones we read in.  Instead, we leave those
18640          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18641          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18642          set.  */
18643       load_partial_comp_unit (per_cu);
18644
18645       pd = per_cu->cu->find_partial_die (sect_off);
18646     }
18647
18648   if (pd == NULL)
18649     internal_error (__FILE__, __LINE__,
18650                     _("could not find partial DIE %s "
18651                       "in cache [from module %s]\n"),
18652                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18653   return pd;
18654 }
18655
18656 /* See if we can figure out if the class lives in a namespace.  We do
18657    this by looking for a member function; its demangled name will
18658    contain namespace info, if there is any.  */
18659
18660 static void
18661 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18662                                   struct dwarf2_cu *cu)
18663 {
18664   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18665      what template types look like, because the demangler
18666      frequently doesn't give the same name as the debug info.  We
18667      could fix this by only using the demangled name to get the
18668      prefix (but see comment in read_structure_type).  */
18669
18670   struct partial_die_info *real_pdi;
18671   struct partial_die_info *child_pdi;
18672
18673   /* If this DIE (this DIE's specification, if any) has a parent, then
18674      we should not do this.  We'll prepend the parent's fully qualified
18675      name when we create the partial symbol.  */
18676
18677   real_pdi = struct_pdi;
18678   while (real_pdi->has_specification)
18679     real_pdi = find_partial_die (real_pdi->spec_offset,
18680                                  real_pdi->spec_is_dwz, cu);
18681
18682   if (real_pdi->die_parent != NULL)
18683     return;
18684
18685   for (child_pdi = struct_pdi->die_child;
18686        child_pdi != NULL;
18687        child_pdi = child_pdi->die_sibling)
18688     {
18689       if (child_pdi->tag == DW_TAG_subprogram
18690           && child_pdi->linkage_name != NULL)
18691         {
18692           char *actual_class_name
18693             = language_class_name_from_physname (cu->language_defn,
18694                                                  child_pdi->linkage_name);
18695           if (actual_class_name != NULL)
18696             {
18697               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18698               struct_pdi->name
18699                 = ((const char *)
18700                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18701                                   actual_class_name,
18702                                   strlen (actual_class_name)));
18703               xfree (actual_class_name);
18704             }
18705           break;
18706         }
18707     }
18708 }
18709
18710 void
18711 partial_die_info::fixup (struct dwarf2_cu *cu)
18712 {
18713   /* Once we've fixed up a die, there's no point in doing so again.
18714      This also avoids a memory leak if we were to call
18715      guess_partial_die_structure_name multiple times.  */
18716   if (fixup_called)
18717     return;
18718
18719   /* If we found a reference attribute and the DIE has no name, try
18720      to find a name in the referred to DIE.  */
18721
18722   if (name == NULL && has_specification)
18723     {
18724       struct partial_die_info *spec_die;
18725
18726       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18727
18728       spec_die->fixup (cu);
18729
18730       if (spec_die->name)
18731         {
18732           name = spec_die->name;
18733
18734           /* Copy DW_AT_external attribute if it is set.  */
18735           if (spec_die->is_external)
18736             is_external = spec_die->is_external;
18737         }
18738     }
18739
18740   /* Set default names for some unnamed DIEs.  */
18741
18742   if (name == NULL && tag == DW_TAG_namespace)
18743     name = CP_ANONYMOUS_NAMESPACE_STR;
18744
18745   /* If there is no parent die to provide a namespace, and there are
18746      children, see if we can determine the namespace from their linkage
18747      name.  */
18748   if (cu->language == language_cplus
18749       && !VEC_empty (dwarf2_section_info_def,
18750                      cu->per_cu->dwarf2_per_objfile->types)
18751       && die_parent == NULL
18752       && has_children
18753       && (tag == DW_TAG_class_type
18754           || tag == DW_TAG_structure_type
18755           || tag == DW_TAG_union_type))
18756     guess_partial_die_structure_name (this, cu);
18757
18758   /* GCC might emit a nameless struct or union that has a linkage
18759      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18760   if (name == NULL
18761       && (tag == DW_TAG_class_type
18762           || tag == DW_TAG_interface_type
18763           || tag == DW_TAG_structure_type
18764           || tag == DW_TAG_union_type)
18765       && linkage_name != NULL)
18766     {
18767       char *demangled;
18768
18769       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18770       if (demangled)
18771         {
18772           const char *base;
18773
18774           /* Strip any leading namespaces/classes, keep only the base name.
18775              DW_AT_name for named DIEs does not contain the prefixes.  */
18776           base = strrchr (demangled, ':');
18777           if (base && base > demangled && base[-1] == ':')
18778             base++;
18779           else
18780             base = demangled;
18781
18782           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18783           name
18784             = ((const char *)
18785                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18786                               base, strlen (base)));
18787           xfree (demangled);
18788         }
18789     }
18790
18791   fixup_called = 1;
18792 }
18793
18794 /* Read an attribute value described by an attribute form.  */
18795
18796 static const gdb_byte *
18797 read_attribute_value (const struct die_reader_specs *reader,
18798                       struct attribute *attr, unsigned form,
18799                       LONGEST implicit_const, const gdb_byte *info_ptr)
18800 {
18801   struct dwarf2_cu *cu = reader->cu;
18802   struct dwarf2_per_objfile *dwarf2_per_objfile
18803     = cu->per_cu->dwarf2_per_objfile;
18804   struct objfile *objfile = dwarf2_per_objfile->objfile;
18805   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18806   bfd *abfd = reader->abfd;
18807   struct comp_unit_head *cu_header = &cu->header;
18808   unsigned int bytes_read;
18809   struct dwarf_block *blk;
18810
18811   attr->form = (enum dwarf_form) form;
18812   switch (form)
18813     {
18814     case DW_FORM_ref_addr:
18815       if (cu->header.version == 2)
18816         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18817       else
18818         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18819                                        &cu->header, &bytes_read);
18820       info_ptr += bytes_read;
18821       break;
18822     case DW_FORM_GNU_ref_alt:
18823       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18824       info_ptr += bytes_read;
18825       break;
18826     case DW_FORM_addr:
18827       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18828       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18829       info_ptr += bytes_read;
18830       break;
18831     case DW_FORM_block2:
18832       blk = dwarf_alloc_block (cu);
18833       blk->size = read_2_bytes (abfd, info_ptr);
18834       info_ptr += 2;
18835       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18836       info_ptr += blk->size;
18837       DW_BLOCK (attr) = blk;
18838       break;
18839     case DW_FORM_block4:
18840       blk = dwarf_alloc_block (cu);
18841       blk->size = read_4_bytes (abfd, info_ptr);
18842       info_ptr += 4;
18843       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18844       info_ptr += blk->size;
18845       DW_BLOCK (attr) = blk;
18846       break;
18847     case DW_FORM_data2:
18848       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18849       info_ptr += 2;
18850       break;
18851     case DW_FORM_data4:
18852       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18853       info_ptr += 4;
18854       break;
18855     case DW_FORM_data8:
18856       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18857       info_ptr += 8;
18858       break;
18859     case DW_FORM_data16:
18860       blk = dwarf_alloc_block (cu);
18861       blk->size = 16;
18862       blk->data = read_n_bytes (abfd, info_ptr, 16);
18863       info_ptr += 16;
18864       DW_BLOCK (attr) = blk;
18865       break;
18866     case DW_FORM_sec_offset:
18867       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18868       info_ptr += bytes_read;
18869       break;
18870     case DW_FORM_string:
18871       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18872       DW_STRING_IS_CANONICAL (attr) = 0;
18873       info_ptr += bytes_read;
18874       break;
18875     case DW_FORM_strp:
18876       if (!cu->per_cu->is_dwz)
18877         {
18878           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18879                                                    abfd, info_ptr, cu_header,
18880                                                    &bytes_read);
18881           DW_STRING_IS_CANONICAL (attr) = 0;
18882           info_ptr += bytes_read;
18883           break;
18884         }
18885       /* FALLTHROUGH */
18886     case DW_FORM_line_strp:
18887       if (!cu->per_cu->is_dwz)
18888         {
18889           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18890                                                         abfd, info_ptr,
18891                                                         cu_header, &bytes_read);
18892           DW_STRING_IS_CANONICAL (attr) = 0;
18893           info_ptr += bytes_read;
18894           break;
18895         }
18896       /* FALLTHROUGH */
18897     case DW_FORM_GNU_strp_alt:
18898       {
18899         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
18900         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18901                                           &bytes_read);
18902
18903         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
18904                                                           dwz, str_offset);
18905         DW_STRING_IS_CANONICAL (attr) = 0;
18906         info_ptr += bytes_read;
18907       }
18908       break;
18909     case DW_FORM_exprloc:
18910     case DW_FORM_block:
18911       blk = dwarf_alloc_block (cu);
18912       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18913       info_ptr += bytes_read;
18914       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18915       info_ptr += blk->size;
18916       DW_BLOCK (attr) = blk;
18917       break;
18918     case DW_FORM_block1:
18919       blk = dwarf_alloc_block (cu);
18920       blk->size = read_1_byte (abfd, info_ptr);
18921       info_ptr += 1;
18922       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18923       info_ptr += blk->size;
18924       DW_BLOCK (attr) = blk;
18925       break;
18926     case DW_FORM_data1:
18927       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18928       info_ptr += 1;
18929       break;
18930     case DW_FORM_flag:
18931       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18932       info_ptr += 1;
18933       break;
18934     case DW_FORM_flag_present:
18935       DW_UNSND (attr) = 1;
18936       break;
18937     case DW_FORM_sdata:
18938       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18939       info_ptr += bytes_read;
18940       break;
18941     case DW_FORM_udata:
18942       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18943       info_ptr += bytes_read;
18944       break;
18945     case DW_FORM_ref1:
18946       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18947                          + read_1_byte (abfd, info_ptr));
18948       info_ptr += 1;
18949       break;
18950     case DW_FORM_ref2:
18951       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18952                          + read_2_bytes (abfd, info_ptr));
18953       info_ptr += 2;
18954       break;
18955     case DW_FORM_ref4:
18956       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18957                          + read_4_bytes (abfd, info_ptr));
18958       info_ptr += 4;
18959       break;
18960     case DW_FORM_ref8:
18961       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18962                          + read_8_bytes (abfd, info_ptr));
18963       info_ptr += 8;
18964       break;
18965     case DW_FORM_ref_sig8:
18966       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
18967       info_ptr += 8;
18968       break;
18969     case DW_FORM_ref_udata:
18970       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18971                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
18972       info_ptr += bytes_read;
18973       break;
18974     case DW_FORM_indirect:
18975       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18976       info_ptr += bytes_read;
18977       if (form == DW_FORM_implicit_const)
18978         {
18979           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18980           info_ptr += bytes_read;
18981         }
18982       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
18983                                        info_ptr);
18984       break;
18985     case DW_FORM_implicit_const:
18986       DW_SND (attr) = implicit_const;
18987       break;
18988     case DW_FORM_GNU_addr_index:
18989       if (reader->dwo_file == NULL)
18990         {
18991           /* For now flag a hard error.
18992              Later we can turn this into a complaint.  */
18993           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
18994                  dwarf_form_name (form),
18995                  bfd_get_filename (abfd));
18996         }
18997       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
18998       info_ptr += bytes_read;
18999       break;
19000     case DW_FORM_GNU_str_index:
19001       if (reader->dwo_file == NULL)
19002         {
19003           /* For now flag a hard error.
19004              Later we can turn this into a complaint if warranted.  */
19005           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19006                  dwarf_form_name (form),
19007                  bfd_get_filename (abfd));
19008         }
19009       {
19010         ULONGEST str_index =
19011           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19012
19013         DW_STRING (attr) = read_str_index (reader, str_index);
19014         DW_STRING_IS_CANONICAL (attr) = 0;
19015         info_ptr += bytes_read;
19016       }
19017       break;
19018     default:
19019       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19020              dwarf_form_name (form),
19021              bfd_get_filename (abfd));
19022     }
19023
19024   /* Super hack.  */
19025   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19026     attr->form = DW_FORM_GNU_ref_alt;
19027
19028   /* We have seen instances where the compiler tried to emit a byte
19029      size attribute of -1 which ended up being encoded as an unsigned
19030      0xffffffff.  Although 0xffffffff is technically a valid size value,
19031      an object of this size seems pretty unlikely so we can relatively
19032      safely treat these cases as if the size attribute was invalid and
19033      treat them as zero by default.  */
19034   if (attr->name == DW_AT_byte_size
19035       && form == DW_FORM_data4
19036       && DW_UNSND (attr) >= 0xffffffff)
19037     {
19038       complaint
19039         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19040          hex_string (DW_UNSND (attr)));
19041       DW_UNSND (attr) = 0;
19042     }
19043
19044   return info_ptr;
19045 }
19046
19047 /* Read an attribute described by an abbreviated attribute.  */
19048
19049 static const gdb_byte *
19050 read_attribute (const struct die_reader_specs *reader,
19051                 struct attribute *attr, struct attr_abbrev *abbrev,
19052                 const gdb_byte *info_ptr)
19053 {
19054   attr->name = abbrev->name;
19055   return read_attribute_value (reader, attr, abbrev->form,
19056                                abbrev->implicit_const, info_ptr);
19057 }
19058
19059 /* Read dwarf information from a buffer.  */
19060
19061 static unsigned int
19062 read_1_byte (bfd *abfd, const gdb_byte *buf)
19063 {
19064   return bfd_get_8 (abfd, buf);
19065 }
19066
19067 static int
19068 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19069 {
19070   return bfd_get_signed_8 (abfd, buf);
19071 }
19072
19073 static unsigned int
19074 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19075 {
19076   return bfd_get_16 (abfd, buf);
19077 }
19078
19079 static int
19080 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19081 {
19082   return bfd_get_signed_16 (abfd, buf);
19083 }
19084
19085 static unsigned int
19086 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19087 {
19088   return bfd_get_32 (abfd, buf);
19089 }
19090
19091 static int
19092 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19093 {
19094   return bfd_get_signed_32 (abfd, buf);
19095 }
19096
19097 static ULONGEST
19098 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19099 {
19100   return bfd_get_64 (abfd, buf);
19101 }
19102
19103 static CORE_ADDR
19104 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19105               unsigned int *bytes_read)
19106 {
19107   struct comp_unit_head *cu_header = &cu->header;
19108   CORE_ADDR retval = 0;
19109
19110   if (cu_header->signed_addr_p)
19111     {
19112       switch (cu_header->addr_size)
19113         {
19114         case 2:
19115           retval = bfd_get_signed_16 (abfd, buf);
19116           break;
19117         case 4:
19118           retval = bfd_get_signed_32 (abfd, buf);
19119           break;
19120         case 8:
19121           retval = bfd_get_signed_64 (abfd, buf);
19122           break;
19123         default:
19124           internal_error (__FILE__, __LINE__,
19125                           _("read_address: bad switch, signed [in module %s]"),
19126                           bfd_get_filename (abfd));
19127         }
19128     }
19129   else
19130     {
19131       switch (cu_header->addr_size)
19132         {
19133         case 2:
19134           retval = bfd_get_16 (abfd, buf);
19135           break;
19136         case 4:
19137           retval = bfd_get_32 (abfd, buf);
19138           break;
19139         case 8:
19140           retval = bfd_get_64 (abfd, buf);
19141           break;
19142         default:
19143           internal_error (__FILE__, __LINE__,
19144                           _("read_address: bad switch, "
19145                             "unsigned [in module %s]"),
19146                           bfd_get_filename (abfd));
19147         }
19148     }
19149
19150   *bytes_read = cu_header->addr_size;
19151   return retval;
19152 }
19153
19154 /* Read the initial length from a section.  The (draft) DWARF 3
19155    specification allows the initial length to take up either 4 bytes
19156    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19157    bytes describe the length and all offsets will be 8 bytes in length
19158    instead of 4.
19159
19160    An older, non-standard 64-bit format is also handled by this
19161    function.  The older format in question stores the initial length
19162    as an 8-byte quantity without an escape value.  Lengths greater
19163    than 2^32 aren't very common which means that the initial 4 bytes
19164    is almost always zero.  Since a length value of zero doesn't make
19165    sense for the 32-bit format, this initial zero can be considered to
19166    be an escape value which indicates the presence of the older 64-bit
19167    format.  As written, the code can't detect (old format) lengths
19168    greater than 4GB.  If it becomes necessary to handle lengths
19169    somewhat larger than 4GB, we could allow other small values (such
19170    as the non-sensical values of 1, 2, and 3) to also be used as
19171    escape values indicating the presence of the old format.
19172
19173    The value returned via bytes_read should be used to increment the
19174    relevant pointer after calling read_initial_length().
19175
19176    [ Note:  read_initial_length() and read_offset() are based on the
19177      document entitled "DWARF Debugging Information Format", revision
19178      3, draft 8, dated November 19, 2001.  This document was obtained
19179      from:
19180
19181         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19182
19183      This document is only a draft and is subject to change.  (So beware.)
19184
19185      Details regarding the older, non-standard 64-bit format were
19186      determined empirically by examining 64-bit ELF files produced by
19187      the SGI toolchain on an IRIX 6.5 machine.
19188
19189      - Kevin, July 16, 2002
19190    ] */
19191
19192 static LONGEST
19193 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19194 {
19195   LONGEST length = bfd_get_32 (abfd, buf);
19196
19197   if (length == 0xffffffff)
19198     {
19199       length = bfd_get_64 (abfd, buf + 4);
19200       *bytes_read = 12;
19201     }
19202   else if (length == 0)
19203     {
19204       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19205       length = bfd_get_64 (abfd, buf);
19206       *bytes_read = 8;
19207     }
19208   else
19209     {
19210       *bytes_read = 4;
19211     }
19212
19213   return length;
19214 }
19215
19216 /* Cover function for read_initial_length.
19217    Returns the length of the object at BUF, and stores the size of the
19218    initial length in *BYTES_READ and stores the size that offsets will be in
19219    *OFFSET_SIZE.
19220    If the initial length size is not equivalent to that specified in
19221    CU_HEADER then issue a complaint.
19222    This is useful when reading non-comp-unit headers.  */
19223
19224 static LONGEST
19225 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19226                                         const struct comp_unit_head *cu_header,
19227                                         unsigned int *bytes_read,
19228                                         unsigned int *offset_size)
19229 {
19230   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19231
19232   gdb_assert (cu_header->initial_length_size == 4
19233               || cu_header->initial_length_size == 8
19234               || cu_header->initial_length_size == 12);
19235
19236   if (cu_header->initial_length_size != *bytes_read)
19237     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19238
19239   *offset_size = (*bytes_read == 4) ? 4 : 8;
19240   return length;
19241 }
19242
19243 /* Read an offset from the data stream.  The size of the offset is
19244    given by cu_header->offset_size.  */
19245
19246 static LONGEST
19247 read_offset (bfd *abfd, const gdb_byte *buf,
19248              const struct comp_unit_head *cu_header,
19249              unsigned int *bytes_read)
19250 {
19251   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19252
19253   *bytes_read = cu_header->offset_size;
19254   return offset;
19255 }
19256
19257 /* Read an offset from the data stream.  */
19258
19259 static LONGEST
19260 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19261 {
19262   LONGEST retval = 0;
19263
19264   switch (offset_size)
19265     {
19266     case 4:
19267       retval = bfd_get_32 (abfd, buf);
19268       break;
19269     case 8:
19270       retval = bfd_get_64 (abfd, buf);
19271       break;
19272     default:
19273       internal_error (__FILE__, __LINE__,
19274                       _("read_offset_1: bad switch [in module %s]"),
19275                       bfd_get_filename (abfd));
19276     }
19277
19278   return retval;
19279 }
19280
19281 static const gdb_byte *
19282 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19283 {
19284   /* If the size of a host char is 8 bits, we can return a pointer
19285      to the buffer, otherwise we have to copy the data to a buffer
19286      allocated on the temporary obstack.  */
19287   gdb_assert (HOST_CHAR_BIT == 8);
19288   return buf;
19289 }
19290
19291 static const char *
19292 read_direct_string (bfd *abfd, const gdb_byte *buf,
19293                     unsigned int *bytes_read_ptr)
19294 {
19295   /* If the size of a host char is 8 bits, we can return a pointer
19296      to the string, otherwise we have to copy the string to a buffer
19297      allocated on the temporary obstack.  */
19298   gdb_assert (HOST_CHAR_BIT == 8);
19299   if (*buf == '\0')
19300     {
19301       *bytes_read_ptr = 1;
19302       return NULL;
19303     }
19304   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19305   return (const char *) buf;
19306 }
19307
19308 /* Return pointer to string at section SECT offset STR_OFFSET with error
19309    reporting strings FORM_NAME and SECT_NAME.  */
19310
19311 static const char *
19312 read_indirect_string_at_offset_from (struct objfile *objfile,
19313                                      bfd *abfd, LONGEST str_offset,
19314                                      struct dwarf2_section_info *sect,
19315                                      const char *form_name,
19316                                      const char *sect_name)
19317 {
19318   dwarf2_read_section (objfile, sect);
19319   if (sect->buffer == NULL)
19320     error (_("%s used without %s section [in module %s]"),
19321            form_name, sect_name, bfd_get_filename (abfd));
19322   if (str_offset >= sect->size)
19323     error (_("%s pointing outside of %s section [in module %s]"),
19324            form_name, sect_name, bfd_get_filename (abfd));
19325   gdb_assert (HOST_CHAR_BIT == 8);
19326   if (sect->buffer[str_offset] == '\0')
19327     return NULL;
19328   return (const char *) (sect->buffer + str_offset);
19329 }
19330
19331 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19332
19333 static const char *
19334 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19335                                 bfd *abfd, LONGEST str_offset)
19336 {
19337   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19338                                               abfd, str_offset,
19339                                               &dwarf2_per_objfile->str,
19340                                               "DW_FORM_strp", ".debug_str");
19341 }
19342
19343 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19344
19345 static const char *
19346 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19347                                      bfd *abfd, LONGEST str_offset)
19348 {
19349   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19350                                               abfd, str_offset,
19351                                               &dwarf2_per_objfile->line_str,
19352                                               "DW_FORM_line_strp",
19353                                               ".debug_line_str");
19354 }
19355
19356 /* Read a string at offset STR_OFFSET in the .debug_str section from
19357    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19358    the string consists of a single NUL byte, return NULL; otherwise
19359    return a pointer to the string.  */
19360
19361 static const char *
19362 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19363                                LONGEST str_offset)
19364 {
19365   dwarf2_read_section (objfile, &dwz->str);
19366
19367   if (dwz->str.buffer == NULL)
19368     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19369              "section [in module %s]"),
19370            bfd_get_filename (dwz->dwz_bfd));
19371   if (str_offset >= dwz->str.size)
19372     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19373              ".debug_str section [in module %s]"),
19374            bfd_get_filename (dwz->dwz_bfd));
19375   gdb_assert (HOST_CHAR_BIT == 8);
19376   if (dwz->str.buffer[str_offset] == '\0')
19377     return NULL;
19378   return (const char *) (dwz->str.buffer + str_offset);
19379 }
19380
19381 /* Return pointer to string at .debug_str offset as read from BUF.
19382    BUF is assumed to be in a compilation unit described by CU_HEADER.
19383    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19384
19385 static const char *
19386 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19387                       const gdb_byte *buf,
19388                       const struct comp_unit_head *cu_header,
19389                       unsigned int *bytes_read_ptr)
19390 {
19391   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19392
19393   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19394 }
19395
19396 /* Return pointer to string at .debug_line_str offset as read from BUF.
19397    BUF is assumed to be in a compilation unit described by CU_HEADER.
19398    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19399
19400 static const char *
19401 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19402                            bfd *abfd, const gdb_byte *buf,
19403                            const struct comp_unit_head *cu_header,
19404                            unsigned int *bytes_read_ptr)
19405 {
19406   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19407
19408   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19409                                               str_offset);
19410 }
19411
19412 ULONGEST
19413 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19414                           unsigned int *bytes_read_ptr)
19415 {
19416   ULONGEST result;
19417   unsigned int num_read;
19418   int shift;
19419   unsigned char byte;
19420
19421   result = 0;
19422   shift = 0;
19423   num_read = 0;
19424   while (1)
19425     {
19426       byte = bfd_get_8 (abfd, buf);
19427       buf++;
19428       num_read++;
19429       result |= ((ULONGEST) (byte & 127) << shift);
19430       if ((byte & 128) == 0)
19431         {
19432           break;
19433         }
19434       shift += 7;
19435     }
19436   *bytes_read_ptr = num_read;
19437   return result;
19438 }
19439
19440 static LONGEST
19441 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19442                     unsigned int *bytes_read_ptr)
19443 {
19444   LONGEST result;
19445   int shift, num_read;
19446   unsigned char byte;
19447
19448   result = 0;
19449   shift = 0;
19450   num_read = 0;
19451   while (1)
19452     {
19453       byte = bfd_get_8 (abfd, buf);
19454       buf++;
19455       num_read++;
19456       result |= ((LONGEST) (byte & 127) << shift);
19457       shift += 7;
19458       if ((byte & 128) == 0)
19459         {
19460           break;
19461         }
19462     }
19463   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19464     result |= -(((LONGEST) 1) << shift);
19465   *bytes_read_ptr = num_read;
19466   return result;
19467 }
19468
19469 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19470    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19471    ADDR_SIZE is the size of addresses from the CU header.  */
19472
19473 static CORE_ADDR
19474 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19475                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19476 {
19477   struct objfile *objfile = dwarf2_per_objfile->objfile;
19478   bfd *abfd = objfile->obfd;
19479   const gdb_byte *info_ptr;
19480
19481   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19482   if (dwarf2_per_objfile->addr.buffer == NULL)
19483     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19484            objfile_name (objfile));
19485   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19486     error (_("DW_FORM_addr_index pointing outside of "
19487              ".debug_addr section [in module %s]"),
19488            objfile_name (objfile));
19489   info_ptr = (dwarf2_per_objfile->addr.buffer
19490               + addr_base + addr_index * addr_size);
19491   if (addr_size == 4)
19492     return bfd_get_32 (abfd, info_ptr);
19493   else
19494     return bfd_get_64 (abfd, info_ptr);
19495 }
19496
19497 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19498
19499 static CORE_ADDR
19500 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19501 {
19502   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19503                             cu->addr_base, cu->header.addr_size);
19504 }
19505
19506 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19507
19508 static CORE_ADDR
19509 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19510                              unsigned int *bytes_read)
19511 {
19512   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19513   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19514
19515   return read_addr_index (cu, addr_index);
19516 }
19517
19518 /* Data structure to pass results from dwarf2_read_addr_index_reader
19519    back to dwarf2_read_addr_index.  */
19520
19521 struct dwarf2_read_addr_index_data
19522 {
19523   ULONGEST addr_base;
19524   int addr_size;
19525 };
19526
19527 /* die_reader_func for dwarf2_read_addr_index.  */
19528
19529 static void
19530 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19531                                const gdb_byte *info_ptr,
19532                                struct die_info *comp_unit_die,
19533                                int has_children,
19534                                void *data)
19535 {
19536   struct dwarf2_cu *cu = reader->cu;
19537   struct dwarf2_read_addr_index_data *aidata =
19538     (struct dwarf2_read_addr_index_data *) data;
19539
19540   aidata->addr_base = cu->addr_base;
19541   aidata->addr_size = cu->header.addr_size;
19542 }
19543
19544 /* Given an index in .debug_addr, fetch the value.
19545    NOTE: This can be called during dwarf expression evaluation,
19546    long after the debug information has been read, and thus per_cu->cu
19547    may no longer exist.  */
19548
19549 CORE_ADDR
19550 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19551                         unsigned int addr_index)
19552 {
19553   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19554   struct dwarf2_cu *cu = per_cu->cu;
19555   ULONGEST addr_base;
19556   int addr_size;
19557
19558   /* We need addr_base and addr_size.
19559      If we don't have PER_CU->cu, we have to get it.
19560      Nasty, but the alternative is storing the needed info in PER_CU,
19561      which at this point doesn't seem justified: it's not clear how frequently
19562      it would get used and it would increase the size of every PER_CU.
19563      Entry points like dwarf2_per_cu_addr_size do a similar thing
19564      so we're not in uncharted territory here.
19565      Alas we need to be a bit more complicated as addr_base is contained
19566      in the DIE.
19567
19568      We don't need to read the entire CU(/TU).
19569      We just need the header and top level die.
19570
19571      IWBN to use the aging mechanism to let us lazily later discard the CU.
19572      For now we skip this optimization.  */
19573
19574   if (cu != NULL)
19575     {
19576       addr_base = cu->addr_base;
19577       addr_size = cu->header.addr_size;
19578     }
19579   else
19580     {
19581       struct dwarf2_read_addr_index_data aidata;
19582
19583       /* Note: We can't use init_cutu_and_read_dies_simple here,
19584          we need addr_base.  */
19585       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19586                                dwarf2_read_addr_index_reader, &aidata);
19587       addr_base = aidata.addr_base;
19588       addr_size = aidata.addr_size;
19589     }
19590
19591   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19592                             addr_size);
19593 }
19594
19595 /* Given a DW_FORM_GNU_str_index, fetch the string.
19596    This is only used by the Fission support.  */
19597
19598 static const char *
19599 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19600 {
19601   struct dwarf2_cu *cu = reader->cu;
19602   struct dwarf2_per_objfile *dwarf2_per_objfile
19603     = cu->per_cu->dwarf2_per_objfile;
19604   struct objfile *objfile = dwarf2_per_objfile->objfile;
19605   const char *objf_name = objfile_name (objfile);
19606   bfd *abfd = objfile->obfd;
19607   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19608   struct dwarf2_section_info *str_offsets_section =
19609     &reader->dwo_file->sections.str_offsets;
19610   const gdb_byte *info_ptr;
19611   ULONGEST str_offset;
19612   static const char form_name[] = "DW_FORM_GNU_str_index";
19613
19614   dwarf2_read_section (objfile, str_section);
19615   dwarf2_read_section (objfile, str_offsets_section);
19616   if (str_section->buffer == NULL)
19617     error (_("%s used without .debug_str.dwo section"
19618              " in CU at offset %s [in module %s]"),
19619            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19620   if (str_offsets_section->buffer == NULL)
19621     error (_("%s used without .debug_str_offsets.dwo section"
19622              " in CU at offset %s [in module %s]"),
19623            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19624   if (str_index * cu->header.offset_size >= str_offsets_section->size)
19625     error (_("%s pointing outside of .debug_str_offsets.dwo"
19626              " section in CU at offset %s [in module %s]"),
19627            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19628   info_ptr = (str_offsets_section->buffer
19629               + str_index * cu->header.offset_size);
19630   if (cu->header.offset_size == 4)
19631     str_offset = bfd_get_32 (abfd, info_ptr);
19632   else
19633     str_offset = bfd_get_64 (abfd, info_ptr);
19634   if (str_offset >= str_section->size)
19635     error (_("Offset from %s pointing outside of"
19636              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19637            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19638   return (const char *) (str_section->buffer + str_offset);
19639 }
19640
19641 /* Return the length of an LEB128 number in BUF.  */
19642
19643 static int
19644 leb128_size (const gdb_byte *buf)
19645 {
19646   const gdb_byte *begin = buf;
19647   gdb_byte byte;
19648
19649   while (1)
19650     {
19651       byte = *buf++;
19652       if ((byte & 128) == 0)
19653         return buf - begin;
19654     }
19655 }
19656
19657 static void
19658 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19659 {
19660   switch (lang)
19661     {
19662     case DW_LANG_C89:
19663     case DW_LANG_C99:
19664     case DW_LANG_C11:
19665     case DW_LANG_C:
19666     case DW_LANG_UPC:
19667       cu->language = language_c;
19668       break;
19669     case DW_LANG_Java:
19670     case DW_LANG_C_plus_plus:
19671     case DW_LANG_C_plus_plus_11:
19672     case DW_LANG_C_plus_plus_14:
19673       cu->language = language_cplus;
19674       break;
19675     case DW_LANG_D:
19676       cu->language = language_d;
19677       break;
19678     case DW_LANG_Fortran77:
19679     case DW_LANG_Fortran90:
19680     case DW_LANG_Fortran95:
19681     case DW_LANG_Fortran03:
19682     case DW_LANG_Fortran08:
19683       cu->language = language_fortran;
19684       break;
19685     case DW_LANG_Go:
19686       cu->language = language_go;
19687       break;
19688     case DW_LANG_Mips_Assembler:
19689       cu->language = language_asm;
19690       break;
19691     case DW_LANG_Ada83:
19692     case DW_LANG_Ada95:
19693       cu->language = language_ada;
19694       break;
19695     case DW_LANG_Modula2:
19696       cu->language = language_m2;
19697       break;
19698     case DW_LANG_Pascal83:
19699       cu->language = language_pascal;
19700       break;
19701     case DW_LANG_ObjC:
19702       cu->language = language_objc;
19703       break;
19704     case DW_LANG_Rust:
19705     case DW_LANG_Rust_old:
19706       cu->language = language_rust;
19707       break;
19708     case DW_LANG_Cobol74:
19709     case DW_LANG_Cobol85:
19710     default:
19711       cu->language = language_minimal;
19712       break;
19713     }
19714   cu->language_defn = language_def (cu->language);
19715 }
19716
19717 /* Return the named attribute or NULL if not there.  */
19718
19719 static struct attribute *
19720 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19721 {
19722   for (;;)
19723     {
19724       unsigned int i;
19725       struct attribute *spec = NULL;
19726
19727       for (i = 0; i < die->num_attrs; ++i)
19728         {
19729           if (die->attrs[i].name == name)
19730             return &die->attrs[i];
19731           if (die->attrs[i].name == DW_AT_specification
19732               || die->attrs[i].name == DW_AT_abstract_origin)
19733             spec = &die->attrs[i];
19734         }
19735
19736       if (!spec)
19737         break;
19738
19739       die = follow_die_ref (die, spec, &cu);
19740     }
19741
19742   return NULL;
19743 }
19744
19745 /* Return the named attribute or NULL if not there,
19746    but do not follow DW_AT_specification, etc.
19747    This is for use in contexts where we're reading .debug_types dies.
19748    Following DW_AT_specification, DW_AT_abstract_origin will take us
19749    back up the chain, and we want to go down.  */
19750
19751 static struct attribute *
19752 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19753 {
19754   unsigned int i;
19755
19756   for (i = 0; i < die->num_attrs; ++i)
19757     if (die->attrs[i].name == name)
19758       return &die->attrs[i];
19759
19760   return NULL;
19761 }
19762
19763 /* Return the string associated with a string-typed attribute, or NULL if it
19764    is either not found or is of an incorrect type.  */
19765
19766 static const char *
19767 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19768 {
19769   struct attribute *attr;
19770   const char *str = NULL;
19771
19772   attr = dwarf2_attr (die, name, cu);
19773
19774   if (attr != NULL)
19775     {
19776       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19777           || attr->form == DW_FORM_string
19778           || attr->form == DW_FORM_GNU_str_index
19779           || attr->form == DW_FORM_GNU_strp_alt)
19780         str = DW_STRING (attr);
19781       else
19782         complaint (_("string type expected for attribute %s for "
19783                      "DIE at %s in module %s"),
19784                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19785                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19786     }
19787
19788   return str;
19789 }
19790
19791 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19792    and holds a non-zero value.  This function should only be used for
19793    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19794
19795 static int
19796 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19797 {
19798   struct attribute *attr = dwarf2_attr (die, name, cu);
19799
19800   return (attr && DW_UNSND (attr));
19801 }
19802
19803 static int
19804 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19805 {
19806   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19807      which value is non-zero.  However, we have to be careful with
19808      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19809      (via dwarf2_flag_true_p) follows this attribute.  So we may
19810      end up accidently finding a declaration attribute that belongs
19811      to a different DIE referenced by the specification attribute,
19812      even though the given DIE does not have a declaration attribute.  */
19813   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19814           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19815 }
19816
19817 /* Return the die giving the specification for DIE, if there is
19818    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19819    containing the return value on output.  If there is no
19820    specification, but there is an abstract origin, that is
19821    returned.  */
19822
19823 static struct die_info *
19824 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19825 {
19826   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19827                                              *spec_cu);
19828
19829   if (spec_attr == NULL)
19830     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19831
19832   if (spec_attr == NULL)
19833     return NULL;
19834   else
19835     return follow_die_ref (die, spec_attr, spec_cu);
19836 }
19837
19838 /* Stub for free_line_header to match void * callback types.  */
19839
19840 static void
19841 free_line_header_voidp (void *arg)
19842 {
19843   struct line_header *lh = (struct line_header *) arg;
19844
19845   delete lh;
19846 }
19847
19848 void
19849 line_header::add_include_dir (const char *include_dir)
19850 {
19851   if (dwarf_line_debug >= 2)
19852     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19853                         include_dirs.size () + 1, include_dir);
19854
19855   include_dirs.push_back (include_dir);
19856 }
19857
19858 void
19859 line_header::add_file_name (const char *name,
19860                             dir_index d_index,
19861                             unsigned int mod_time,
19862                             unsigned int length)
19863 {
19864   if (dwarf_line_debug >= 2)
19865     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19866                         (unsigned) file_names.size () + 1, name);
19867
19868   file_names.emplace_back (name, d_index, mod_time, length);
19869 }
19870
19871 /* A convenience function to find the proper .debug_line section for a CU.  */
19872
19873 static struct dwarf2_section_info *
19874 get_debug_line_section (struct dwarf2_cu *cu)
19875 {
19876   struct dwarf2_section_info *section;
19877   struct dwarf2_per_objfile *dwarf2_per_objfile
19878     = cu->per_cu->dwarf2_per_objfile;
19879
19880   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19881      DWO file.  */
19882   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19883     section = &cu->dwo_unit->dwo_file->sections.line;
19884   else if (cu->per_cu->is_dwz)
19885     {
19886       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19887
19888       section = &dwz->line;
19889     }
19890   else
19891     section = &dwarf2_per_objfile->line;
19892
19893   return section;
19894 }
19895
19896 /* Read directory or file name entry format, starting with byte of
19897    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19898    entries count and the entries themselves in the described entry
19899    format.  */
19900
19901 static void
19902 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
19903                         bfd *abfd, const gdb_byte **bufp,
19904                         struct line_header *lh,
19905                         const struct comp_unit_head *cu_header,
19906                         void (*callback) (struct line_header *lh,
19907                                           const char *name,
19908                                           dir_index d_index,
19909                                           unsigned int mod_time,
19910                                           unsigned int length))
19911 {
19912   gdb_byte format_count, formati;
19913   ULONGEST data_count, datai;
19914   const gdb_byte *buf = *bufp;
19915   const gdb_byte *format_header_data;
19916   unsigned int bytes_read;
19917
19918   format_count = read_1_byte (abfd, buf);
19919   buf += 1;
19920   format_header_data = buf;
19921   for (formati = 0; formati < format_count; formati++)
19922     {
19923       read_unsigned_leb128 (abfd, buf, &bytes_read);
19924       buf += bytes_read;
19925       read_unsigned_leb128 (abfd, buf, &bytes_read);
19926       buf += bytes_read;
19927     }
19928
19929   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
19930   buf += bytes_read;
19931   for (datai = 0; datai < data_count; datai++)
19932     {
19933       const gdb_byte *format = format_header_data;
19934       struct file_entry fe;
19935
19936       for (formati = 0; formati < format_count; formati++)
19937         {
19938           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
19939           format += bytes_read;
19940
19941           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
19942           format += bytes_read;
19943
19944           gdb::optional<const char *> string;
19945           gdb::optional<unsigned int> uint;
19946
19947           switch (form)
19948             {
19949             case DW_FORM_string:
19950               string.emplace (read_direct_string (abfd, buf, &bytes_read));
19951               buf += bytes_read;
19952               break;
19953
19954             case DW_FORM_line_strp:
19955               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
19956                                                          abfd, buf,
19957                                                          cu_header,
19958                                                          &bytes_read));
19959               buf += bytes_read;
19960               break;
19961
19962             case DW_FORM_data1:
19963               uint.emplace (read_1_byte (abfd, buf));
19964               buf += 1;
19965               break;
19966
19967             case DW_FORM_data2:
19968               uint.emplace (read_2_bytes (abfd, buf));
19969               buf += 2;
19970               break;
19971
19972             case DW_FORM_data4:
19973               uint.emplace (read_4_bytes (abfd, buf));
19974               buf += 4;
19975               break;
19976
19977             case DW_FORM_data8:
19978               uint.emplace (read_8_bytes (abfd, buf));
19979               buf += 8;
19980               break;
19981
19982             case DW_FORM_udata:
19983               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
19984               buf += bytes_read;
19985               break;
19986
19987             case DW_FORM_block:
19988               /* It is valid only for DW_LNCT_timestamp which is ignored by
19989                  current GDB.  */
19990               break;
19991             }
19992
19993           switch (content_type)
19994             {
19995             case DW_LNCT_path:
19996               if (string.has_value ())
19997                 fe.name = *string;
19998               break;
19999             case DW_LNCT_directory_index:
20000               if (uint.has_value ())
20001                 fe.d_index = (dir_index) *uint;
20002               break;
20003             case DW_LNCT_timestamp:
20004               if (uint.has_value ())
20005                 fe.mod_time = *uint;
20006               break;
20007             case DW_LNCT_size:
20008               if (uint.has_value ())
20009                 fe.length = *uint;
20010               break;
20011             case DW_LNCT_MD5:
20012               break;
20013             default:
20014               complaint (_("Unknown format content type %s"),
20015                          pulongest (content_type));
20016             }
20017         }
20018
20019       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20020     }
20021
20022   *bufp = buf;
20023 }
20024
20025 /* Read the statement program header starting at OFFSET in
20026    .debug_line, or .debug_line.dwo.  Return a pointer
20027    to a struct line_header, allocated using xmalloc.
20028    Returns NULL if there is a problem reading the header, e.g., if it
20029    has a version we don't understand.
20030
20031    NOTE: the strings in the include directory and file name tables of
20032    the returned object point into the dwarf line section buffer,
20033    and must not be freed.  */
20034
20035 static line_header_up
20036 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20037 {
20038   const gdb_byte *line_ptr;
20039   unsigned int bytes_read, offset_size;
20040   int i;
20041   const char *cur_dir, *cur_file;
20042   struct dwarf2_section_info *section;
20043   bfd *abfd;
20044   struct dwarf2_per_objfile *dwarf2_per_objfile
20045     = cu->per_cu->dwarf2_per_objfile;
20046
20047   section = get_debug_line_section (cu);
20048   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20049   if (section->buffer == NULL)
20050     {
20051       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20052         complaint (_("missing .debug_line.dwo section"));
20053       else
20054         complaint (_("missing .debug_line section"));
20055       return 0;
20056     }
20057
20058   /* We can't do this until we know the section is non-empty.
20059      Only then do we know we have such a section.  */
20060   abfd = get_section_bfd_owner (section);
20061
20062   /* Make sure that at least there's room for the total_length field.
20063      That could be 12 bytes long, but we're just going to fudge that.  */
20064   if (to_underlying (sect_off) + 4 >= section->size)
20065     {
20066       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20067       return 0;
20068     }
20069
20070   line_header_up lh (new line_header ());
20071
20072   lh->sect_off = sect_off;
20073   lh->offset_in_dwz = cu->per_cu->is_dwz;
20074
20075   line_ptr = section->buffer + to_underlying (sect_off);
20076
20077   /* Read in the header.  */
20078   lh->total_length =
20079     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20080                                             &bytes_read, &offset_size);
20081   line_ptr += bytes_read;
20082   if (line_ptr + lh->total_length > (section->buffer + section->size))
20083     {
20084       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20085       return 0;
20086     }
20087   lh->statement_program_end = line_ptr + lh->total_length;
20088   lh->version = read_2_bytes (abfd, line_ptr);
20089   line_ptr += 2;
20090   if (lh->version > 5)
20091     {
20092       /* This is a version we don't understand.  The format could have
20093          changed in ways we don't handle properly so just punt.  */
20094       complaint (_("unsupported version in .debug_line section"));
20095       return NULL;
20096     }
20097   if (lh->version >= 5)
20098     {
20099       gdb_byte segment_selector_size;
20100
20101       /* Skip address size.  */
20102       read_1_byte (abfd, line_ptr);
20103       line_ptr += 1;
20104
20105       segment_selector_size = read_1_byte (abfd, line_ptr);
20106       line_ptr += 1;
20107       if (segment_selector_size != 0)
20108         {
20109           complaint (_("unsupported segment selector size %u "
20110                        "in .debug_line section"),
20111                      segment_selector_size);
20112           return NULL;
20113         }
20114     }
20115   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20116   line_ptr += offset_size;
20117   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20118   line_ptr += 1;
20119   if (lh->version >= 4)
20120     {
20121       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20122       line_ptr += 1;
20123     }
20124   else
20125     lh->maximum_ops_per_instruction = 1;
20126
20127   if (lh->maximum_ops_per_instruction == 0)
20128     {
20129       lh->maximum_ops_per_instruction = 1;
20130       complaint (_("invalid maximum_ops_per_instruction "
20131                    "in `.debug_line' section"));
20132     }
20133
20134   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20135   line_ptr += 1;
20136   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20137   line_ptr += 1;
20138   lh->line_range = read_1_byte (abfd, line_ptr);
20139   line_ptr += 1;
20140   lh->opcode_base = read_1_byte (abfd, line_ptr);
20141   line_ptr += 1;
20142   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20143
20144   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20145   for (i = 1; i < lh->opcode_base; ++i)
20146     {
20147       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20148       line_ptr += 1;
20149     }
20150
20151   if (lh->version >= 5)
20152     {
20153       /* Read directory table.  */
20154       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20155                               &cu->header,
20156                               [] (struct line_header *lh, const char *name,
20157                                   dir_index d_index, unsigned int mod_time,
20158                                   unsigned int length)
20159         {
20160           lh->add_include_dir (name);
20161         });
20162
20163       /* Read file name table.  */
20164       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20165                               &cu->header,
20166                               [] (struct line_header *lh, const char *name,
20167                                   dir_index d_index, unsigned int mod_time,
20168                                   unsigned int length)
20169         {
20170           lh->add_file_name (name, d_index, mod_time, length);
20171         });
20172     }
20173   else
20174     {
20175       /* Read directory table.  */
20176       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20177         {
20178           line_ptr += bytes_read;
20179           lh->add_include_dir (cur_dir);
20180         }
20181       line_ptr += bytes_read;
20182
20183       /* Read file name table.  */
20184       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20185         {
20186           unsigned int mod_time, length;
20187           dir_index d_index;
20188
20189           line_ptr += bytes_read;
20190           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20191           line_ptr += bytes_read;
20192           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20193           line_ptr += bytes_read;
20194           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20195           line_ptr += bytes_read;
20196
20197           lh->add_file_name (cur_file, d_index, mod_time, length);
20198         }
20199       line_ptr += bytes_read;
20200     }
20201   lh->statement_program_start = line_ptr;
20202
20203   if (line_ptr > (section->buffer + section->size))
20204     complaint (_("line number info header doesn't "
20205                  "fit in `.debug_line' section"));
20206
20207   return lh;
20208 }
20209
20210 /* Subroutine of dwarf_decode_lines to simplify it.
20211    Return the file name of the psymtab for included file FILE_INDEX
20212    in line header LH of PST.
20213    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20214    If space for the result is malloc'd, *NAME_HOLDER will be set.
20215    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20216
20217 static const char *
20218 psymtab_include_file_name (const struct line_header *lh, int file_index,
20219                            const struct partial_symtab *pst,
20220                            const char *comp_dir,
20221                            gdb::unique_xmalloc_ptr<char> *name_holder)
20222 {
20223   const file_entry &fe = lh->file_names[file_index];
20224   const char *include_name = fe.name;
20225   const char *include_name_to_compare = include_name;
20226   const char *pst_filename;
20227   int file_is_pst;
20228
20229   const char *dir_name = fe.include_dir (lh);
20230
20231   gdb::unique_xmalloc_ptr<char> hold_compare;
20232   if (!IS_ABSOLUTE_PATH (include_name)
20233       && (dir_name != NULL || comp_dir != NULL))
20234     {
20235       /* Avoid creating a duplicate psymtab for PST.
20236          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20237          Before we do the comparison, however, we need to account
20238          for DIR_NAME and COMP_DIR.
20239          First prepend dir_name (if non-NULL).  If we still don't
20240          have an absolute path prepend comp_dir (if non-NULL).
20241          However, the directory we record in the include-file's
20242          psymtab does not contain COMP_DIR (to match the
20243          corresponding symtab(s)).
20244
20245          Example:
20246
20247          bash$ cd /tmp
20248          bash$ gcc -g ./hello.c
20249          include_name = "hello.c"
20250          dir_name = "."
20251          DW_AT_comp_dir = comp_dir = "/tmp"
20252          DW_AT_name = "./hello.c"
20253
20254       */
20255
20256       if (dir_name != NULL)
20257         {
20258           name_holder->reset (concat (dir_name, SLASH_STRING,
20259                                       include_name, (char *) NULL));
20260           include_name = name_holder->get ();
20261           include_name_to_compare = include_name;
20262         }
20263       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20264         {
20265           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20266                                       include_name, (char *) NULL));
20267           include_name_to_compare = hold_compare.get ();
20268         }
20269     }
20270
20271   pst_filename = pst->filename;
20272   gdb::unique_xmalloc_ptr<char> copied_name;
20273   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20274     {
20275       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20276                                  pst_filename, (char *) NULL));
20277       pst_filename = copied_name.get ();
20278     }
20279
20280   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20281
20282   if (file_is_pst)
20283     return NULL;
20284   return include_name;
20285 }
20286
20287 /* State machine to track the state of the line number program.  */
20288
20289 class lnp_state_machine
20290 {
20291 public:
20292   /* Initialize a machine state for the start of a line number
20293      program.  */
20294   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20295
20296   file_entry *current_file ()
20297   {
20298     /* lh->file_names is 0-based, but the file name numbers in the
20299        statement program are 1-based.  */
20300     return m_line_header->file_name_at (m_file);
20301   }
20302
20303   /* Record the line in the state machine.  END_SEQUENCE is true if
20304      we're processing the end of a sequence.  */
20305   void record_line (bool end_sequence);
20306
20307   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20308      nop-out rest of the lines in this sequence.  */
20309   void check_line_address (struct dwarf2_cu *cu,
20310                            const gdb_byte *line_ptr,
20311                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20312
20313   void handle_set_discriminator (unsigned int discriminator)
20314   {
20315     m_discriminator = discriminator;
20316     m_line_has_non_zero_discriminator |= discriminator != 0;
20317   }
20318
20319   /* Handle DW_LNE_set_address.  */
20320   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20321   {
20322     m_op_index = 0;
20323     address += baseaddr;
20324     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20325   }
20326
20327   /* Handle DW_LNS_advance_pc.  */
20328   void handle_advance_pc (CORE_ADDR adjust);
20329
20330   /* Handle a special opcode.  */
20331   void handle_special_opcode (unsigned char op_code);
20332
20333   /* Handle DW_LNS_advance_line.  */
20334   void handle_advance_line (int line_delta)
20335   {
20336     advance_line (line_delta);
20337   }
20338
20339   /* Handle DW_LNS_set_file.  */
20340   void handle_set_file (file_name_index file);
20341
20342   /* Handle DW_LNS_negate_stmt.  */
20343   void handle_negate_stmt ()
20344   {
20345     m_is_stmt = !m_is_stmt;
20346   }
20347
20348   /* Handle DW_LNS_const_add_pc.  */
20349   void handle_const_add_pc ();
20350
20351   /* Handle DW_LNS_fixed_advance_pc.  */
20352   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20353   {
20354     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20355     m_op_index = 0;
20356   }
20357
20358   /* Handle DW_LNS_copy.  */
20359   void handle_copy ()
20360   {
20361     record_line (false);
20362     m_discriminator = 0;
20363   }
20364
20365   /* Handle DW_LNE_end_sequence.  */
20366   void handle_end_sequence ()
20367   {
20368     m_record_line_callback = ::record_line;
20369   }
20370
20371 private:
20372   /* Advance the line by LINE_DELTA.  */
20373   void advance_line (int line_delta)
20374   {
20375     m_line += line_delta;
20376
20377     if (line_delta != 0)
20378       m_line_has_non_zero_discriminator = m_discriminator != 0;
20379   }
20380
20381   gdbarch *m_gdbarch;
20382
20383   /* True if we're recording lines.
20384      Otherwise we're building partial symtabs and are just interested in
20385      finding include files mentioned by the line number program.  */
20386   bool m_record_lines_p;
20387
20388   /* The line number header.  */
20389   line_header *m_line_header;
20390
20391   /* These are part of the standard DWARF line number state machine,
20392      and initialized according to the DWARF spec.  */
20393
20394   unsigned char m_op_index = 0;
20395   /* The line table index (1-based) of the current file.  */
20396   file_name_index m_file = (file_name_index) 1;
20397   unsigned int m_line = 1;
20398
20399   /* These are initialized in the constructor.  */
20400
20401   CORE_ADDR m_address;
20402   bool m_is_stmt;
20403   unsigned int m_discriminator;
20404
20405   /* Additional bits of state we need to track.  */
20406
20407   /* The last file that we called dwarf2_start_subfile for.
20408      This is only used for TLLs.  */
20409   unsigned int m_last_file = 0;
20410   /* The last file a line number was recorded for.  */
20411   struct subfile *m_last_subfile = NULL;
20412
20413   /* The function to call to record a line.  */
20414   record_line_ftype *m_record_line_callback = NULL;
20415
20416   /* The last line number that was recorded, used to coalesce
20417      consecutive entries for the same line.  This can happen, for
20418      example, when discriminators are present.  PR 17276.  */
20419   unsigned int m_last_line = 0;
20420   bool m_line_has_non_zero_discriminator = false;
20421 };
20422
20423 void
20424 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20425 {
20426   CORE_ADDR addr_adj = (((m_op_index + adjust)
20427                          / m_line_header->maximum_ops_per_instruction)
20428                         * m_line_header->minimum_instruction_length);
20429   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20430   m_op_index = ((m_op_index + adjust)
20431                 % m_line_header->maximum_ops_per_instruction);
20432 }
20433
20434 void
20435 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20436 {
20437   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20438   CORE_ADDR addr_adj = (((m_op_index
20439                           + (adj_opcode / m_line_header->line_range))
20440                          / m_line_header->maximum_ops_per_instruction)
20441                         * m_line_header->minimum_instruction_length);
20442   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20443   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20444                 % m_line_header->maximum_ops_per_instruction);
20445
20446   int line_delta = (m_line_header->line_base
20447                     + (adj_opcode % m_line_header->line_range));
20448   advance_line (line_delta);
20449   record_line (false);
20450   m_discriminator = 0;
20451 }
20452
20453 void
20454 lnp_state_machine::handle_set_file (file_name_index file)
20455 {
20456   m_file = file;
20457
20458   const file_entry *fe = current_file ();
20459   if (fe == NULL)
20460     dwarf2_debug_line_missing_file_complaint ();
20461   else if (m_record_lines_p)
20462     {
20463       const char *dir = fe->include_dir (m_line_header);
20464
20465       m_last_subfile = current_subfile;
20466       m_line_has_non_zero_discriminator = m_discriminator != 0;
20467       dwarf2_start_subfile (fe->name, dir);
20468     }
20469 }
20470
20471 void
20472 lnp_state_machine::handle_const_add_pc ()
20473 {
20474   CORE_ADDR adjust
20475     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20476
20477   CORE_ADDR addr_adj
20478     = (((m_op_index + adjust)
20479         / m_line_header->maximum_ops_per_instruction)
20480        * m_line_header->minimum_instruction_length);
20481
20482   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20483   m_op_index = ((m_op_index + adjust)
20484                 % m_line_header->maximum_ops_per_instruction);
20485 }
20486
20487 /* Ignore this record_line request.  */
20488
20489 static void
20490 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20491 {
20492   return;
20493 }
20494
20495 /* Return non-zero if we should add LINE to the line number table.
20496    LINE is the line to add, LAST_LINE is the last line that was added,
20497    LAST_SUBFILE is the subfile for LAST_LINE.
20498    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20499    had a non-zero discriminator.
20500
20501    We have to be careful in the presence of discriminators.
20502    E.g., for this line:
20503
20504      for (i = 0; i < 100000; i++);
20505
20506    clang can emit four line number entries for that one line,
20507    each with a different discriminator.
20508    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20509
20510    However, we want gdb to coalesce all four entries into one.
20511    Otherwise the user could stepi into the middle of the line and
20512    gdb would get confused about whether the pc really was in the
20513    middle of the line.
20514
20515    Things are further complicated by the fact that two consecutive
20516    line number entries for the same line is a heuristic used by gcc
20517    to denote the end of the prologue.  So we can't just discard duplicate
20518    entries, we have to be selective about it.  The heuristic we use is
20519    that we only collapse consecutive entries for the same line if at least
20520    one of those entries has a non-zero discriminator.  PR 17276.
20521
20522    Note: Addresses in the line number state machine can never go backwards
20523    within one sequence, thus this coalescing is ok.  */
20524
20525 static int
20526 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20527                      int line_has_non_zero_discriminator,
20528                      struct subfile *last_subfile)
20529 {
20530   if (current_subfile != last_subfile)
20531     return 1;
20532   if (line != last_line)
20533     return 1;
20534   /* Same line for the same file that we've seen already.
20535      As a last check, for pr 17276, only record the line if the line
20536      has never had a non-zero discriminator.  */
20537   if (!line_has_non_zero_discriminator)
20538     return 1;
20539   return 0;
20540 }
20541
20542 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20543    in the line table of subfile SUBFILE.  */
20544
20545 static void
20546 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20547                      unsigned int line, CORE_ADDR address,
20548                      record_line_ftype p_record_line)
20549 {
20550   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20551
20552   if (dwarf_line_debug)
20553     {
20554       fprintf_unfiltered (gdb_stdlog,
20555                           "Recording line %u, file %s, address %s\n",
20556                           line, lbasename (subfile->name),
20557                           paddress (gdbarch, address));
20558     }
20559
20560   (*p_record_line) (subfile, line, addr);
20561 }
20562
20563 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20564    Mark the end of a set of line number records.
20565    The arguments are the same as for dwarf_record_line_1.
20566    If SUBFILE is NULL the request is ignored.  */
20567
20568 static void
20569 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20570                    CORE_ADDR address, record_line_ftype p_record_line)
20571 {
20572   if (subfile == NULL)
20573     return;
20574
20575   if (dwarf_line_debug)
20576     {
20577       fprintf_unfiltered (gdb_stdlog,
20578                           "Finishing current line, file %s, address %s\n",
20579                           lbasename (subfile->name),
20580                           paddress (gdbarch, address));
20581     }
20582
20583   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20584 }
20585
20586 void
20587 lnp_state_machine::record_line (bool end_sequence)
20588 {
20589   if (dwarf_line_debug)
20590     {
20591       fprintf_unfiltered (gdb_stdlog,
20592                           "Processing actual line %u: file %u,"
20593                           " address %s, is_stmt %u, discrim %u\n",
20594                           m_line, to_underlying (m_file),
20595                           paddress (m_gdbarch, m_address),
20596                           m_is_stmt, m_discriminator);
20597     }
20598
20599   file_entry *fe = current_file ();
20600
20601   if (fe == NULL)
20602     dwarf2_debug_line_missing_file_complaint ();
20603   /* For now we ignore lines not starting on an instruction boundary.
20604      But not when processing end_sequence for compatibility with the
20605      previous version of the code.  */
20606   else if (m_op_index == 0 || end_sequence)
20607     {
20608       fe->included_p = 1;
20609       if (m_record_lines_p && m_is_stmt)
20610         {
20611           if (m_last_subfile != current_subfile || end_sequence)
20612             {
20613               dwarf_finish_line (m_gdbarch, m_last_subfile,
20614                                  m_address, m_record_line_callback);
20615             }
20616
20617           if (!end_sequence)
20618             {
20619               if (dwarf_record_line_p (m_line, m_last_line,
20620                                        m_line_has_non_zero_discriminator,
20621                                        m_last_subfile))
20622                 {
20623                   dwarf_record_line_1 (m_gdbarch, current_subfile,
20624                                        m_line, m_address,
20625                                        m_record_line_callback);
20626                 }
20627               m_last_subfile = current_subfile;
20628               m_last_line = m_line;
20629             }
20630         }
20631     }
20632 }
20633
20634 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20635                                       bool record_lines_p)
20636 {
20637   m_gdbarch = arch;
20638   m_record_lines_p = record_lines_p;
20639   m_line_header = lh;
20640
20641   m_record_line_callback = ::record_line;
20642
20643   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20644      was a line entry for it so that the backend has a chance to adjust it
20645      and also record it in case it needs it.  This is currently used by MIPS
20646      code, cf. `mips_adjust_dwarf2_line'.  */
20647   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20648   m_is_stmt = lh->default_is_stmt;
20649   m_discriminator = 0;
20650 }
20651
20652 void
20653 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20654                                        const gdb_byte *line_ptr,
20655                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20656 {
20657   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20658      the pc range of the CU.  However, we restrict the test to only ADDRESS
20659      values of zero to preserve GDB's previous behaviour which is to handle
20660      the specific case of a function being GC'd by the linker.  */
20661
20662   if (address == 0 && address < unrelocated_lowpc)
20663     {
20664       /* This line table is for a function which has been
20665          GCd by the linker.  Ignore it.  PR gdb/12528 */
20666
20667       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20668       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20669
20670       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20671                  line_offset, objfile_name (objfile));
20672       m_record_line_callback = noop_record_line;
20673       /* Note: record_line_callback is left as noop_record_line until
20674          we see DW_LNE_end_sequence.  */
20675     }
20676 }
20677
20678 /* Subroutine of dwarf_decode_lines to simplify it.
20679    Process the line number information in LH.
20680    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20681    program in order to set included_p for every referenced header.  */
20682
20683 static void
20684 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20685                       const int decode_for_pst_p, CORE_ADDR lowpc)
20686 {
20687   const gdb_byte *line_ptr, *extended_end;
20688   const gdb_byte *line_end;
20689   unsigned int bytes_read, extended_len;
20690   unsigned char op_code, extended_op;
20691   CORE_ADDR baseaddr;
20692   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20693   bfd *abfd = objfile->obfd;
20694   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20695   /* True if we're recording line info (as opposed to building partial
20696      symtabs and just interested in finding include files mentioned by
20697      the line number program).  */
20698   bool record_lines_p = !decode_for_pst_p;
20699
20700   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20701
20702   line_ptr = lh->statement_program_start;
20703   line_end = lh->statement_program_end;
20704
20705   /* Read the statement sequences until there's nothing left.  */
20706   while (line_ptr < line_end)
20707     {
20708       /* The DWARF line number program state machine.  Reset the state
20709          machine at the start of each sequence.  */
20710       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20711       bool end_sequence = false;
20712
20713       if (record_lines_p)
20714         {
20715           /* Start a subfile for the current file of the state
20716              machine.  */
20717           const file_entry *fe = state_machine.current_file ();
20718
20719           if (fe != NULL)
20720             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20721         }
20722
20723       /* Decode the table.  */
20724       while (line_ptr < line_end && !end_sequence)
20725         {
20726           op_code = read_1_byte (abfd, line_ptr);
20727           line_ptr += 1;
20728
20729           if (op_code >= lh->opcode_base)
20730             {
20731               /* Special opcode.  */
20732               state_machine.handle_special_opcode (op_code);
20733             }
20734           else switch (op_code)
20735             {
20736             case DW_LNS_extended_op:
20737               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20738                                                    &bytes_read);
20739               line_ptr += bytes_read;
20740               extended_end = line_ptr + extended_len;
20741               extended_op = read_1_byte (abfd, line_ptr);
20742               line_ptr += 1;
20743               switch (extended_op)
20744                 {
20745                 case DW_LNE_end_sequence:
20746                   state_machine.handle_end_sequence ();
20747                   end_sequence = true;
20748                   break;
20749                 case DW_LNE_set_address:
20750                   {
20751                     CORE_ADDR address
20752                       = read_address (abfd, line_ptr, cu, &bytes_read);
20753                     line_ptr += bytes_read;
20754
20755                     state_machine.check_line_address (cu, line_ptr,
20756                                                       lowpc - baseaddr, address);
20757                     state_machine.handle_set_address (baseaddr, address);
20758                   }
20759                   break;
20760                 case DW_LNE_define_file:
20761                   {
20762                     const char *cur_file;
20763                     unsigned int mod_time, length;
20764                     dir_index dindex;
20765
20766                     cur_file = read_direct_string (abfd, line_ptr,
20767                                                    &bytes_read);
20768                     line_ptr += bytes_read;
20769                     dindex = (dir_index)
20770                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20771                     line_ptr += bytes_read;
20772                     mod_time =
20773                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20774                     line_ptr += bytes_read;
20775                     length =
20776                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20777                     line_ptr += bytes_read;
20778                     lh->add_file_name (cur_file, dindex, mod_time, length);
20779                   }
20780                   break;
20781                 case DW_LNE_set_discriminator:
20782                   {
20783                     /* The discriminator is not interesting to the
20784                        debugger; just ignore it.  We still need to
20785                        check its value though:
20786                        if there are consecutive entries for the same
20787                        (non-prologue) line we want to coalesce them.
20788                        PR 17276.  */
20789                     unsigned int discr
20790                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20791                     line_ptr += bytes_read;
20792
20793                     state_machine.handle_set_discriminator (discr);
20794                   }
20795                   break;
20796                 default:
20797                   complaint (_("mangled .debug_line section"));
20798                   return;
20799                 }
20800               /* Make sure that we parsed the extended op correctly.  If e.g.
20801                  we expected a different address size than the producer used,
20802                  we may have read the wrong number of bytes.  */
20803               if (line_ptr != extended_end)
20804                 {
20805                   complaint (_("mangled .debug_line section"));
20806                   return;
20807                 }
20808               break;
20809             case DW_LNS_copy:
20810               state_machine.handle_copy ();
20811               break;
20812             case DW_LNS_advance_pc:
20813               {
20814                 CORE_ADDR adjust
20815                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20816                 line_ptr += bytes_read;
20817
20818                 state_machine.handle_advance_pc (adjust);
20819               }
20820               break;
20821             case DW_LNS_advance_line:
20822               {
20823                 int line_delta
20824                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20825                 line_ptr += bytes_read;
20826
20827                 state_machine.handle_advance_line (line_delta);
20828               }
20829               break;
20830             case DW_LNS_set_file:
20831               {
20832                 file_name_index file
20833                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20834                                                             &bytes_read);
20835                 line_ptr += bytes_read;
20836
20837                 state_machine.handle_set_file (file);
20838               }
20839               break;
20840             case DW_LNS_set_column:
20841               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20842               line_ptr += bytes_read;
20843               break;
20844             case DW_LNS_negate_stmt:
20845               state_machine.handle_negate_stmt ();
20846               break;
20847             case DW_LNS_set_basic_block:
20848               break;
20849             /* Add to the address register of the state machine the
20850                address increment value corresponding to special opcode
20851                255.  I.e., this value is scaled by the minimum
20852                instruction length since special opcode 255 would have
20853                scaled the increment.  */
20854             case DW_LNS_const_add_pc:
20855               state_machine.handle_const_add_pc ();
20856               break;
20857             case DW_LNS_fixed_advance_pc:
20858               {
20859                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20860                 line_ptr += 2;
20861
20862                 state_machine.handle_fixed_advance_pc (addr_adj);
20863               }
20864               break;
20865             default:
20866               {
20867                 /* Unknown standard opcode, ignore it.  */
20868                 int i;
20869
20870                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20871                   {
20872                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20873                     line_ptr += bytes_read;
20874                   }
20875               }
20876             }
20877         }
20878
20879       if (!end_sequence)
20880         dwarf2_debug_line_missing_end_sequence_complaint ();
20881
20882       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20883          in which case we still finish recording the last line).  */
20884       state_machine.record_line (true);
20885     }
20886 }
20887
20888 /* Decode the Line Number Program (LNP) for the given line_header
20889    structure and CU.  The actual information extracted and the type
20890    of structures created from the LNP depends on the value of PST.
20891
20892    1. If PST is NULL, then this procedure uses the data from the program
20893       to create all necessary symbol tables, and their linetables.
20894
20895    2. If PST is not NULL, this procedure reads the program to determine
20896       the list of files included by the unit represented by PST, and
20897       builds all the associated partial symbol tables.
20898
20899    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20900    It is used for relative paths in the line table.
20901    NOTE: When processing partial symtabs (pst != NULL),
20902    comp_dir == pst->dirname.
20903
20904    NOTE: It is important that psymtabs have the same file name (via strcmp)
20905    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20906    symtab we don't use it in the name of the psymtabs we create.
20907    E.g. expand_line_sal requires this when finding psymtabs to expand.
20908    A good testcase for this is mb-inline.exp.
20909
20910    LOWPC is the lowest address in CU (or 0 if not known).
20911
20912    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20913    for its PC<->lines mapping information.  Otherwise only the filename
20914    table is read in.  */
20915
20916 static void
20917 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20918                     struct dwarf2_cu *cu, struct partial_symtab *pst,
20919                     CORE_ADDR lowpc, int decode_mapping)
20920 {
20921   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20922   const int decode_for_pst_p = (pst != NULL);
20923
20924   if (decode_mapping)
20925     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
20926
20927   if (decode_for_pst_p)
20928     {
20929       int file_index;
20930
20931       /* Now that we're done scanning the Line Header Program, we can
20932          create the psymtab of each included file.  */
20933       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
20934         if (lh->file_names[file_index].included_p == 1)
20935           {
20936             gdb::unique_xmalloc_ptr<char> name_holder;
20937             const char *include_name =
20938               psymtab_include_file_name (lh, file_index, pst, comp_dir,
20939                                          &name_holder);
20940             if (include_name != NULL)
20941               dwarf2_create_include_psymtab (include_name, pst, objfile);
20942           }
20943     }
20944   else
20945     {
20946       /* Make sure a symtab is created for every file, even files
20947          which contain only variables (i.e. no code with associated
20948          line numbers).  */
20949       struct compunit_symtab *cust = buildsym_compunit_symtab ();
20950       int i;
20951
20952       for (i = 0; i < lh->file_names.size (); i++)
20953         {
20954           file_entry &fe = lh->file_names[i];
20955
20956           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
20957
20958           if (current_subfile->symtab == NULL)
20959             {
20960               current_subfile->symtab
20961                 = allocate_symtab (cust, current_subfile->name);
20962             }
20963           fe.symtab = current_subfile->symtab;
20964         }
20965     }
20966 }
20967
20968 /* Start a subfile for DWARF.  FILENAME is the name of the file and
20969    DIRNAME the name of the source directory which contains FILENAME
20970    or NULL if not known.
20971    This routine tries to keep line numbers from identical absolute and
20972    relative file names in a common subfile.
20973
20974    Using the `list' example from the GDB testsuite, which resides in
20975    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
20976    of /srcdir/list0.c yields the following debugging information for list0.c:
20977
20978    DW_AT_name:          /srcdir/list0.c
20979    DW_AT_comp_dir:      /compdir
20980    files.files[0].name: list0.h
20981    files.files[0].dir:  /srcdir
20982    files.files[1].name: list0.c
20983    files.files[1].dir:  /srcdir
20984
20985    The line number information for list0.c has to end up in a single
20986    subfile, so that `break /srcdir/list0.c:1' works as expected.
20987    start_subfile will ensure that this happens provided that we pass the
20988    concatenation of files.files[1].dir and files.files[1].name as the
20989    subfile's name.  */
20990
20991 static void
20992 dwarf2_start_subfile (const char *filename, const char *dirname)
20993 {
20994   char *copy = NULL;
20995
20996   /* In order not to lose the line information directory,
20997      we concatenate it to the filename when it makes sense.
20998      Note that the Dwarf3 standard says (speaking of filenames in line
20999      information): ``The directory index is ignored for file names
21000      that represent full path names''.  Thus ignoring dirname in the
21001      `else' branch below isn't an issue.  */
21002
21003   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21004     {
21005       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21006       filename = copy;
21007     }
21008
21009   start_subfile (filename);
21010
21011   if (copy != NULL)
21012     xfree (copy);
21013 }
21014
21015 /* Start a symtab for DWARF.
21016    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21017
21018 static struct compunit_symtab *
21019 dwarf2_start_symtab (struct dwarf2_cu *cu,
21020                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21021 {
21022   struct compunit_symtab *cust
21023     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21024                     low_pc, cu->language);
21025
21026   record_debugformat ("DWARF 2");
21027   record_producer (cu->producer);
21028
21029   /* We assume that we're processing GCC output.  */
21030   processing_gcc_compilation = 2;
21031
21032   cu->processing_has_namespace_info = 0;
21033
21034   return cust;
21035 }
21036
21037 static void
21038 var_decode_location (struct attribute *attr, struct symbol *sym,
21039                      struct dwarf2_cu *cu)
21040 {
21041   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21042   struct comp_unit_head *cu_header = &cu->header;
21043
21044   /* NOTE drow/2003-01-30: There used to be a comment and some special
21045      code here to turn a symbol with DW_AT_external and a
21046      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21047      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21048      with some versions of binutils) where shared libraries could have
21049      relocations against symbols in their debug information - the
21050      minimal symbol would have the right address, but the debug info
21051      would not.  It's no longer necessary, because we will explicitly
21052      apply relocations when we read in the debug information now.  */
21053
21054   /* A DW_AT_location attribute with no contents indicates that a
21055      variable has been optimized away.  */
21056   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21057     {
21058       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21059       return;
21060     }
21061
21062   /* Handle one degenerate form of location expression specially, to
21063      preserve GDB's previous behavior when section offsets are
21064      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21065      then mark this symbol as LOC_STATIC.  */
21066
21067   if (attr_form_is_block (attr)
21068       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21069            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21070           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21071               && (DW_BLOCK (attr)->size
21072                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21073     {
21074       unsigned int dummy;
21075
21076       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21077         SYMBOL_VALUE_ADDRESS (sym) =
21078           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21079       else
21080         SYMBOL_VALUE_ADDRESS (sym) =
21081           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21082       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21083       fixup_symbol_section (sym, objfile);
21084       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21085                                               SYMBOL_SECTION (sym));
21086       return;
21087     }
21088
21089   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21090      expression evaluator, and use LOC_COMPUTED only when necessary
21091      (i.e. when the value of a register or memory location is
21092      referenced, or a thread-local block, etc.).  Then again, it might
21093      not be worthwhile.  I'm assuming that it isn't unless performance
21094      or memory numbers show me otherwise.  */
21095
21096   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21097
21098   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21099     cu->has_loclist = 1;
21100 }
21101
21102 /* Given a pointer to a DWARF information entry, figure out if we need
21103    to make a symbol table entry for it, and if so, create a new entry
21104    and return a pointer to it.
21105    If TYPE is NULL, determine symbol type from the die, otherwise
21106    used the passed type.
21107    If SPACE is not NULL, use it to hold the new symbol.  If it is
21108    NULL, allocate a new symbol on the objfile's obstack.  */
21109
21110 static struct symbol *
21111 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21112             struct symbol *space)
21113 {
21114   struct dwarf2_per_objfile *dwarf2_per_objfile
21115     = cu->per_cu->dwarf2_per_objfile;
21116   struct objfile *objfile = dwarf2_per_objfile->objfile;
21117   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21118   struct symbol *sym = NULL;
21119   const char *name;
21120   struct attribute *attr = NULL;
21121   struct attribute *attr2 = NULL;
21122   CORE_ADDR baseaddr;
21123   struct pending **list_to_add = NULL;
21124
21125   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21126
21127   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21128
21129   name = dwarf2_name (die, cu);
21130   if (name)
21131     {
21132       const char *linkagename;
21133       int suppress_add = 0;
21134
21135       if (space)
21136         sym = space;
21137       else
21138         sym = allocate_symbol (objfile);
21139       OBJSTAT (objfile, n_syms++);
21140
21141       /* Cache this symbol's name and the name's demangled form (if any).  */
21142       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21143       linkagename = dwarf2_physname (name, die, cu);
21144       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21145
21146       /* Fortran does not have mangling standard and the mangling does differ
21147          between gfortran, iFort etc.  */
21148       if (cu->language == language_fortran
21149           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21150         symbol_set_demangled_name (&(sym->ginfo),
21151                                    dwarf2_full_name (name, die, cu),
21152                                    NULL);
21153
21154       /* Default assumptions.
21155          Use the passed type or decode it from the die.  */
21156       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21157       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21158       if (type != NULL)
21159         SYMBOL_TYPE (sym) = type;
21160       else
21161         SYMBOL_TYPE (sym) = die_type (die, cu);
21162       attr = dwarf2_attr (die,
21163                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21164                           cu);
21165       if (attr)
21166         {
21167           SYMBOL_LINE (sym) = DW_UNSND (attr);
21168         }
21169
21170       attr = dwarf2_attr (die,
21171                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21172                           cu);
21173       if (attr)
21174         {
21175           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21176           struct file_entry *fe;
21177
21178           if (cu->line_header != NULL)
21179             fe = cu->line_header->file_name_at (file_index);
21180           else
21181             fe = NULL;
21182
21183           if (fe == NULL)
21184             complaint (_("file index out of range"));
21185           else
21186             symbol_set_symtab (sym, fe->symtab);
21187         }
21188
21189       switch (die->tag)
21190         {
21191         case DW_TAG_label:
21192           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21193           if (attr)
21194             {
21195               CORE_ADDR addr;
21196
21197               addr = attr_value_as_address (attr);
21198               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21199               SYMBOL_VALUE_ADDRESS (sym) = addr;
21200             }
21201           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21202           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21203           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21204           add_symbol_to_list (sym, cu->list_in_scope);
21205           break;
21206         case DW_TAG_subprogram:
21207           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21208              finish_block.  */
21209           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21210           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21211           if ((attr2 && (DW_UNSND (attr2) != 0))
21212               || cu->language == language_ada)
21213             {
21214               /* Subprograms marked external are stored as a global symbol.
21215                  Ada subprograms, whether marked external or not, are always
21216                  stored as a global symbol, because we want to be able to
21217                  access them globally.  For instance, we want to be able
21218                  to break on a nested subprogram without having to
21219                  specify the context.  */
21220               list_to_add = &global_symbols;
21221             }
21222           else
21223             {
21224               list_to_add = cu->list_in_scope;
21225             }
21226           break;
21227         case DW_TAG_inlined_subroutine:
21228           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21229              finish_block.  */
21230           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21231           SYMBOL_INLINED (sym) = 1;
21232           list_to_add = cu->list_in_scope;
21233           break;
21234         case DW_TAG_template_value_param:
21235           suppress_add = 1;
21236           /* Fall through.  */
21237         case DW_TAG_constant:
21238         case DW_TAG_variable:
21239         case DW_TAG_member:
21240           /* Compilation with minimal debug info may result in
21241              variables with missing type entries.  Change the
21242              misleading `void' type to something sensible.  */
21243           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21244             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21245
21246           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21247           /* In the case of DW_TAG_member, we should only be called for
21248              static const members.  */
21249           if (die->tag == DW_TAG_member)
21250             {
21251               /* dwarf2_add_field uses die_is_declaration,
21252                  so we do the same.  */
21253               gdb_assert (die_is_declaration (die, cu));
21254               gdb_assert (attr);
21255             }
21256           if (attr)
21257             {
21258               dwarf2_const_value (attr, sym, cu);
21259               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21260               if (!suppress_add)
21261                 {
21262                   if (attr2 && (DW_UNSND (attr2) != 0))
21263                     list_to_add = &global_symbols;
21264                   else
21265                     list_to_add = cu->list_in_scope;
21266                 }
21267               break;
21268             }
21269           attr = dwarf2_attr (die, DW_AT_location, cu);
21270           if (attr)
21271             {
21272               var_decode_location (attr, sym, cu);
21273               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21274
21275               /* Fortran explicitly imports any global symbols to the local
21276                  scope by DW_TAG_common_block.  */
21277               if (cu->language == language_fortran && die->parent
21278                   && die->parent->tag == DW_TAG_common_block)
21279                 attr2 = NULL;
21280
21281               if (SYMBOL_CLASS (sym) == LOC_STATIC
21282                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21283                   && !dwarf2_per_objfile->has_section_at_zero)
21284                 {
21285                   /* When a static variable is eliminated by the linker,
21286                      the corresponding debug information is not stripped
21287                      out, but the variable address is set to null;
21288                      do not add such variables into symbol table.  */
21289                 }
21290               else if (attr2 && (DW_UNSND (attr2) != 0))
21291                 {
21292                   /* Workaround gfortran PR debug/40040 - it uses
21293                      DW_AT_location for variables in -fPIC libraries which may
21294                      get overriden by other libraries/executable and get
21295                      a different address.  Resolve it by the minimal symbol
21296                      which may come from inferior's executable using copy
21297                      relocation.  Make this workaround only for gfortran as for
21298                      other compilers GDB cannot guess the minimal symbol
21299                      Fortran mangling kind.  */
21300                   if (cu->language == language_fortran && die->parent
21301                       && die->parent->tag == DW_TAG_module
21302                       && cu->producer
21303                       && startswith (cu->producer, "GNU Fortran"))
21304                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21305
21306                   /* A variable with DW_AT_external is never static,
21307                      but it may be block-scoped.  */
21308                   list_to_add = (cu->list_in_scope == &file_symbols
21309                                  ? &global_symbols : cu->list_in_scope);
21310                 }
21311               else
21312                 list_to_add = cu->list_in_scope;
21313             }
21314           else
21315             {
21316               /* We do not know the address of this symbol.
21317                  If it is an external symbol and we have type information
21318                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21319                  The address of the variable will then be determined from
21320                  the minimal symbol table whenever the variable is
21321                  referenced.  */
21322               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21323
21324               /* Fortran explicitly imports any global symbols to the local
21325                  scope by DW_TAG_common_block.  */
21326               if (cu->language == language_fortran && die->parent
21327                   && die->parent->tag == DW_TAG_common_block)
21328                 {
21329                   /* SYMBOL_CLASS doesn't matter here because
21330                      read_common_block is going to reset it.  */
21331                   if (!suppress_add)
21332                     list_to_add = cu->list_in_scope;
21333                 }
21334               else if (attr2 && (DW_UNSND (attr2) != 0)
21335                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21336                 {
21337                   /* A variable with DW_AT_external is never static, but it
21338                      may be block-scoped.  */
21339                   list_to_add = (cu->list_in_scope == &file_symbols
21340                                  ? &global_symbols : cu->list_in_scope);
21341
21342                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21343                 }
21344               else if (!die_is_declaration (die, cu))
21345                 {
21346                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21347                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21348                   if (!suppress_add)
21349                     list_to_add = cu->list_in_scope;
21350                 }
21351             }
21352           break;
21353         case DW_TAG_formal_parameter:
21354           /* If we are inside a function, mark this as an argument.  If
21355              not, we might be looking at an argument to an inlined function
21356              when we do not have enough information to show inlined frames;
21357              pretend it's a local variable in that case so that the user can
21358              still see it.  */
21359           if (context_stack_depth > 0
21360               && context_stack[context_stack_depth - 1].name != NULL)
21361             SYMBOL_IS_ARGUMENT (sym) = 1;
21362           attr = dwarf2_attr (die, DW_AT_location, cu);
21363           if (attr)
21364             {
21365               var_decode_location (attr, sym, cu);
21366             }
21367           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21368           if (attr)
21369             {
21370               dwarf2_const_value (attr, sym, cu);
21371             }
21372
21373           list_to_add = cu->list_in_scope;
21374           break;
21375         case DW_TAG_unspecified_parameters:
21376           /* From varargs functions; gdb doesn't seem to have any
21377              interest in this information, so just ignore it for now.
21378              (FIXME?) */
21379           break;
21380         case DW_TAG_template_type_param:
21381           suppress_add = 1;
21382           /* Fall through.  */
21383         case DW_TAG_class_type:
21384         case DW_TAG_interface_type:
21385         case DW_TAG_structure_type:
21386         case DW_TAG_union_type:
21387         case DW_TAG_set_type:
21388         case DW_TAG_enumeration_type:
21389           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21390           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21391
21392           {
21393             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21394                really ever be static objects: otherwise, if you try
21395                to, say, break of a class's method and you're in a file
21396                which doesn't mention that class, it won't work unless
21397                the check for all static symbols in lookup_symbol_aux
21398                saves you.  See the OtherFileClass tests in
21399                gdb.c++/namespace.exp.  */
21400
21401             if (!suppress_add)
21402               {
21403                 list_to_add = (cu->list_in_scope == &file_symbols
21404                                && cu->language == language_cplus
21405                                ? &global_symbols : cu->list_in_scope);
21406
21407                 /* The semantics of C++ state that "struct foo {
21408                    ... }" also defines a typedef for "foo".  */
21409                 if (cu->language == language_cplus
21410                     || cu->language == language_ada
21411                     || cu->language == language_d
21412                     || cu->language == language_rust)
21413                   {
21414                     /* The symbol's name is already allocated along
21415                        with this objfile, so we don't need to
21416                        duplicate it for the type.  */
21417                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21418                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21419                   }
21420               }
21421           }
21422           break;
21423         case DW_TAG_typedef:
21424           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21425           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21426           list_to_add = cu->list_in_scope;
21427           break;
21428         case DW_TAG_base_type:
21429         case DW_TAG_subrange_type:
21430           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21431           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21432           list_to_add = cu->list_in_scope;
21433           break;
21434         case DW_TAG_enumerator:
21435           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21436           if (attr)
21437             {
21438               dwarf2_const_value (attr, sym, cu);
21439             }
21440           {
21441             /* NOTE: carlton/2003-11-10: See comment above in the
21442                DW_TAG_class_type, etc. block.  */
21443
21444             list_to_add = (cu->list_in_scope == &file_symbols
21445                            && cu->language == language_cplus
21446                            ? &global_symbols : cu->list_in_scope);
21447           }
21448           break;
21449         case DW_TAG_imported_declaration:
21450         case DW_TAG_namespace:
21451           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21452           list_to_add = &global_symbols;
21453           break;
21454         case DW_TAG_module:
21455           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21456           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21457           list_to_add = &global_symbols;
21458           break;
21459         case DW_TAG_common_block:
21460           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21461           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21462           add_symbol_to_list (sym, cu->list_in_scope);
21463           break;
21464         default:
21465           /* Not a tag we recognize.  Hopefully we aren't processing
21466              trash data, but since we must specifically ignore things
21467              we don't recognize, there is nothing else we should do at
21468              this point.  */
21469           complaint (_("unsupported tag: '%s'"),
21470                      dwarf_tag_name (die->tag));
21471           break;
21472         }
21473
21474       if (suppress_add)
21475         {
21476           sym->hash_next = objfile->template_symbols;
21477           objfile->template_symbols = sym;
21478           list_to_add = NULL;
21479         }
21480
21481       if (list_to_add != NULL)
21482         add_symbol_to_list (sym, list_to_add);
21483
21484       /* For the benefit of old versions of GCC, check for anonymous
21485          namespaces based on the demangled name.  */
21486       if (!cu->processing_has_namespace_info
21487           && cu->language == language_cplus)
21488         cp_scan_for_anonymous_namespaces (sym, objfile);
21489     }
21490   return (sym);
21491 }
21492
21493 /* Given an attr with a DW_FORM_dataN value in host byte order,
21494    zero-extend it as appropriate for the symbol's type.  The DWARF
21495    standard (v4) is not entirely clear about the meaning of using
21496    DW_FORM_dataN for a constant with a signed type, where the type is
21497    wider than the data.  The conclusion of a discussion on the DWARF
21498    list was that this is unspecified.  We choose to always zero-extend
21499    because that is the interpretation long in use by GCC.  */
21500
21501 static gdb_byte *
21502 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21503                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21504 {
21505   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21506   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21507                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21508   LONGEST l = DW_UNSND (attr);
21509
21510   if (bits < sizeof (*value) * 8)
21511     {
21512       l &= ((LONGEST) 1 << bits) - 1;
21513       *value = l;
21514     }
21515   else if (bits == sizeof (*value) * 8)
21516     *value = l;
21517   else
21518     {
21519       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21520       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21521       return bytes;
21522     }
21523
21524   return NULL;
21525 }
21526
21527 /* Read a constant value from an attribute.  Either set *VALUE, or if
21528    the value does not fit in *VALUE, set *BYTES - either already
21529    allocated on the objfile obstack, or newly allocated on OBSTACK,
21530    or, set *BATON, if we translated the constant to a location
21531    expression.  */
21532
21533 static void
21534 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21535                          const char *name, struct obstack *obstack,
21536                          struct dwarf2_cu *cu,
21537                          LONGEST *value, const gdb_byte **bytes,
21538                          struct dwarf2_locexpr_baton **baton)
21539 {
21540   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21541   struct comp_unit_head *cu_header = &cu->header;
21542   struct dwarf_block *blk;
21543   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21544                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21545
21546   *value = 0;
21547   *bytes = NULL;
21548   *baton = NULL;
21549
21550   switch (attr->form)
21551     {
21552     case DW_FORM_addr:
21553     case DW_FORM_GNU_addr_index:
21554       {
21555         gdb_byte *data;
21556
21557         if (TYPE_LENGTH (type) != cu_header->addr_size)
21558           dwarf2_const_value_length_mismatch_complaint (name,
21559                                                         cu_header->addr_size,
21560                                                         TYPE_LENGTH (type));
21561         /* Symbols of this form are reasonably rare, so we just
21562            piggyback on the existing location code rather than writing
21563            a new implementation of symbol_computed_ops.  */
21564         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21565         (*baton)->per_cu = cu->per_cu;
21566         gdb_assert ((*baton)->per_cu);
21567
21568         (*baton)->size = 2 + cu_header->addr_size;
21569         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21570         (*baton)->data = data;
21571
21572         data[0] = DW_OP_addr;
21573         store_unsigned_integer (&data[1], cu_header->addr_size,
21574                                 byte_order, DW_ADDR (attr));
21575         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21576       }
21577       break;
21578     case DW_FORM_string:
21579     case DW_FORM_strp:
21580     case DW_FORM_GNU_str_index:
21581     case DW_FORM_GNU_strp_alt:
21582       /* DW_STRING is already allocated on the objfile obstack, point
21583          directly to it.  */
21584       *bytes = (const gdb_byte *) DW_STRING (attr);
21585       break;
21586     case DW_FORM_block1:
21587     case DW_FORM_block2:
21588     case DW_FORM_block4:
21589     case DW_FORM_block:
21590     case DW_FORM_exprloc:
21591     case DW_FORM_data16:
21592       blk = DW_BLOCK (attr);
21593       if (TYPE_LENGTH (type) != blk->size)
21594         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21595                                                       TYPE_LENGTH (type));
21596       *bytes = blk->data;
21597       break;
21598
21599       /* The DW_AT_const_value attributes are supposed to carry the
21600          symbol's value "represented as it would be on the target
21601          architecture."  By the time we get here, it's already been
21602          converted to host endianness, so we just need to sign- or
21603          zero-extend it as appropriate.  */
21604     case DW_FORM_data1:
21605       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21606       break;
21607     case DW_FORM_data2:
21608       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21609       break;
21610     case DW_FORM_data4:
21611       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21612       break;
21613     case DW_FORM_data8:
21614       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21615       break;
21616
21617     case DW_FORM_sdata:
21618     case DW_FORM_implicit_const:
21619       *value = DW_SND (attr);
21620       break;
21621
21622     case DW_FORM_udata:
21623       *value = DW_UNSND (attr);
21624       break;
21625
21626     default:
21627       complaint (_("unsupported const value attribute form: '%s'"),
21628                  dwarf_form_name (attr->form));
21629       *value = 0;
21630       break;
21631     }
21632 }
21633
21634
21635 /* Copy constant value from an attribute to a symbol.  */
21636
21637 static void
21638 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21639                     struct dwarf2_cu *cu)
21640 {
21641   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21642   LONGEST value;
21643   const gdb_byte *bytes;
21644   struct dwarf2_locexpr_baton *baton;
21645
21646   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21647                            SYMBOL_PRINT_NAME (sym),
21648                            &objfile->objfile_obstack, cu,
21649                            &value, &bytes, &baton);
21650
21651   if (baton != NULL)
21652     {
21653       SYMBOL_LOCATION_BATON (sym) = baton;
21654       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21655     }
21656   else if (bytes != NULL)
21657      {
21658       SYMBOL_VALUE_BYTES (sym) = bytes;
21659       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21660     }
21661   else
21662     {
21663       SYMBOL_VALUE (sym) = value;
21664       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21665     }
21666 }
21667
21668 /* Return the type of the die in question using its DW_AT_type attribute.  */
21669
21670 static struct type *
21671 die_type (struct die_info *die, struct dwarf2_cu *cu)
21672 {
21673   struct attribute *type_attr;
21674
21675   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21676   if (!type_attr)
21677     {
21678       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21679       /* A missing DW_AT_type represents a void type.  */
21680       return objfile_type (objfile)->builtin_void;
21681     }
21682
21683   return lookup_die_type (die, type_attr, cu);
21684 }
21685
21686 /* True iff CU's producer generates GNAT Ada auxiliary information
21687    that allows to find parallel types through that information instead
21688    of having to do expensive parallel lookups by type name.  */
21689
21690 static int
21691 need_gnat_info (struct dwarf2_cu *cu)
21692 {
21693   /* Assume that the Ada compiler was GNAT, which always produces
21694      the auxiliary information.  */
21695   return (cu->language == language_ada);
21696 }
21697
21698 /* Return the auxiliary type of the die in question using its
21699    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21700    attribute is not present.  */
21701
21702 static struct type *
21703 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21704 {
21705   struct attribute *type_attr;
21706
21707   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21708   if (!type_attr)
21709     return NULL;
21710
21711   return lookup_die_type (die, type_attr, cu);
21712 }
21713
21714 /* If DIE has a descriptive_type attribute, then set the TYPE's
21715    descriptive type accordingly.  */
21716
21717 static void
21718 set_descriptive_type (struct type *type, struct die_info *die,
21719                       struct dwarf2_cu *cu)
21720 {
21721   struct type *descriptive_type = die_descriptive_type (die, cu);
21722
21723   if (descriptive_type)
21724     {
21725       ALLOCATE_GNAT_AUX_TYPE (type);
21726       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21727     }
21728 }
21729
21730 /* Return the containing type of the die in question using its
21731    DW_AT_containing_type attribute.  */
21732
21733 static struct type *
21734 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21735 {
21736   struct attribute *type_attr;
21737   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21738
21739   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21740   if (!type_attr)
21741     error (_("Dwarf Error: Problem turning containing type into gdb type "
21742              "[in module %s]"), objfile_name (objfile));
21743
21744   return lookup_die_type (die, type_attr, cu);
21745 }
21746
21747 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21748
21749 static struct type *
21750 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21751 {
21752   struct dwarf2_per_objfile *dwarf2_per_objfile
21753     = cu->per_cu->dwarf2_per_objfile;
21754   struct objfile *objfile = dwarf2_per_objfile->objfile;
21755   char *message, *saved;
21756
21757   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
21758                         objfile_name (objfile),
21759                         sect_offset_str (cu->header.sect_off),
21760                         sect_offset_str (die->sect_off));
21761   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21762                                   message, strlen (message));
21763   xfree (message);
21764
21765   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21766 }
21767
21768 /* Look up the type of DIE in CU using its type attribute ATTR.
21769    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21770    DW_AT_containing_type.
21771    If there is no type substitute an error marker.  */
21772
21773 static struct type *
21774 lookup_die_type (struct die_info *die, const struct attribute *attr,
21775                  struct dwarf2_cu *cu)
21776 {
21777   struct dwarf2_per_objfile *dwarf2_per_objfile
21778     = cu->per_cu->dwarf2_per_objfile;
21779   struct objfile *objfile = dwarf2_per_objfile->objfile;
21780   struct type *this_type;
21781
21782   gdb_assert (attr->name == DW_AT_type
21783               || attr->name == DW_AT_GNAT_descriptive_type
21784               || attr->name == DW_AT_containing_type);
21785
21786   /* First see if we have it cached.  */
21787
21788   if (attr->form == DW_FORM_GNU_ref_alt)
21789     {
21790       struct dwarf2_per_cu_data *per_cu;
21791       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21792
21793       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21794                                                  dwarf2_per_objfile);
21795       this_type = get_die_type_at_offset (sect_off, per_cu);
21796     }
21797   else if (attr_form_is_ref (attr))
21798     {
21799       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21800
21801       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21802     }
21803   else if (attr->form == DW_FORM_ref_sig8)
21804     {
21805       ULONGEST signature = DW_SIGNATURE (attr);
21806
21807       return get_signatured_type (die, signature, cu);
21808     }
21809   else
21810     {
21811       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
21812                    " at %s [in module %s]"),
21813                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21814                  objfile_name (objfile));
21815       return build_error_marker_type (cu, die);
21816     }
21817
21818   /* If not cached we need to read it in.  */
21819
21820   if (this_type == NULL)
21821     {
21822       struct die_info *type_die = NULL;
21823       struct dwarf2_cu *type_cu = cu;
21824
21825       if (attr_form_is_ref (attr))
21826         type_die = follow_die_ref (die, attr, &type_cu);
21827       if (type_die == NULL)
21828         return build_error_marker_type (cu, die);
21829       /* If we find the type now, it's probably because the type came
21830          from an inter-CU reference and the type's CU got expanded before
21831          ours.  */
21832       this_type = read_type_die (type_die, type_cu);
21833     }
21834
21835   /* If we still don't have a type use an error marker.  */
21836
21837   if (this_type == NULL)
21838     return build_error_marker_type (cu, die);
21839
21840   return this_type;
21841 }
21842
21843 /* Return the type in DIE, CU.
21844    Returns NULL for invalid types.
21845
21846    This first does a lookup in die_type_hash,
21847    and only reads the die in if necessary.
21848
21849    NOTE: This can be called when reading in partial or full symbols.  */
21850
21851 static struct type *
21852 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21853 {
21854   struct type *this_type;
21855
21856   this_type = get_die_type (die, cu);
21857   if (this_type)
21858     return this_type;
21859
21860   return read_type_die_1 (die, cu);
21861 }
21862
21863 /* Read the type in DIE, CU.
21864    Returns NULL for invalid types.  */
21865
21866 static struct type *
21867 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21868 {
21869   struct type *this_type = NULL;
21870
21871   switch (die->tag)
21872     {
21873     case DW_TAG_class_type:
21874     case DW_TAG_interface_type:
21875     case DW_TAG_structure_type:
21876     case DW_TAG_union_type:
21877       this_type = read_structure_type (die, cu);
21878       break;
21879     case DW_TAG_enumeration_type:
21880       this_type = read_enumeration_type (die, cu);
21881       break;
21882     case DW_TAG_subprogram:
21883     case DW_TAG_subroutine_type:
21884     case DW_TAG_inlined_subroutine:
21885       this_type = read_subroutine_type (die, cu);
21886       break;
21887     case DW_TAG_array_type:
21888       this_type = read_array_type (die, cu);
21889       break;
21890     case DW_TAG_set_type:
21891       this_type = read_set_type (die, cu);
21892       break;
21893     case DW_TAG_pointer_type:
21894       this_type = read_tag_pointer_type (die, cu);
21895       break;
21896     case DW_TAG_ptr_to_member_type:
21897       this_type = read_tag_ptr_to_member_type (die, cu);
21898       break;
21899     case DW_TAG_reference_type:
21900       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21901       break;
21902     case DW_TAG_rvalue_reference_type:
21903       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21904       break;
21905     case DW_TAG_const_type:
21906       this_type = read_tag_const_type (die, cu);
21907       break;
21908     case DW_TAG_volatile_type:
21909       this_type = read_tag_volatile_type (die, cu);
21910       break;
21911     case DW_TAG_restrict_type:
21912       this_type = read_tag_restrict_type (die, cu);
21913       break;
21914     case DW_TAG_string_type:
21915       this_type = read_tag_string_type (die, cu);
21916       break;
21917     case DW_TAG_typedef:
21918       this_type = read_typedef (die, cu);
21919       break;
21920     case DW_TAG_subrange_type:
21921       this_type = read_subrange_type (die, cu);
21922       break;
21923     case DW_TAG_base_type:
21924       this_type = read_base_type (die, cu);
21925       break;
21926     case DW_TAG_unspecified_type:
21927       this_type = read_unspecified_type (die, cu);
21928       break;
21929     case DW_TAG_namespace:
21930       this_type = read_namespace_type (die, cu);
21931       break;
21932     case DW_TAG_module:
21933       this_type = read_module_type (die, cu);
21934       break;
21935     case DW_TAG_atomic_type:
21936       this_type = read_tag_atomic_type (die, cu);
21937       break;
21938     default:
21939       complaint (_("unexpected tag in read_type_die: '%s'"),
21940                  dwarf_tag_name (die->tag));
21941       break;
21942     }
21943
21944   return this_type;
21945 }
21946
21947 /* See if we can figure out if the class lives in a namespace.  We do
21948    this by looking for a member function; its demangled name will
21949    contain namespace info, if there is any.
21950    Return the computed name or NULL.
21951    Space for the result is allocated on the objfile's obstack.
21952    This is the full-die version of guess_partial_die_structure_name.
21953    In this case we know DIE has no useful parent.  */
21954
21955 static char *
21956 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
21957 {
21958   struct die_info *spec_die;
21959   struct dwarf2_cu *spec_cu;
21960   struct die_info *child;
21961   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21962
21963   spec_cu = cu;
21964   spec_die = die_specification (die, &spec_cu);
21965   if (spec_die != NULL)
21966     {
21967       die = spec_die;
21968       cu = spec_cu;
21969     }
21970
21971   for (child = die->child;
21972        child != NULL;
21973        child = child->sibling)
21974     {
21975       if (child->tag == DW_TAG_subprogram)
21976         {
21977           const char *linkage_name = dw2_linkage_name (child, cu);
21978
21979           if (linkage_name != NULL)
21980             {
21981               char *actual_name
21982                 = language_class_name_from_physname (cu->language_defn,
21983                                                      linkage_name);
21984               char *name = NULL;
21985
21986               if (actual_name != NULL)
21987                 {
21988                   const char *die_name = dwarf2_name (die, cu);
21989
21990                   if (die_name != NULL
21991                       && strcmp (die_name, actual_name) != 0)
21992                     {
21993                       /* Strip off the class name from the full name.
21994                          We want the prefix.  */
21995                       int die_name_len = strlen (die_name);
21996                       int actual_name_len = strlen (actual_name);
21997
21998                       /* Test for '::' as a sanity check.  */
21999                       if (actual_name_len > die_name_len + 2
22000                           && actual_name[actual_name_len
22001                                          - die_name_len - 1] == ':')
22002                         name = (char *) obstack_copy0 (
22003                           &objfile->per_bfd->storage_obstack,
22004                           actual_name, actual_name_len - die_name_len - 2);
22005                     }
22006                 }
22007               xfree (actual_name);
22008               return name;
22009             }
22010         }
22011     }
22012
22013   return NULL;
22014 }
22015
22016 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22017    prefix part in such case.  See
22018    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22019
22020 static const char *
22021 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22022 {
22023   struct attribute *attr;
22024   const char *base;
22025
22026   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22027       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22028     return NULL;
22029
22030   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22031     return NULL;
22032
22033   attr = dw2_linkage_name_attr (die, cu);
22034   if (attr == NULL || DW_STRING (attr) == NULL)
22035     return NULL;
22036
22037   /* dwarf2_name had to be already called.  */
22038   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22039
22040   /* Strip the base name, keep any leading namespaces/classes.  */
22041   base = strrchr (DW_STRING (attr), ':');
22042   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22043     return "";
22044
22045   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22046   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22047                                  DW_STRING (attr),
22048                                  &base[-1] - DW_STRING (attr));
22049 }
22050
22051 /* Return the name of the namespace/class that DIE is defined within,
22052    or "" if we can't tell.  The caller should not xfree the result.
22053
22054    For example, if we're within the method foo() in the following
22055    code:
22056
22057    namespace N {
22058      class C {
22059        void foo () {
22060        }
22061      };
22062    }
22063
22064    then determine_prefix on foo's die will return "N::C".  */
22065
22066 static const char *
22067 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22068 {
22069   struct dwarf2_per_objfile *dwarf2_per_objfile
22070     = cu->per_cu->dwarf2_per_objfile;
22071   struct die_info *parent, *spec_die;
22072   struct dwarf2_cu *spec_cu;
22073   struct type *parent_type;
22074   const char *retval;
22075
22076   if (cu->language != language_cplus
22077       && cu->language != language_fortran && cu->language != language_d
22078       && cu->language != language_rust)
22079     return "";
22080
22081   retval = anonymous_struct_prefix (die, cu);
22082   if (retval)
22083     return retval;
22084
22085   /* We have to be careful in the presence of DW_AT_specification.
22086      For example, with GCC 3.4, given the code
22087
22088      namespace N {
22089        void foo() {
22090          // Definition of N::foo.
22091        }
22092      }
22093
22094      then we'll have a tree of DIEs like this:
22095
22096      1: DW_TAG_compile_unit
22097        2: DW_TAG_namespace        // N
22098          3: DW_TAG_subprogram     // declaration of N::foo
22099        4: DW_TAG_subprogram       // definition of N::foo
22100             DW_AT_specification   // refers to die #3
22101
22102      Thus, when processing die #4, we have to pretend that we're in
22103      the context of its DW_AT_specification, namely the contex of die
22104      #3.  */
22105   spec_cu = cu;
22106   spec_die = die_specification (die, &spec_cu);
22107   if (spec_die == NULL)
22108     parent = die->parent;
22109   else
22110     {
22111       parent = spec_die->parent;
22112       cu = spec_cu;
22113     }
22114
22115   if (parent == NULL)
22116     return "";
22117   else if (parent->building_fullname)
22118     {
22119       const char *name;
22120       const char *parent_name;
22121
22122       /* It has been seen on RealView 2.2 built binaries,
22123          DW_TAG_template_type_param types actually _defined_ as
22124          children of the parent class:
22125
22126          enum E {};
22127          template class <class Enum> Class{};
22128          Class<enum E> class_e;
22129
22130          1: DW_TAG_class_type (Class)
22131            2: DW_TAG_enumeration_type (E)
22132              3: DW_TAG_enumerator (enum1:0)
22133              3: DW_TAG_enumerator (enum2:1)
22134              ...
22135            2: DW_TAG_template_type_param
22136               DW_AT_type  DW_FORM_ref_udata (E)
22137
22138          Besides being broken debug info, it can put GDB into an
22139          infinite loop.  Consider:
22140
22141          When we're building the full name for Class<E>, we'll start
22142          at Class, and go look over its template type parameters,
22143          finding E.  We'll then try to build the full name of E, and
22144          reach here.  We're now trying to build the full name of E,
22145          and look over the parent DIE for containing scope.  In the
22146          broken case, if we followed the parent DIE of E, we'd again
22147          find Class, and once again go look at its template type
22148          arguments, etc., etc.  Simply don't consider such parent die
22149          as source-level parent of this die (it can't be, the language
22150          doesn't allow it), and break the loop here.  */
22151       name = dwarf2_name (die, cu);
22152       parent_name = dwarf2_name (parent, cu);
22153       complaint (_("template param type '%s' defined within parent '%s'"),
22154                  name ? name : "<unknown>",
22155                  parent_name ? parent_name : "<unknown>");
22156       return "";
22157     }
22158   else
22159     switch (parent->tag)
22160       {
22161       case DW_TAG_namespace:
22162         parent_type = read_type_die (parent, cu);
22163         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22164            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22165            Work around this problem here.  */
22166         if (cu->language == language_cplus
22167             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22168           return "";
22169         /* We give a name to even anonymous namespaces.  */
22170         return TYPE_NAME (parent_type);
22171       case DW_TAG_class_type:
22172       case DW_TAG_interface_type:
22173       case DW_TAG_structure_type:
22174       case DW_TAG_union_type:
22175       case DW_TAG_module:
22176         parent_type = read_type_die (parent, cu);
22177         if (TYPE_NAME (parent_type) != NULL)
22178           return TYPE_NAME (parent_type);
22179         else
22180           /* An anonymous structure is only allowed non-static data
22181              members; no typedefs, no member functions, et cetera.
22182              So it does not need a prefix.  */
22183           return "";
22184       case DW_TAG_compile_unit:
22185       case DW_TAG_partial_unit:
22186         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22187         if (cu->language == language_cplus
22188             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22189             && die->child != NULL
22190             && (die->tag == DW_TAG_class_type
22191                 || die->tag == DW_TAG_structure_type
22192                 || die->tag == DW_TAG_union_type))
22193           {
22194             char *name = guess_full_die_structure_name (die, cu);
22195             if (name != NULL)
22196               return name;
22197           }
22198         return "";
22199       case DW_TAG_enumeration_type:
22200         parent_type = read_type_die (parent, cu);
22201         if (TYPE_DECLARED_CLASS (parent_type))
22202           {
22203             if (TYPE_NAME (parent_type) != NULL)
22204               return TYPE_NAME (parent_type);
22205             return "";
22206           }
22207         /* Fall through.  */
22208       default:
22209         return determine_prefix (parent, cu);
22210       }
22211 }
22212
22213 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22214    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22215    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22216    an obconcat, otherwise allocate storage for the result.  The CU argument is
22217    used to determine the language and hence, the appropriate separator.  */
22218
22219 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22220
22221 static char *
22222 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22223                  int physname, struct dwarf2_cu *cu)
22224 {
22225   const char *lead = "";
22226   const char *sep;
22227
22228   if (suffix == NULL || suffix[0] == '\0'
22229       || prefix == NULL || prefix[0] == '\0')
22230     sep = "";
22231   else if (cu->language == language_d)
22232     {
22233       /* For D, the 'main' function could be defined in any module, but it
22234          should never be prefixed.  */
22235       if (strcmp (suffix, "D main") == 0)
22236         {
22237           prefix = "";
22238           sep = "";
22239         }
22240       else
22241         sep = ".";
22242     }
22243   else if (cu->language == language_fortran && physname)
22244     {
22245       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22246          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22247
22248       lead = "__";
22249       sep = "_MOD_";
22250     }
22251   else
22252     sep = "::";
22253
22254   if (prefix == NULL)
22255     prefix = "";
22256   if (suffix == NULL)
22257     suffix = "";
22258
22259   if (obs == NULL)
22260     {
22261       char *retval
22262         = ((char *)
22263            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22264
22265       strcpy (retval, lead);
22266       strcat (retval, prefix);
22267       strcat (retval, sep);
22268       strcat (retval, suffix);
22269       return retval;
22270     }
22271   else
22272     {
22273       /* We have an obstack.  */
22274       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22275     }
22276 }
22277
22278 /* Return sibling of die, NULL if no sibling.  */
22279
22280 static struct die_info *
22281 sibling_die (struct die_info *die)
22282 {
22283   return die->sibling;
22284 }
22285
22286 /* Get name of a die, return NULL if not found.  */
22287
22288 static const char *
22289 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22290                           struct obstack *obstack)
22291 {
22292   if (name && cu->language == language_cplus)
22293     {
22294       std::string canon_name = cp_canonicalize_string (name);
22295
22296       if (!canon_name.empty ())
22297         {
22298           if (canon_name != name)
22299             name = (const char *) obstack_copy0 (obstack,
22300                                                  canon_name.c_str (),
22301                                                  canon_name.length ());
22302         }
22303     }
22304
22305   return name;
22306 }
22307
22308 /* Get name of a die, return NULL if not found.
22309    Anonymous namespaces are converted to their magic string.  */
22310
22311 static const char *
22312 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22313 {
22314   struct attribute *attr;
22315   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22316
22317   attr = dwarf2_attr (die, DW_AT_name, cu);
22318   if ((!attr || !DW_STRING (attr))
22319       && die->tag != DW_TAG_namespace
22320       && die->tag != DW_TAG_class_type
22321       && die->tag != DW_TAG_interface_type
22322       && die->tag != DW_TAG_structure_type
22323       && die->tag != DW_TAG_union_type)
22324     return NULL;
22325
22326   switch (die->tag)
22327     {
22328     case DW_TAG_compile_unit:
22329     case DW_TAG_partial_unit:
22330       /* Compilation units have a DW_AT_name that is a filename, not
22331          a source language identifier.  */
22332     case DW_TAG_enumeration_type:
22333     case DW_TAG_enumerator:
22334       /* These tags always have simple identifiers already; no need
22335          to canonicalize them.  */
22336       return DW_STRING (attr);
22337
22338     case DW_TAG_namespace:
22339       if (attr != NULL && DW_STRING (attr) != NULL)
22340         return DW_STRING (attr);
22341       return CP_ANONYMOUS_NAMESPACE_STR;
22342
22343     case DW_TAG_class_type:
22344     case DW_TAG_interface_type:
22345     case DW_TAG_structure_type:
22346     case DW_TAG_union_type:
22347       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22348          structures or unions.  These were of the form "._%d" in GCC 4.1,
22349          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22350          and GCC 4.4.  We work around this problem by ignoring these.  */
22351       if (attr && DW_STRING (attr)
22352           && (startswith (DW_STRING (attr), "._")
22353               || startswith (DW_STRING (attr), "<anonymous")))
22354         return NULL;
22355
22356       /* GCC might emit a nameless typedef that has a linkage name.  See
22357          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22358       if (!attr || DW_STRING (attr) == NULL)
22359         {
22360           char *demangled = NULL;
22361
22362           attr = dw2_linkage_name_attr (die, cu);
22363           if (attr == NULL || DW_STRING (attr) == NULL)
22364             return NULL;
22365
22366           /* Avoid demangling DW_STRING (attr) the second time on a second
22367              call for the same DIE.  */
22368           if (!DW_STRING_IS_CANONICAL (attr))
22369             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22370
22371           if (demangled)
22372             {
22373               const char *base;
22374
22375               /* FIXME: we already did this for the partial symbol... */
22376               DW_STRING (attr)
22377                 = ((const char *)
22378                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22379                                   demangled, strlen (demangled)));
22380               DW_STRING_IS_CANONICAL (attr) = 1;
22381               xfree (demangled);
22382
22383               /* Strip any leading namespaces/classes, keep only the base name.
22384                  DW_AT_name for named DIEs does not contain the prefixes.  */
22385               base = strrchr (DW_STRING (attr), ':');
22386               if (base && base > DW_STRING (attr) && base[-1] == ':')
22387                 return &base[1];
22388               else
22389                 return DW_STRING (attr);
22390             }
22391         }
22392       break;
22393
22394     default:
22395       break;
22396     }
22397
22398   if (!DW_STRING_IS_CANONICAL (attr))
22399     {
22400       DW_STRING (attr)
22401         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22402                                     &objfile->per_bfd->storage_obstack);
22403       DW_STRING_IS_CANONICAL (attr) = 1;
22404     }
22405   return DW_STRING (attr);
22406 }
22407
22408 /* Return the die that this die in an extension of, or NULL if there
22409    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22410    containing the return value on output.  */
22411
22412 static struct die_info *
22413 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22414 {
22415   struct attribute *attr;
22416
22417   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22418   if (attr == NULL)
22419     return NULL;
22420
22421   return follow_die_ref (die, attr, ext_cu);
22422 }
22423
22424 /* Convert a DIE tag into its string name.  */
22425
22426 static const char *
22427 dwarf_tag_name (unsigned tag)
22428 {
22429   const char *name = get_DW_TAG_name (tag);
22430
22431   if (name == NULL)
22432     return "DW_TAG_<unknown>";
22433
22434   return name;
22435 }
22436
22437 /* Convert a DWARF attribute code into its string name.  */
22438
22439 static const char *
22440 dwarf_attr_name (unsigned attr)
22441 {
22442   const char *name;
22443
22444 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22445   if (attr == DW_AT_MIPS_fde)
22446     return "DW_AT_MIPS_fde";
22447 #else
22448   if (attr == DW_AT_HP_block_index)
22449     return "DW_AT_HP_block_index";
22450 #endif
22451
22452   name = get_DW_AT_name (attr);
22453
22454   if (name == NULL)
22455     return "DW_AT_<unknown>";
22456
22457   return name;
22458 }
22459
22460 /* Convert a DWARF value form code into its string name.  */
22461
22462 static const char *
22463 dwarf_form_name (unsigned form)
22464 {
22465   const char *name = get_DW_FORM_name (form);
22466
22467   if (name == NULL)
22468     return "DW_FORM_<unknown>";
22469
22470   return name;
22471 }
22472
22473 static const char *
22474 dwarf_bool_name (unsigned mybool)
22475 {
22476   if (mybool)
22477     return "TRUE";
22478   else
22479     return "FALSE";
22480 }
22481
22482 /* Convert a DWARF type code into its string name.  */
22483
22484 static const char *
22485 dwarf_type_encoding_name (unsigned enc)
22486 {
22487   const char *name = get_DW_ATE_name (enc);
22488
22489   if (name == NULL)
22490     return "DW_ATE_<unknown>";
22491
22492   return name;
22493 }
22494
22495 static void
22496 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22497 {
22498   unsigned int i;
22499
22500   print_spaces (indent, f);
22501   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22502                       dwarf_tag_name (die->tag), die->abbrev,
22503                       sect_offset_str (die->sect_off));
22504
22505   if (die->parent != NULL)
22506     {
22507       print_spaces (indent, f);
22508       fprintf_unfiltered (f, "  parent at offset: %s\n",
22509                           sect_offset_str (die->parent->sect_off));
22510     }
22511
22512   print_spaces (indent, f);
22513   fprintf_unfiltered (f, "  has children: %s\n",
22514            dwarf_bool_name (die->child != NULL));
22515
22516   print_spaces (indent, f);
22517   fprintf_unfiltered (f, "  attributes:\n");
22518
22519   for (i = 0; i < die->num_attrs; ++i)
22520     {
22521       print_spaces (indent, f);
22522       fprintf_unfiltered (f, "    %s (%s) ",
22523                dwarf_attr_name (die->attrs[i].name),
22524                dwarf_form_name (die->attrs[i].form));
22525
22526       switch (die->attrs[i].form)
22527         {
22528         case DW_FORM_addr:
22529         case DW_FORM_GNU_addr_index:
22530           fprintf_unfiltered (f, "address: ");
22531           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22532           break;
22533         case DW_FORM_block2:
22534         case DW_FORM_block4:
22535         case DW_FORM_block:
22536         case DW_FORM_block1:
22537           fprintf_unfiltered (f, "block: size %s",
22538                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22539           break;
22540         case DW_FORM_exprloc:
22541           fprintf_unfiltered (f, "expression: size %s",
22542                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22543           break;
22544         case DW_FORM_data16:
22545           fprintf_unfiltered (f, "constant of 16 bytes");
22546           break;
22547         case DW_FORM_ref_addr:
22548           fprintf_unfiltered (f, "ref address: ");
22549           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22550           break;
22551         case DW_FORM_GNU_ref_alt:
22552           fprintf_unfiltered (f, "alt ref address: ");
22553           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22554           break;
22555         case DW_FORM_ref1:
22556         case DW_FORM_ref2:
22557         case DW_FORM_ref4:
22558         case DW_FORM_ref8:
22559         case DW_FORM_ref_udata:
22560           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22561                               (long) (DW_UNSND (&die->attrs[i])));
22562           break;
22563         case DW_FORM_data1:
22564         case DW_FORM_data2:
22565         case DW_FORM_data4:
22566         case DW_FORM_data8:
22567         case DW_FORM_udata:
22568         case DW_FORM_sdata:
22569           fprintf_unfiltered (f, "constant: %s",
22570                               pulongest (DW_UNSND (&die->attrs[i])));
22571           break;
22572         case DW_FORM_sec_offset:
22573           fprintf_unfiltered (f, "section offset: %s",
22574                               pulongest (DW_UNSND (&die->attrs[i])));
22575           break;
22576         case DW_FORM_ref_sig8:
22577           fprintf_unfiltered (f, "signature: %s",
22578                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22579           break;
22580         case DW_FORM_string:
22581         case DW_FORM_strp:
22582         case DW_FORM_line_strp:
22583         case DW_FORM_GNU_str_index:
22584         case DW_FORM_GNU_strp_alt:
22585           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22586                    DW_STRING (&die->attrs[i])
22587                    ? DW_STRING (&die->attrs[i]) : "",
22588                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22589           break;
22590         case DW_FORM_flag:
22591           if (DW_UNSND (&die->attrs[i]))
22592             fprintf_unfiltered (f, "flag: TRUE");
22593           else
22594             fprintf_unfiltered (f, "flag: FALSE");
22595           break;
22596         case DW_FORM_flag_present:
22597           fprintf_unfiltered (f, "flag: TRUE");
22598           break;
22599         case DW_FORM_indirect:
22600           /* The reader will have reduced the indirect form to
22601              the "base form" so this form should not occur.  */
22602           fprintf_unfiltered (f, 
22603                               "unexpected attribute form: DW_FORM_indirect");
22604           break;
22605         case DW_FORM_implicit_const:
22606           fprintf_unfiltered (f, "constant: %s",
22607                               plongest (DW_SND (&die->attrs[i])));
22608           break;
22609         default:
22610           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22611                    die->attrs[i].form);
22612           break;
22613         }
22614       fprintf_unfiltered (f, "\n");
22615     }
22616 }
22617
22618 static void
22619 dump_die_for_error (struct die_info *die)
22620 {
22621   dump_die_shallow (gdb_stderr, 0, die);
22622 }
22623
22624 static void
22625 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22626 {
22627   int indent = level * 4;
22628
22629   gdb_assert (die != NULL);
22630
22631   if (level >= max_level)
22632     return;
22633
22634   dump_die_shallow (f, indent, die);
22635
22636   if (die->child != NULL)
22637     {
22638       print_spaces (indent, f);
22639       fprintf_unfiltered (f, "  Children:");
22640       if (level + 1 < max_level)
22641         {
22642           fprintf_unfiltered (f, "\n");
22643           dump_die_1 (f, level + 1, max_level, die->child);
22644         }
22645       else
22646         {
22647           fprintf_unfiltered (f,
22648                               " [not printed, max nesting level reached]\n");
22649         }
22650     }
22651
22652   if (die->sibling != NULL && level > 0)
22653     {
22654       dump_die_1 (f, level, max_level, die->sibling);
22655     }
22656 }
22657
22658 /* This is called from the pdie macro in gdbinit.in.
22659    It's not static so gcc will keep a copy callable from gdb.  */
22660
22661 void
22662 dump_die (struct die_info *die, int max_level)
22663 {
22664   dump_die_1 (gdb_stdlog, 0, max_level, die);
22665 }
22666
22667 static void
22668 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22669 {
22670   void **slot;
22671
22672   slot = htab_find_slot_with_hash (cu->die_hash, die,
22673                                    to_underlying (die->sect_off),
22674                                    INSERT);
22675
22676   *slot = die;
22677 }
22678
22679 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22680    required kind.  */
22681
22682 static sect_offset
22683 dwarf2_get_ref_die_offset (const struct attribute *attr)
22684 {
22685   if (attr_form_is_ref (attr))
22686     return (sect_offset) DW_UNSND (attr);
22687
22688   complaint (_("unsupported die ref attribute form: '%s'"),
22689              dwarf_form_name (attr->form));
22690   return {};
22691 }
22692
22693 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22694  * the value held by the attribute is not constant.  */
22695
22696 static LONGEST
22697 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22698 {
22699   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22700     return DW_SND (attr);
22701   else if (attr->form == DW_FORM_udata
22702            || attr->form == DW_FORM_data1
22703            || attr->form == DW_FORM_data2
22704            || attr->form == DW_FORM_data4
22705            || attr->form == DW_FORM_data8)
22706     return DW_UNSND (attr);
22707   else
22708     {
22709       /* For DW_FORM_data16 see attr_form_is_constant.  */
22710       complaint (_("Attribute value is not a constant (%s)"),
22711                  dwarf_form_name (attr->form));
22712       return default_value;
22713     }
22714 }
22715
22716 /* Follow reference or signature attribute ATTR of SRC_DIE.
22717    On entry *REF_CU is the CU of SRC_DIE.
22718    On exit *REF_CU is the CU of the result.  */
22719
22720 static struct die_info *
22721 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22722                        struct dwarf2_cu **ref_cu)
22723 {
22724   struct die_info *die;
22725
22726   if (attr_form_is_ref (attr))
22727     die = follow_die_ref (src_die, attr, ref_cu);
22728   else if (attr->form == DW_FORM_ref_sig8)
22729     die = follow_die_sig (src_die, attr, ref_cu);
22730   else
22731     {
22732       dump_die_for_error (src_die);
22733       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22734              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22735     }
22736
22737   return die;
22738 }
22739
22740 /* Follow reference OFFSET.
22741    On entry *REF_CU is the CU of the source die referencing OFFSET.
22742    On exit *REF_CU is the CU of the result.
22743    Returns NULL if OFFSET is invalid.  */
22744
22745 static struct die_info *
22746 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22747                    struct dwarf2_cu **ref_cu)
22748 {
22749   struct die_info temp_die;
22750   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22751   struct dwarf2_per_objfile *dwarf2_per_objfile
22752     = cu->per_cu->dwarf2_per_objfile;
22753
22754   gdb_assert (cu->per_cu != NULL);
22755
22756   target_cu = cu;
22757
22758   if (cu->per_cu->is_debug_types)
22759     {
22760       /* .debug_types CUs cannot reference anything outside their CU.
22761          If they need to, they have to reference a signatured type via
22762          DW_FORM_ref_sig8.  */
22763       if (!offset_in_cu_p (&cu->header, sect_off))
22764         return NULL;
22765     }
22766   else if (offset_in_dwz != cu->per_cu->is_dwz
22767            || !offset_in_cu_p (&cu->header, sect_off))
22768     {
22769       struct dwarf2_per_cu_data *per_cu;
22770
22771       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22772                                                  dwarf2_per_objfile);
22773
22774       /* If necessary, add it to the queue and load its DIEs.  */
22775       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22776         load_full_comp_unit (per_cu, false, cu->language);
22777
22778       target_cu = per_cu->cu;
22779     }
22780   else if (cu->dies == NULL)
22781     {
22782       /* We're loading full DIEs during partial symbol reading.  */
22783       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22784       load_full_comp_unit (cu->per_cu, false, language_minimal);
22785     }
22786
22787   *ref_cu = target_cu;
22788   temp_die.sect_off = sect_off;
22789   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22790                                                   &temp_die,
22791                                                   to_underlying (sect_off));
22792 }
22793
22794 /* Follow reference attribute ATTR of SRC_DIE.
22795    On entry *REF_CU is the CU of SRC_DIE.
22796    On exit *REF_CU is the CU of the result.  */
22797
22798 static struct die_info *
22799 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22800                 struct dwarf2_cu **ref_cu)
22801 {
22802   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22803   struct dwarf2_cu *cu = *ref_cu;
22804   struct die_info *die;
22805
22806   die = follow_die_offset (sect_off,
22807                            (attr->form == DW_FORM_GNU_ref_alt
22808                             || cu->per_cu->is_dwz),
22809                            ref_cu);
22810   if (!die)
22811     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22812            "at %s [in module %s]"),
22813            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22814            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22815
22816   return die;
22817 }
22818
22819 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22820    Returned value is intended for DW_OP_call*.  Returned
22821    dwarf2_locexpr_baton->data has lifetime of
22822    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22823
22824 struct dwarf2_locexpr_baton
22825 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22826                                struct dwarf2_per_cu_data *per_cu,
22827                                CORE_ADDR (*get_frame_pc) (void *baton),
22828                                void *baton)
22829 {
22830   struct dwarf2_cu *cu;
22831   struct die_info *die;
22832   struct attribute *attr;
22833   struct dwarf2_locexpr_baton retval;
22834   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22835   struct objfile *objfile = dwarf2_per_objfile->objfile;
22836
22837   if (per_cu->cu == NULL)
22838     load_cu (per_cu, false);
22839   cu = per_cu->cu;
22840   if (cu == NULL)
22841     {
22842       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22843          Instead just throw an error, not much else we can do.  */
22844       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22845              sect_offset_str (sect_off), objfile_name (objfile));
22846     }
22847
22848   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22849   if (!die)
22850     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22851            sect_offset_str (sect_off), objfile_name (objfile));
22852
22853   attr = dwarf2_attr (die, DW_AT_location, cu);
22854   if (!attr)
22855     {
22856       /* DWARF: "If there is no such attribute, then there is no effect.".
22857          DATA is ignored if SIZE is 0.  */
22858
22859       retval.data = NULL;
22860       retval.size = 0;
22861     }
22862   else if (attr_form_is_section_offset (attr))
22863     {
22864       struct dwarf2_loclist_baton loclist_baton;
22865       CORE_ADDR pc = (*get_frame_pc) (baton);
22866       size_t size;
22867
22868       fill_in_loclist_baton (cu, &loclist_baton, attr);
22869
22870       retval.data = dwarf2_find_location_expression (&loclist_baton,
22871                                                      &size, pc);
22872       retval.size = size;
22873     }
22874   else
22875     {
22876       if (!attr_form_is_block (attr))
22877         error (_("Dwarf Error: DIE at %s referenced in module %s "
22878                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22879                sect_offset_str (sect_off), objfile_name (objfile));
22880
22881       retval.data = DW_BLOCK (attr)->data;
22882       retval.size = DW_BLOCK (attr)->size;
22883     }
22884   retval.per_cu = cu->per_cu;
22885
22886   age_cached_comp_units (dwarf2_per_objfile);
22887
22888   return retval;
22889 }
22890
22891 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
22892    offset.  */
22893
22894 struct dwarf2_locexpr_baton
22895 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
22896                              struct dwarf2_per_cu_data *per_cu,
22897                              CORE_ADDR (*get_frame_pc) (void *baton),
22898                              void *baton)
22899 {
22900   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
22901
22902   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
22903 }
22904
22905 /* Write a constant of a given type as target-ordered bytes into
22906    OBSTACK.  */
22907
22908 static const gdb_byte *
22909 write_constant_as_bytes (struct obstack *obstack,
22910                          enum bfd_endian byte_order,
22911                          struct type *type,
22912                          ULONGEST value,
22913                          LONGEST *len)
22914 {
22915   gdb_byte *result;
22916
22917   *len = TYPE_LENGTH (type);
22918   result = (gdb_byte *) obstack_alloc (obstack, *len);
22919   store_unsigned_integer (result, *len, byte_order, value);
22920
22921   return result;
22922 }
22923
22924 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
22925    pointer to the constant bytes and set LEN to the length of the
22926    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
22927    does not have a DW_AT_const_value, return NULL.  */
22928
22929 const gdb_byte *
22930 dwarf2_fetch_constant_bytes (sect_offset sect_off,
22931                              struct dwarf2_per_cu_data *per_cu,
22932                              struct obstack *obstack,
22933                              LONGEST *len)
22934 {
22935   struct dwarf2_cu *cu;
22936   struct die_info *die;
22937   struct attribute *attr;
22938   const gdb_byte *result = NULL;
22939   struct type *type;
22940   LONGEST value;
22941   enum bfd_endian byte_order;
22942   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
22943
22944   if (per_cu->cu == NULL)
22945     load_cu (per_cu, false);
22946   cu = per_cu->cu;
22947   if (cu == NULL)
22948     {
22949       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22950          Instead just throw an error, not much else we can do.  */
22951       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22952              sect_offset_str (sect_off), objfile_name (objfile));
22953     }
22954
22955   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22956   if (!die)
22957     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22958            sect_offset_str (sect_off), objfile_name (objfile));
22959
22960   attr = dwarf2_attr (die, DW_AT_const_value, cu);
22961   if (attr == NULL)
22962     return NULL;
22963
22964   byte_order = (bfd_big_endian (objfile->obfd)
22965                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
22966
22967   switch (attr->form)
22968     {
22969     case DW_FORM_addr:
22970     case DW_FORM_GNU_addr_index:
22971       {
22972         gdb_byte *tem;
22973
22974         *len = cu->header.addr_size;
22975         tem = (gdb_byte *) obstack_alloc (obstack, *len);
22976         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
22977         result = tem;
22978       }
22979       break;
22980     case DW_FORM_string:
22981     case DW_FORM_strp:
22982     case DW_FORM_GNU_str_index:
22983     case DW_FORM_GNU_strp_alt:
22984       /* DW_STRING is already allocated on the objfile obstack, point
22985          directly to it.  */
22986       result = (const gdb_byte *) DW_STRING (attr);
22987       *len = strlen (DW_STRING (attr));
22988       break;
22989     case DW_FORM_block1:
22990     case DW_FORM_block2:
22991     case DW_FORM_block4:
22992     case DW_FORM_block:
22993     case DW_FORM_exprloc:
22994     case DW_FORM_data16:
22995       result = DW_BLOCK (attr)->data;
22996       *len = DW_BLOCK (attr)->size;
22997       break;
22998
22999       /* The DW_AT_const_value attributes are supposed to carry the
23000          symbol's value "represented as it would be on the target
23001          architecture."  By the time we get here, it's already been
23002          converted to host endianness, so we just need to sign- or
23003          zero-extend it as appropriate.  */
23004     case DW_FORM_data1:
23005       type = die_type (die, cu);
23006       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23007       if (result == NULL)
23008         result = write_constant_as_bytes (obstack, byte_order,
23009                                           type, value, len);
23010       break;
23011     case DW_FORM_data2:
23012       type = die_type (die, cu);
23013       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23014       if (result == NULL)
23015         result = write_constant_as_bytes (obstack, byte_order,
23016                                           type, value, len);
23017       break;
23018     case DW_FORM_data4:
23019       type = die_type (die, cu);
23020       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23021       if (result == NULL)
23022         result = write_constant_as_bytes (obstack, byte_order,
23023                                           type, value, len);
23024       break;
23025     case DW_FORM_data8:
23026       type = die_type (die, cu);
23027       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23028       if (result == NULL)
23029         result = write_constant_as_bytes (obstack, byte_order,
23030                                           type, value, len);
23031       break;
23032
23033     case DW_FORM_sdata:
23034     case DW_FORM_implicit_const:
23035       type = die_type (die, cu);
23036       result = write_constant_as_bytes (obstack, byte_order,
23037                                         type, DW_SND (attr), len);
23038       break;
23039
23040     case DW_FORM_udata:
23041       type = die_type (die, cu);
23042       result = write_constant_as_bytes (obstack, byte_order,
23043                                         type, DW_UNSND (attr), len);
23044       break;
23045
23046     default:
23047       complaint (_("unsupported const value attribute form: '%s'"),
23048                  dwarf_form_name (attr->form));
23049       break;
23050     }
23051
23052   return result;
23053 }
23054
23055 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23056    valid type for this die is found.  */
23057
23058 struct type *
23059 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23060                                 struct dwarf2_per_cu_data *per_cu)
23061 {
23062   struct dwarf2_cu *cu;
23063   struct die_info *die;
23064
23065   if (per_cu->cu == NULL)
23066     load_cu (per_cu, false);
23067   cu = per_cu->cu;
23068   if (!cu)
23069     return NULL;
23070
23071   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23072   if (!die)
23073     return NULL;
23074
23075   return die_type (die, cu);
23076 }
23077
23078 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23079    PER_CU.  */
23080
23081 struct type *
23082 dwarf2_get_die_type (cu_offset die_offset,
23083                      struct dwarf2_per_cu_data *per_cu)
23084 {
23085   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23086   return get_die_type_at_offset (die_offset_sect, per_cu);
23087 }
23088
23089 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23090    On entry *REF_CU is the CU of SRC_DIE.
23091    On exit *REF_CU is the CU of the result.
23092    Returns NULL if the referenced DIE isn't found.  */
23093
23094 static struct die_info *
23095 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23096                   struct dwarf2_cu **ref_cu)
23097 {
23098   struct die_info temp_die;
23099   struct dwarf2_cu *sig_cu;
23100   struct die_info *die;
23101
23102   /* While it might be nice to assert sig_type->type == NULL here,
23103      we can get here for DW_AT_imported_declaration where we need
23104      the DIE not the type.  */
23105
23106   /* If necessary, add it to the queue and load its DIEs.  */
23107
23108   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23109     read_signatured_type (sig_type);
23110
23111   sig_cu = sig_type->per_cu.cu;
23112   gdb_assert (sig_cu != NULL);
23113   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23114   temp_die.sect_off = sig_type->type_offset_in_section;
23115   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23116                                                  to_underlying (temp_die.sect_off));
23117   if (die)
23118     {
23119       struct dwarf2_per_objfile *dwarf2_per_objfile
23120         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23121
23122       /* For .gdb_index version 7 keep track of included TUs.
23123          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23124       if (dwarf2_per_objfile->index_table != NULL
23125           && dwarf2_per_objfile->index_table->version <= 7)
23126         {
23127           VEC_safe_push (dwarf2_per_cu_ptr,
23128                          (*ref_cu)->per_cu->imported_symtabs,
23129                          sig_cu->per_cu);
23130         }
23131
23132       *ref_cu = sig_cu;
23133       return die;
23134     }
23135
23136   return NULL;
23137 }
23138
23139 /* Follow signatured type referenced by ATTR in SRC_DIE.
23140    On entry *REF_CU is the CU of SRC_DIE.
23141    On exit *REF_CU is the CU of the result.
23142    The result is the DIE of the type.
23143    If the referenced type cannot be found an error is thrown.  */
23144
23145 static struct die_info *
23146 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23147                 struct dwarf2_cu **ref_cu)
23148 {
23149   ULONGEST signature = DW_SIGNATURE (attr);
23150   struct signatured_type *sig_type;
23151   struct die_info *die;
23152
23153   gdb_assert (attr->form == DW_FORM_ref_sig8);
23154
23155   sig_type = lookup_signatured_type (*ref_cu, signature);
23156   /* sig_type will be NULL if the signatured type is missing from
23157      the debug info.  */
23158   if (sig_type == NULL)
23159     {
23160       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23161                " from DIE at %s [in module %s]"),
23162              hex_string (signature), sect_offset_str (src_die->sect_off),
23163              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23164     }
23165
23166   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23167   if (die == NULL)
23168     {
23169       dump_die_for_error (src_die);
23170       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23171                " from DIE at %s [in module %s]"),
23172              hex_string (signature), sect_offset_str (src_die->sect_off),
23173              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23174     }
23175
23176   return die;
23177 }
23178
23179 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23180    reading in and processing the type unit if necessary.  */
23181
23182 static struct type *
23183 get_signatured_type (struct die_info *die, ULONGEST signature,
23184                      struct dwarf2_cu *cu)
23185 {
23186   struct dwarf2_per_objfile *dwarf2_per_objfile
23187     = cu->per_cu->dwarf2_per_objfile;
23188   struct signatured_type *sig_type;
23189   struct dwarf2_cu *type_cu;
23190   struct die_info *type_die;
23191   struct type *type;
23192
23193   sig_type = lookup_signatured_type (cu, signature);
23194   /* sig_type will be NULL if the signatured type is missing from
23195      the debug info.  */
23196   if (sig_type == NULL)
23197     {
23198       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23199                    " from DIE at %s [in module %s]"),
23200                  hex_string (signature), sect_offset_str (die->sect_off),
23201                  objfile_name (dwarf2_per_objfile->objfile));
23202       return build_error_marker_type (cu, die);
23203     }
23204
23205   /* If we already know the type we're done.  */
23206   if (sig_type->type != NULL)
23207     return sig_type->type;
23208
23209   type_cu = cu;
23210   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23211   if (type_die != NULL)
23212     {
23213       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23214          is created.  This is important, for example, because for c++ classes
23215          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23216       type = read_type_die (type_die, type_cu);
23217       if (type == NULL)
23218         {
23219           complaint (_("Dwarf Error: Cannot build signatured type %s"
23220                        " referenced from DIE at %s [in module %s]"),
23221                      hex_string (signature), sect_offset_str (die->sect_off),
23222                      objfile_name (dwarf2_per_objfile->objfile));
23223           type = build_error_marker_type (cu, die);
23224         }
23225     }
23226   else
23227     {
23228       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23229                    " from DIE at %s [in module %s]"),
23230                  hex_string (signature), sect_offset_str (die->sect_off),
23231                  objfile_name (dwarf2_per_objfile->objfile));
23232       type = build_error_marker_type (cu, die);
23233     }
23234   sig_type->type = type;
23235
23236   return type;
23237 }
23238
23239 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23240    reading in and processing the type unit if necessary.  */
23241
23242 static struct type *
23243 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23244                           struct dwarf2_cu *cu) /* ARI: editCase function */
23245 {
23246   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23247   if (attr_form_is_ref (attr))
23248     {
23249       struct dwarf2_cu *type_cu = cu;
23250       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23251
23252       return read_type_die (type_die, type_cu);
23253     }
23254   else if (attr->form == DW_FORM_ref_sig8)
23255     {
23256       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23257     }
23258   else
23259     {
23260       struct dwarf2_per_objfile *dwarf2_per_objfile
23261         = cu->per_cu->dwarf2_per_objfile;
23262
23263       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23264                    " at %s [in module %s]"),
23265                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23266                  objfile_name (dwarf2_per_objfile->objfile));
23267       return build_error_marker_type (cu, die);
23268     }
23269 }
23270
23271 /* Load the DIEs associated with type unit PER_CU into memory.  */
23272
23273 static void
23274 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23275 {
23276   struct signatured_type *sig_type;
23277
23278   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23279   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23280
23281   /* We have the per_cu, but we need the signatured_type.
23282      Fortunately this is an easy translation.  */
23283   gdb_assert (per_cu->is_debug_types);
23284   sig_type = (struct signatured_type *) per_cu;
23285
23286   gdb_assert (per_cu->cu == NULL);
23287
23288   read_signatured_type (sig_type);
23289
23290   gdb_assert (per_cu->cu != NULL);
23291 }
23292
23293 /* die_reader_func for read_signatured_type.
23294    This is identical to load_full_comp_unit_reader,
23295    but is kept separate for now.  */
23296
23297 static void
23298 read_signatured_type_reader (const struct die_reader_specs *reader,
23299                              const gdb_byte *info_ptr,
23300                              struct die_info *comp_unit_die,
23301                              int has_children,
23302                              void *data)
23303 {
23304   struct dwarf2_cu *cu = reader->cu;
23305
23306   gdb_assert (cu->die_hash == NULL);
23307   cu->die_hash =
23308     htab_create_alloc_ex (cu->header.length / 12,
23309                           die_hash,
23310                           die_eq,
23311                           NULL,
23312                           &cu->comp_unit_obstack,
23313                           hashtab_obstack_allocate,
23314                           dummy_obstack_deallocate);
23315
23316   if (has_children)
23317     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23318                                                   &info_ptr, comp_unit_die);
23319   cu->dies = comp_unit_die;
23320   /* comp_unit_die is not stored in die_hash, no need.  */
23321
23322   /* We try not to read any attributes in this function, because not
23323      all CUs needed for references have been loaded yet, and symbol
23324      table processing isn't initialized.  But we have to set the CU language,
23325      or we won't be able to build types correctly.
23326      Similarly, if we do not read the producer, we can not apply
23327      producer-specific interpretation.  */
23328   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23329 }
23330
23331 /* Read in a signatured type and build its CU and DIEs.
23332    If the type is a stub for the real type in a DWO file,
23333    read in the real type from the DWO file as well.  */
23334
23335 static void
23336 read_signatured_type (struct signatured_type *sig_type)
23337 {
23338   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23339
23340   gdb_assert (per_cu->is_debug_types);
23341   gdb_assert (per_cu->cu == NULL);
23342
23343   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23344                            read_signatured_type_reader, NULL);
23345   sig_type->per_cu.tu_read = 1;
23346 }
23347
23348 /* Decode simple location descriptions.
23349    Given a pointer to a dwarf block that defines a location, compute
23350    the location and return the value.
23351
23352    NOTE drow/2003-11-18: This function is called in two situations
23353    now: for the address of static or global variables (partial symbols
23354    only) and for offsets into structures which are expected to be
23355    (more or less) constant.  The partial symbol case should go away,
23356    and only the constant case should remain.  That will let this
23357    function complain more accurately.  A few special modes are allowed
23358    without complaint for global variables (for instance, global
23359    register values and thread-local values).
23360
23361    A location description containing no operations indicates that the
23362    object is optimized out.  The return value is 0 for that case.
23363    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23364    callers will only want a very basic result and this can become a
23365    complaint.
23366
23367    Note that stack[0] is unused except as a default error return.  */
23368
23369 static CORE_ADDR
23370 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23371 {
23372   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23373   size_t i;
23374   size_t size = blk->size;
23375   const gdb_byte *data = blk->data;
23376   CORE_ADDR stack[64];
23377   int stacki;
23378   unsigned int bytes_read, unsnd;
23379   gdb_byte op;
23380
23381   i = 0;
23382   stacki = 0;
23383   stack[stacki] = 0;
23384   stack[++stacki] = 0;
23385
23386   while (i < size)
23387     {
23388       op = data[i++];
23389       switch (op)
23390         {
23391         case DW_OP_lit0:
23392         case DW_OP_lit1:
23393         case DW_OP_lit2:
23394         case DW_OP_lit3:
23395         case DW_OP_lit4:
23396         case DW_OP_lit5:
23397         case DW_OP_lit6:
23398         case DW_OP_lit7:
23399         case DW_OP_lit8:
23400         case DW_OP_lit9:
23401         case DW_OP_lit10:
23402         case DW_OP_lit11:
23403         case DW_OP_lit12:
23404         case DW_OP_lit13:
23405         case DW_OP_lit14:
23406         case DW_OP_lit15:
23407         case DW_OP_lit16:
23408         case DW_OP_lit17:
23409         case DW_OP_lit18:
23410         case DW_OP_lit19:
23411         case DW_OP_lit20:
23412         case DW_OP_lit21:
23413         case DW_OP_lit22:
23414         case DW_OP_lit23:
23415         case DW_OP_lit24:
23416         case DW_OP_lit25:
23417         case DW_OP_lit26:
23418         case DW_OP_lit27:
23419         case DW_OP_lit28:
23420         case DW_OP_lit29:
23421         case DW_OP_lit30:
23422         case DW_OP_lit31:
23423           stack[++stacki] = op - DW_OP_lit0;
23424           break;
23425
23426         case DW_OP_reg0:
23427         case DW_OP_reg1:
23428         case DW_OP_reg2:
23429         case DW_OP_reg3:
23430         case DW_OP_reg4:
23431         case DW_OP_reg5:
23432         case DW_OP_reg6:
23433         case DW_OP_reg7:
23434         case DW_OP_reg8:
23435         case DW_OP_reg9:
23436         case DW_OP_reg10:
23437         case DW_OP_reg11:
23438         case DW_OP_reg12:
23439         case DW_OP_reg13:
23440         case DW_OP_reg14:
23441         case DW_OP_reg15:
23442         case DW_OP_reg16:
23443         case DW_OP_reg17:
23444         case DW_OP_reg18:
23445         case DW_OP_reg19:
23446         case DW_OP_reg20:
23447         case DW_OP_reg21:
23448         case DW_OP_reg22:
23449         case DW_OP_reg23:
23450         case DW_OP_reg24:
23451         case DW_OP_reg25:
23452         case DW_OP_reg26:
23453         case DW_OP_reg27:
23454         case DW_OP_reg28:
23455         case DW_OP_reg29:
23456         case DW_OP_reg30:
23457         case DW_OP_reg31:
23458           stack[++stacki] = op - DW_OP_reg0;
23459           if (i < size)
23460             dwarf2_complex_location_expr_complaint ();
23461           break;
23462
23463         case DW_OP_regx:
23464           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23465           i += bytes_read;
23466           stack[++stacki] = unsnd;
23467           if (i < size)
23468             dwarf2_complex_location_expr_complaint ();
23469           break;
23470
23471         case DW_OP_addr:
23472           stack[++stacki] = read_address (objfile->obfd, &data[i],
23473                                           cu, &bytes_read);
23474           i += bytes_read;
23475           break;
23476
23477         case DW_OP_const1u:
23478           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23479           i += 1;
23480           break;
23481
23482         case DW_OP_const1s:
23483           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23484           i += 1;
23485           break;
23486
23487         case DW_OP_const2u:
23488           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23489           i += 2;
23490           break;
23491
23492         case DW_OP_const2s:
23493           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23494           i += 2;
23495           break;
23496
23497         case DW_OP_const4u:
23498           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23499           i += 4;
23500           break;
23501
23502         case DW_OP_const4s:
23503           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23504           i += 4;
23505           break;
23506
23507         case DW_OP_const8u:
23508           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23509           i += 8;
23510           break;
23511
23512         case DW_OP_constu:
23513           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23514                                                   &bytes_read);
23515           i += bytes_read;
23516           break;
23517
23518         case DW_OP_consts:
23519           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23520           i += bytes_read;
23521           break;
23522
23523         case DW_OP_dup:
23524           stack[stacki + 1] = stack[stacki];
23525           stacki++;
23526           break;
23527
23528         case DW_OP_plus:
23529           stack[stacki - 1] += stack[stacki];
23530           stacki--;
23531           break;
23532
23533         case DW_OP_plus_uconst:
23534           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23535                                                  &bytes_read);
23536           i += bytes_read;
23537           break;
23538
23539         case DW_OP_minus:
23540           stack[stacki - 1] -= stack[stacki];
23541           stacki--;
23542           break;
23543
23544         case DW_OP_deref:
23545           /* If we're not the last op, then we definitely can't encode
23546              this using GDB's address_class enum.  This is valid for partial
23547              global symbols, although the variable's address will be bogus
23548              in the psymtab.  */
23549           if (i < size)
23550             dwarf2_complex_location_expr_complaint ();
23551           break;
23552
23553         case DW_OP_GNU_push_tls_address:
23554         case DW_OP_form_tls_address:
23555           /* The top of the stack has the offset from the beginning
23556              of the thread control block at which the variable is located.  */
23557           /* Nothing should follow this operator, so the top of stack would
23558              be returned.  */
23559           /* This is valid for partial global symbols, but the variable's
23560              address will be bogus in the psymtab.  Make it always at least
23561              non-zero to not look as a variable garbage collected by linker
23562              which have DW_OP_addr 0.  */
23563           if (i < size)
23564             dwarf2_complex_location_expr_complaint ();
23565           stack[stacki]++;
23566           break;
23567
23568         case DW_OP_GNU_uninit:
23569           break;
23570
23571         case DW_OP_GNU_addr_index:
23572         case DW_OP_GNU_const_index:
23573           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23574                                                          &bytes_read);
23575           i += bytes_read;
23576           break;
23577
23578         default:
23579           {
23580             const char *name = get_DW_OP_name (op);
23581
23582             if (name)
23583               complaint (_("unsupported stack op: '%s'"),
23584                          name);
23585             else
23586               complaint (_("unsupported stack op: '%02x'"),
23587                          op);
23588           }
23589
23590           return (stack[stacki]);
23591         }
23592
23593       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23594          outside of the allocated space.  Also enforce minimum>0.  */
23595       if (stacki >= ARRAY_SIZE (stack) - 1)
23596         {
23597           complaint (_("location description stack overflow"));
23598           return 0;
23599         }
23600
23601       if (stacki <= 0)
23602         {
23603           complaint (_("location description stack underflow"));
23604           return 0;
23605         }
23606     }
23607   return (stack[stacki]);
23608 }
23609
23610 /* memory allocation interface */
23611
23612 static struct dwarf_block *
23613 dwarf_alloc_block (struct dwarf2_cu *cu)
23614 {
23615   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23616 }
23617
23618 static struct die_info *
23619 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23620 {
23621   struct die_info *die;
23622   size_t size = sizeof (struct die_info);
23623
23624   if (num_attrs > 1)
23625     size += (num_attrs - 1) * sizeof (struct attribute);
23626
23627   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23628   memset (die, 0, sizeof (struct die_info));
23629   return (die);
23630 }
23631
23632 \f
23633 /* Macro support.  */
23634
23635 /* Return file name relative to the compilation directory of file number I in
23636    *LH's file name table.  The result is allocated using xmalloc; the caller is
23637    responsible for freeing it.  */
23638
23639 static char *
23640 file_file_name (int file, struct line_header *lh)
23641 {
23642   /* Is the file number a valid index into the line header's file name
23643      table?  Remember that file numbers start with one, not zero.  */
23644   if (1 <= file && file <= lh->file_names.size ())
23645     {
23646       const file_entry &fe = lh->file_names[file - 1];
23647
23648       if (!IS_ABSOLUTE_PATH (fe.name))
23649         {
23650           const char *dir = fe.include_dir (lh);
23651           if (dir != NULL)
23652             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23653         }
23654       return xstrdup (fe.name);
23655     }
23656   else
23657     {
23658       /* The compiler produced a bogus file number.  We can at least
23659          record the macro definitions made in the file, even if we
23660          won't be able to find the file by name.  */
23661       char fake_name[80];
23662
23663       xsnprintf (fake_name, sizeof (fake_name),
23664                  "<bad macro file number %d>", file);
23665
23666       complaint (_("bad file number in macro information (%d)"),
23667                  file);
23668
23669       return xstrdup (fake_name);
23670     }
23671 }
23672
23673 /* Return the full name of file number I in *LH's file name table.
23674    Use COMP_DIR as the name of the current directory of the
23675    compilation.  The result is allocated using xmalloc; the caller is
23676    responsible for freeing it.  */
23677 static char *
23678 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23679 {
23680   /* Is the file number a valid index into the line header's file name
23681      table?  Remember that file numbers start with one, not zero.  */
23682   if (1 <= file && file <= lh->file_names.size ())
23683     {
23684       char *relative = file_file_name (file, lh);
23685
23686       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23687         return relative;
23688       return reconcat (relative, comp_dir, SLASH_STRING,
23689                        relative, (char *) NULL);
23690     }
23691   else
23692     return file_file_name (file, lh);
23693 }
23694
23695
23696 static struct macro_source_file *
23697 macro_start_file (int file, int line,
23698                   struct macro_source_file *current_file,
23699                   struct line_header *lh)
23700 {
23701   /* File name relative to the compilation directory of this source file.  */
23702   char *file_name = file_file_name (file, lh);
23703
23704   if (! current_file)
23705     {
23706       /* Note: We don't create a macro table for this compilation unit
23707          at all until we actually get a filename.  */
23708       struct macro_table *macro_table = get_macro_table ();
23709
23710       /* If we have no current file, then this must be the start_file
23711          directive for the compilation unit's main source file.  */
23712       current_file = macro_set_main (macro_table, file_name);
23713       macro_define_special (macro_table);
23714     }
23715   else
23716     current_file = macro_include (current_file, line, file_name);
23717
23718   xfree (file_name);
23719
23720   return current_file;
23721 }
23722
23723 static const char *
23724 consume_improper_spaces (const char *p, const char *body)
23725 {
23726   if (*p == ' ')
23727     {
23728       complaint (_("macro definition contains spaces "
23729                    "in formal argument list:\n`%s'"),
23730                  body);
23731
23732       while (*p == ' ')
23733         p++;
23734     }
23735
23736   return p;
23737 }
23738
23739
23740 static void
23741 parse_macro_definition (struct macro_source_file *file, int line,
23742                         const char *body)
23743 {
23744   const char *p;
23745
23746   /* The body string takes one of two forms.  For object-like macro
23747      definitions, it should be:
23748
23749         <macro name> " " <definition>
23750
23751      For function-like macro definitions, it should be:
23752
23753         <macro name> "() " <definition>
23754      or
23755         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23756
23757      Spaces may appear only where explicitly indicated, and in the
23758      <definition>.
23759
23760      The Dwarf 2 spec says that an object-like macro's name is always
23761      followed by a space, but versions of GCC around March 2002 omit
23762      the space when the macro's definition is the empty string.
23763
23764      The Dwarf 2 spec says that there should be no spaces between the
23765      formal arguments in a function-like macro's formal argument list,
23766      but versions of GCC around March 2002 include spaces after the
23767      commas.  */
23768
23769
23770   /* Find the extent of the macro name.  The macro name is terminated
23771      by either a space or null character (for an object-like macro) or
23772      an opening paren (for a function-like macro).  */
23773   for (p = body; *p; p++)
23774     if (*p == ' ' || *p == '(')
23775       break;
23776
23777   if (*p == ' ' || *p == '\0')
23778     {
23779       /* It's an object-like macro.  */
23780       int name_len = p - body;
23781       char *name = savestring (body, name_len);
23782       const char *replacement;
23783
23784       if (*p == ' ')
23785         replacement = body + name_len + 1;
23786       else
23787         {
23788           dwarf2_macro_malformed_definition_complaint (body);
23789           replacement = body + name_len;
23790         }
23791
23792       macro_define_object (file, line, name, replacement);
23793
23794       xfree (name);
23795     }
23796   else if (*p == '(')
23797     {
23798       /* It's a function-like macro.  */
23799       char *name = savestring (body, p - body);
23800       int argc = 0;
23801       int argv_size = 1;
23802       char **argv = XNEWVEC (char *, argv_size);
23803
23804       p++;
23805
23806       p = consume_improper_spaces (p, body);
23807
23808       /* Parse the formal argument list.  */
23809       while (*p && *p != ')')
23810         {
23811           /* Find the extent of the current argument name.  */
23812           const char *arg_start = p;
23813
23814           while (*p && *p != ',' && *p != ')' && *p != ' ')
23815             p++;
23816
23817           if (! *p || p == arg_start)
23818             dwarf2_macro_malformed_definition_complaint (body);
23819           else
23820             {
23821               /* Make sure argv has room for the new argument.  */
23822               if (argc >= argv_size)
23823                 {
23824                   argv_size *= 2;
23825                   argv = XRESIZEVEC (char *, argv, argv_size);
23826                 }
23827
23828               argv[argc++] = savestring (arg_start, p - arg_start);
23829             }
23830
23831           p = consume_improper_spaces (p, body);
23832
23833           /* Consume the comma, if present.  */
23834           if (*p == ',')
23835             {
23836               p++;
23837
23838               p = consume_improper_spaces (p, body);
23839             }
23840         }
23841
23842       if (*p == ')')
23843         {
23844           p++;
23845
23846           if (*p == ' ')
23847             /* Perfectly formed definition, no complaints.  */
23848             macro_define_function (file, line, name,
23849                                    argc, (const char **) argv,
23850                                    p + 1);
23851           else if (*p == '\0')
23852             {
23853               /* Complain, but do define it.  */
23854               dwarf2_macro_malformed_definition_complaint (body);
23855               macro_define_function (file, line, name,
23856                                      argc, (const char **) argv,
23857                                      p);
23858             }
23859           else
23860             /* Just complain.  */
23861             dwarf2_macro_malformed_definition_complaint (body);
23862         }
23863       else
23864         /* Just complain.  */
23865         dwarf2_macro_malformed_definition_complaint (body);
23866
23867       xfree (name);
23868       {
23869         int i;
23870
23871         for (i = 0; i < argc; i++)
23872           xfree (argv[i]);
23873       }
23874       xfree (argv);
23875     }
23876   else
23877     dwarf2_macro_malformed_definition_complaint (body);
23878 }
23879
23880 /* Skip some bytes from BYTES according to the form given in FORM.
23881    Returns the new pointer.  */
23882
23883 static const gdb_byte *
23884 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23885                  enum dwarf_form form,
23886                  unsigned int offset_size,
23887                  struct dwarf2_section_info *section)
23888 {
23889   unsigned int bytes_read;
23890
23891   switch (form)
23892     {
23893     case DW_FORM_data1:
23894     case DW_FORM_flag:
23895       ++bytes;
23896       break;
23897
23898     case DW_FORM_data2:
23899       bytes += 2;
23900       break;
23901
23902     case DW_FORM_data4:
23903       bytes += 4;
23904       break;
23905
23906     case DW_FORM_data8:
23907       bytes += 8;
23908       break;
23909
23910     case DW_FORM_data16:
23911       bytes += 16;
23912       break;
23913
23914     case DW_FORM_string:
23915       read_direct_string (abfd, bytes, &bytes_read);
23916       bytes += bytes_read;
23917       break;
23918
23919     case DW_FORM_sec_offset:
23920     case DW_FORM_strp:
23921     case DW_FORM_GNU_strp_alt:
23922       bytes += offset_size;
23923       break;
23924
23925     case DW_FORM_block:
23926       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
23927       bytes += bytes_read;
23928       break;
23929
23930     case DW_FORM_block1:
23931       bytes += 1 + read_1_byte (abfd, bytes);
23932       break;
23933     case DW_FORM_block2:
23934       bytes += 2 + read_2_bytes (abfd, bytes);
23935       break;
23936     case DW_FORM_block4:
23937       bytes += 4 + read_4_bytes (abfd, bytes);
23938       break;
23939
23940     case DW_FORM_sdata:
23941     case DW_FORM_udata:
23942     case DW_FORM_GNU_addr_index:
23943     case DW_FORM_GNU_str_index:
23944       bytes = gdb_skip_leb128 (bytes, buffer_end);
23945       if (bytes == NULL)
23946         {
23947           dwarf2_section_buffer_overflow_complaint (section);
23948           return NULL;
23949         }
23950       break;
23951
23952     case DW_FORM_implicit_const:
23953       break;
23954
23955     default:
23956       {
23957         complaint (_("invalid form 0x%x in `%s'"),
23958                    form, get_section_name (section));
23959         return NULL;
23960       }
23961     }
23962
23963   return bytes;
23964 }
23965
23966 /* A helper for dwarf_decode_macros that handles skipping an unknown
23967    opcode.  Returns an updated pointer to the macro data buffer; or,
23968    on error, issues a complaint and returns NULL.  */
23969
23970 static const gdb_byte *
23971 skip_unknown_opcode (unsigned int opcode,
23972                      const gdb_byte **opcode_definitions,
23973                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
23974                      bfd *abfd,
23975                      unsigned int offset_size,
23976                      struct dwarf2_section_info *section)
23977 {
23978   unsigned int bytes_read, i;
23979   unsigned long arg;
23980   const gdb_byte *defn;
23981
23982   if (opcode_definitions[opcode] == NULL)
23983     {
23984       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
23985                  opcode);
23986       return NULL;
23987     }
23988
23989   defn = opcode_definitions[opcode];
23990   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
23991   defn += bytes_read;
23992
23993   for (i = 0; i < arg; ++i)
23994     {
23995       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
23996                                  (enum dwarf_form) defn[i], offset_size,
23997                                  section);
23998       if (mac_ptr == NULL)
23999         {
24000           /* skip_form_bytes already issued the complaint.  */
24001           return NULL;
24002         }
24003     }
24004
24005   return mac_ptr;
24006 }
24007
24008 /* A helper function which parses the header of a macro section.
24009    If the macro section is the extended (for now called "GNU") type,
24010    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24011    the header, or issues a complaint and returns NULL on error.  */
24012
24013 static const gdb_byte *
24014 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24015                           bfd *abfd,
24016                           const gdb_byte *mac_ptr,
24017                           unsigned int *offset_size,
24018                           int section_is_gnu)
24019 {
24020   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24021
24022   if (section_is_gnu)
24023     {
24024       unsigned int version, flags;
24025
24026       version = read_2_bytes (abfd, mac_ptr);
24027       if (version != 4 && version != 5)
24028         {
24029           complaint (_("unrecognized version `%d' in .debug_macro section"),
24030                      version);
24031           return NULL;
24032         }
24033       mac_ptr += 2;
24034
24035       flags = read_1_byte (abfd, mac_ptr);
24036       ++mac_ptr;
24037       *offset_size = (flags & 1) ? 8 : 4;
24038
24039       if ((flags & 2) != 0)
24040         /* We don't need the line table offset.  */
24041         mac_ptr += *offset_size;
24042
24043       /* Vendor opcode descriptions.  */
24044       if ((flags & 4) != 0)
24045         {
24046           unsigned int i, count;
24047
24048           count = read_1_byte (abfd, mac_ptr);
24049           ++mac_ptr;
24050           for (i = 0; i < count; ++i)
24051             {
24052               unsigned int opcode, bytes_read;
24053               unsigned long arg;
24054
24055               opcode = read_1_byte (abfd, mac_ptr);
24056               ++mac_ptr;
24057               opcode_definitions[opcode] = mac_ptr;
24058               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24059               mac_ptr += bytes_read;
24060               mac_ptr += arg;
24061             }
24062         }
24063     }
24064
24065   return mac_ptr;
24066 }
24067
24068 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24069    including DW_MACRO_import.  */
24070
24071 static void
24072 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24073                           bfd *abfd,
24074                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24075                           struct macro_source_file *current_file,
24076                           struct line_header *lh,
24077                           struct dwarf2_section_info *section,
24078                           int section_is_gnu, int section_is_dwz,
24079                           unsigned int offset_size,
24080                           htab_t include_hash)
24081 {
24082   struct objfile *objfile = dwarf2_per_objfile->objfile;
24083   enum dwarf_macro_record_type macinfo_type;
24084   int at_commandline;
24085   const gdb_byte *opcode_definitions[256];
24086
24087   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24088                                       &offset_size, section_is_gnu);
24089   if (mac_ptr == NULL)
24090     {
24091       /* We already issued a complaint.  */
24092       return;
24093     }
24094
24095   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24096      GDB is still reading the definitions from command line.  First
24097      DW_MACINFO_start_file will need to be ignored as it was already executed
24098      to create CURRENT_FILE for the main source holding also the command line
24099      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24100      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24101
24102   at_commandline = 1;
24103
24104   do
24105     {
24106       /* Do we at least have room for a macinfo type byte?  */
24107       if (mac_ptr >= mac_end)
24108         {
24109           dwarf2_section_buffer_overflow_complaint (section);
24110           break;
24111         }
24112
24113       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24114       mac_ptr++;
24115
24116       /* Note that we rely on the fact that the corresponding GNU and
24117          DWARF constants are the same.  */
24118       DIAGNOSTIC_PUSH
24119       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24120       switch (macinfo_type)
24121         {
24122           /* A zero macinfo type indicates the end of the macro
24123              information.  */
24124         case 0:
24125           break;
24126
24127         case DW_MACRO_define:
24128         case DW_MACRO_undef:
24129         case DW_MACRO_define_strp:
24130         case DW_MACRO_undef_strp:
24131         case DW_MACRO_define_sup:
24132         case DW_MACRO_undef_sup:
24133           {
24134             unsigned int bytes_read;
24135             int line;
24136             const char *body;
24137             int is_define;
24138
24139             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24140             mac_ptr += bytes_read;
24141
24142             if (macinfo_type == DW_MACRO_define
24143                 || macinfo_type == DW_MACRO_undef)
24144               {
24145                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24146                 mac_ptr += bytes_read;
24147               }
24148             else
24149               {
24150                 LONGEST str_offset;
24151
24152                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24153                 mac_ptr += offset_size;
24154
24155                 if (macinfo_type == DW_MACRO_define_sup
24156                     || macinfo_type == DW_MACRO_undef_sup
24157                     || section_is_dwz)
24158                   {
24159                     struct dwz_file *dwz
24160                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24161
24162                     body = read_indirect_string_from_dwz (objfile,
24163                                                           dwz, str_offset);
24164                   }
24165                 else
24166                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24167                                                          abfd, str_offset);
24168               }
24169
24170             is_define = (macinfo_type == DW_MACRO_define
24171                          || macinfo_type == DW_MACRO_define_strp
24172                          || macinfo_type == DW_MACRO_define_sup);
24173             if (! current_file)
24174               {
24175                 /* DWARF violation as no main source is present.  */
24176                 complaint (_("debug info with no main source gives macro %s "
24177                              "on line %d: %s"),
24178                            is_define ? _("definition") : _("undefinition"),
24179                            line, body);
24180                 break;
24181               }
24182             if ((line == 0 && !at_commandline)
24183                 || (line != 0 && at_commandline))
24184               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24185                          at_commandline ? _("command-line") : _("in-file"),
24186                          is_define ? _("definition") : _("undefinition"),
24187                          line == 0 ? _("zero") : _("non-zero"), line, body);
24188
24189             if (is_define)
24190               parse_macro_definition (current_file, line, body);
24191             else
24192               {
24193                 gdb_assert (macinfo_type == DW_MACRO_undef
24194                             || macinfo_type == DW_MACRO_undef_strp
24195                             || macinfo_type == DW_MACRO_undef_sup);
24196                 macro_undef (current_file, line, body);
24197               }
24198           }
24199           break;
24200
24201         case DW_MACRO_start_file:
24202           {
24203             unsigned int bytes_read;
24204             int line, file;
24205
24206             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24207             mac_ptr += bytes_read;
24208             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24209             mac_ptr += bytes_read;
24210
24211             if ((line == 0 && !at_commandline)
24212                 || (line != 0 && at_commandline))
24213               complaint (_("debug info gives source %d included "
24214                            "from %s at %s line %d"),
24215                          file, at_commandline ? _("command-line") : _("file"),
24216                          line == 0 ? _("zero") : _("non-zero"), line);
24217
24218             if (at_commandline)
24219               {
24220                 /* This DW_MACRO_start_file was executed in the
24221                    pass one.  */
24222                 at_commandline = 0;
24223               }
24224             else
24225               current_file = macro_start_file (file, line, current_file, lh);
24226           }
24227           break;
24228
24229         case DW_MACRO_end_file:
24230           if (! current_file)
24231             complaint (_("macro debug info has an unmatched "
24232                          "`close_file' directive"));
24233           else
24234             {
24235               current_file = current_file->included_by;
24236               if (! current_file)
24237                 {
24238                   enum dwarf_macro_record_type next_type;
24239
24240                   /* GCC circa March 2002 doesn't produce the zero
24241                      type byte marking the end of the compilation
24242                      unit.  Complain if it's not there, but exit no
24243                      matter what.  */
24244
24245                   /* Do we at least have room for a macinfo type byte?  */
24246                   if (mac_ptr >= mac_end)
24247                     {
24248                       dwarf2_section_buffer_overflow_complaint (section);
24249                       return;
24250                     }
24251
24252                   /* We don't increment mac_ptr here, so this is just
24253                      a look-ahead.  */
24254                   next_type
24255                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24256                                                                   mac_ptr);
24257                   if (next_type != 0)
24258                     complaint (_("no terminating 0-type entry for "
24259                                  "macros in `.debug_macinfo' section"));
24260
24261                   return;
24262                 }
24263             }
24264           break;
24265
24266         case DW_MACRO_import:
24267         case DW_MACRO_import_sup:
24268           {
24269             LONGEST offset;
24270             void **slot;
24271             bfd *include_bfd = abfd;
24272             struct dwarf2_section_info *include_section = section;
24273             const gdb_byte *include_mac_end = mac_end;
24274             int is_dwz = section_is_dwz;
24275             const gdb_byte *new_mac_ptr;
24276
24277             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24278             mac_ptr += offset_size;
24279
24280             if (macinfo_type == DW_MACRO_import_sup)
24281               {
24282                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24283
24284                 dwarf2_read_section (objfile, &dwz->macro);
24285
24286                 include_section = &dwz->macro;
24287                 include_bfd = get_section_bfd_owner (include_section);
24288                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24289                 is_dwz = 1;
24290               }
24291
24292             new_mac_ptr = include_section->buffer + offset;
24293             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24294
24295             if (*slot != NULL)
24296               {
24297                 /* This has actually happened; see
24298                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24299                 complaint (_("recursive DW_MACRO_import in "
24300                              ".debug_macro section"));
24301               }
24302             else
24303               {
24304                 *slot = (void *) new_mac_ptr;
24305
24306                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24307                                           include_bfd, new_mac_ptr,
24308                                           include_mac_end, current_file, lh,
24309                                           section, section_is_gnu, is_dwz,
24310                                           offset_size, include_hash);
24311
24312                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24313               }
24314           }
24315           break;
24316
24317         case DW_MACINFO_vendor_ext:
24318           if (!section_is_gnu)
24319             {
24320               unsigned int bytes_read;
24321
24322               /* This reads the constant, but since we don't recognize
24323                  any vendor extensions, we ignore it.  */
24324               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24325               mac_ptr += bytes_read;
24326               read_direct_string (abfd, mac_ptr, &bytes_read);
24327               mac_ptr += bytes_read;
24328
24329               /* We don't recognize any vendor extensions.  */
24330               break;
24331             }
24332           /* FALLTHROUGH */
24333
24334         default:
24335           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24336                                          mac_ptr, mac_end, abfd, offset_size,
24337                                          section);
24338           if (mac_ptr == NULL)
24339             return;
24340           break;
24341         }
24342       DIAGNOSTIC_POP
24343     } while (macinfo_type != 0);
24344 }
24345
24346 static void
24347 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24348                      int section_is_gnu)
24349 {
24350   struct dwarf2_per_objfile *dwarf2_per_objfile
24351     = cu->per_cu->dwarf2_per_objfile;
24352   struct objfile *objfile = dwarf2_per_objfile->objfile;
24353   struct line_header *lh = cu->line_header;
24354   bfd *abfd;
24355   const gdb_byte *mac_ptr, *mac_end;
24356   struct macro_source_file *current_file = 0;
24357   enum dwarf_macro_record_type macinfo_type;
24358   unsigned int offset_size = cu->header.offset_size;
24359   const gdb_byte *opcode_definitions[256];
24360   void **slot;
24361   struct dwarf2_section_info *section;
24362   const char *section_name;
24363
24364   if (cu->dwo_unit != NULL)
24365     {
24366       if (section_is_gnu)
24367         {
24368           section = &cu->dwo_unit->dwo_file->sections.macro;
24369           section_name = ".debug_macro.dwo";
24370         }
24371       else
24372         {
24373           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24374           section_name = ".debug_macinfo.dwo";
24375         }
24376     }
24377   else
24378     {
24379       if (section_is_gnu)
24380         {
24381           section = &dwarf2_per_objfile->macro;
24382           section_name = ".debug_macro";
24383         }
24384       else
24385         {
24386           section = &dwarf2_per_objfile->macinfo;
24387           section_name = ".debug_macinfo";
24388         }
24389     }
24390
24391   dwarf2_read_section (objfile, section);
24392   if (section->buffer == NULL)
24393     {
24394       complaint (_("missing %s section"), section_name);
24395       return;
24396     }
24397   abfd = get_section_bfd_owner (section);
24398
24399   /* First pass: Find the name of the base filename.
24400      This filename is needed in order to process all macros whose definition
24401      (or undefinition) comes from the command line.  These macros are defined
24402      before the first DW_MACINFO_start_file entry, and yet still need to be
24403      associated to the base file.
24404
24405      To determine the base file name, we scan the macro definitions until we
24406      reach the first DW_MACINFO_start_file entry.  We then initialize
24407      CURRENT_FILE accordingly so that any macro definition found before the
24408      first DW_MACINFO_start_file can still be associated to the base file.  */
24409
24410   mac_ptr = section->buffer + offset;
24411   mac_end = section->buffer + section->size;
24412
24413   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24414                                       &offset_size, section_is_gnu);
24415   if (mac_ptr == NULL)
24416     {
24417       /* We already issued a complaint.  */
24418       return;
24419     }
24420
24421   do
24422     {
24423       /* Do we at least have room for a macinfo type byte?  */
24424       if (mac_ptr >= mac_end)
24425         {
24426           /* Complaint is printed during the second pass as GDB will probably
24427              stop the first pass earlier upon finding
24428              DW_MACINFO_start_file.  */
24429           break;
24430         }
24431
24432       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24433       mac_ptr++;
24434
24435       /* Note that we rely on the fact that the corresponding GNU and
24436          DWARF constants are the same.  */
24437       DIAGNOSTIC_PUSH
24438       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24439       switch (macinfo_type)
24440         {
24441           /* A zero macinfo type indicates the end of the macro
24442              information.  */
24443         case 0:
24444           break;
24445
24446         case DW_MACRO_define:
24447         case DW_MACRO_undef:
24448           /* Only skip the data by MAC_PTR.  */
24449           {
24450             unsigned int bytes_read;
24451
24452             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24453             mac_ptr += bytes_read;
24454             read_direct_string (abfd, mac_ptr, &bytes_read);
24455             mac_ptr += bytes_read;
24456           }
24457           break;
24458
24459         case DW_MACRO_start_file:
24460           {
24461             unsigned int bytes_read;
24462             int line, file;
24463
24464             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24465             mac_ptr += bytes_read;
24466             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24467             mac_ptr += bytes_read;
24468
24469             current_file = macro_start_file (file, line, current_file, lh);
24470           }
24471           break;
24472
24473         case DW_MACRO_end_file:
24474           /* No data to skip by MAC_PTR.  */
24475           break;
24476
24477         case DW_MACRO_define_strp:
24478         case DW_MACRO_undef_strp:
24479         case DW_MACRO_define_sup:
24480         case DW_MACRO_undef_sup:
24481           {
24482             unsigned int bytes_read;
24483
24484             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24485             mac_ptr += bytes_read;
24486             mac_ptr += offset_size;
24487           }
24488           break;
24489
24490         case DW_MACRO_import:
24491         case DW_MACRO_import_sup:
24492           /* Note that, according to the spec, a transparent include
24493              chain cannot call DW_MACRO_start_file.  So, we can just
24494              skip this opcode.  */
24495           mac_ptr += offset_size;
24496           break;
24497
24498         case DW_MACINFO_vendor_ext:
24499           /* Only skip the data by MAC_PTR.  */
24500           if (!section_is_gnu)
24501             {
24502               unsigned int bytes_read;
24503
24504               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24505               mac_ptr += bytes_read;
24506               read_direct_string (abfd, mac_ptr, &bytes_read);
24507               mac_ptr += bytes_read;
24508             }
24509           /* FALLTHROUGH */
24510
24511         default:
24512           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24513                                          mac_ptr, mac_end, abfd, offset_size,
24514                                          section);
24515           if (mac_ptr == NULL)
24516             return;
24517           break;
24518         }
24519       DIAGNOSTIC_POP
24520     } while (macinfo_type != 0 && current_file == NULL);
24521
24522   /* Second pass: Process all entries.
24523
24524      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24525      command-line macro definitions/undefinitions.  This flag is unset when we
24526      reach the first DW_MACINFO_start_file entry.  */
24527
24528   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24529                                            htab_eq_pointer,
24530                                            NULL, xcalloc, xfree));
24531   mac_ptr = section->buffer + offset;
24532   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24533   *slot = (void *) mac_ptr;
24534   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24535                             abfd, mac_ptr, mac_end,
24536                             current_file, lh, section,
24537                             section_is_gnu, 0, offset_size,
24538                             include_hash.get ());
24539 }
24540
24541 /* Check if the attribute's form is a DW_FORM_block*
24542    if so return true else false.  */
24543
24544 static int
24545 attr_form_is_block (const struct attribute *attr)
24546 {
24547   return (attr == NULL ? 0 :
24548       attr->form == DW_FORM_block1
24549       || attr->form == DW_FORM_block2
24550       || attr->form == DW_FORM_block4
24551       || attr->form == DW_FORM_block
24552       || attr->form == DW_FORM_exprloc);
24553 }
24554
24555 /* Return non-zero if ATTR's value is a section offset --- classes
24556    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24557    You may use DW_UNSND (attr) to retrieve such offsets.
24558
24559    Section 7.5.4, "Attribute Encodings", explains that no attribute
24560    may have a value that belongs to more than one of these classes; it
24561    would be ambiguous if we did, because we use the same forms for all
24562    of them.  */
24563
24564 static int
24565 attr_form_is_section_offset (const struct attribute *attr)
24566 {
24567   return (attr->form == DW_FORM_data4
24568           || attr->form == DW_FORM_data8
24569           || attr->form == DW_FORM_sec_offset);
24570 }
24571
24572 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24573    zero otherwise.  When this function returns true, you can apply
24574    dwarf2_get_attr_constant_value to it.
24575
24576    However, note that for some attributes you must check
24577    attr_form_is_section_offset before using this test.  DW_FORM_data4
24578    and DW_FORM_data8 are members of both the constant class, and of
24579    the classes that contain offsets into other debug sections
24580    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24581    that, if an attribute's can be either a constant or one of the
24582    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24583    taken as section offsets, not constants.
24584
24585    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24586    cannot handle that.  */
24587
24588 static int
24589 attr_form_is_constant (const struct attribute *attr)
24590 {
24591   switch (attr->form)
24592     {
24593     case DW_FORM_sdata:
24594     case DW_FORM_udata:
24595     case DW_FORM_data1:
24596     case DW_FORM_data2:
24597     case DW_FORM_data4:
24598     case DW_FORM_data8:
24599     case DW_FORM_implicit_const:
24600       return 1;
24601     default:
24602       return 0;
24603     }
24604 }
24605
24606
24607 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24608    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24609
24610 static int
24611 attr_form_is_ref (const struct attribute *attr)
24612 {
24613   switch (attr->form)
24614     {
24615     case DW_FORM_ref_addr:
24616     case DW_FORM_ref1:
24617     case DW_FORM_ref2:
24618     case DW_FORM_ref4:
24619     case DW_FORM_ref8:
24620     case DW_FORM_ref_udata:
24621     case DW_FORM_GNU_ref_alt:
24622       return 1;
24623     default:
24624       return 0;
24625     }
24626 }
24627
24628 /* Return the .debug_loc section to use for CU.
24629    For DWO files use .debug_loc.dwo.  */
24630
24631 static struct dwarf2_section_info *
24632 cu_debug_loc_section (struct dwarf2_cu *cu)
24633 {
24634   struct dwarf2_per_objfile *dwarf2_per_objfile
24635     = cu->per_cu->dwarf2_per_objfile;
24636
24637   if (cu->dwo_unit)
24638     {
24639       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24640       
24641       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24642     }
24643   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24644                                   : &dwarf2_per_objfile->loc);
24645 }
24646
24647 /* A helper function that fills in a dwarf2_loclist_baton.  */
24648
24649 static void
24650 fill_in_loclist_baton (struct dwarf2_cu *cu,
24651                        struct dwarf2_loclist_baton *baton,
24652                        const struct attribute *attr)
24653 {
24654   struct dwarf2_per_objfile *dwarf2_per_objfile
24655     = cu->per_cu->dwarf2_per_objfile;
24656   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24657
24658   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24659
24660   baton->per_cu = cu->per_cu;
24661   gdb_assert (baton->per_cu);
24662   /* We don't know how long the location list is, but make sure we
24663      don't run off the edge of the section.  */
24664   baton->size = section->size - DW_UNSND (attr);
24665   baton->data = section->buffer + DW_UNSND (attr);
24666   baton->base_address = cu->base_address;
24667   baton->from_dwo = cu->dwo_unit != NULL;
24668 }
24669
24670 static void
24671 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24672                              struct dwarf2_cu *cu, int is_block)
24673 {
24674   struct dwarf2_per_objfile *dwarf2_per_objfile
24675     = cu->per_cu->dwarf2_per_objfile;
24676   struct objfile *objfile = dwarf2_per_objfile->objfile;
24677   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24678
24679   if (attr_form_is_section_offset (attr)
24680       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24681          the section.  If so, fall through to the complaint in the
24682          other branch.  */
24683       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24684     {
24685       struct dwarf2_loclist_baton *baton;
24686
24687       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24688
24689       fill_in_loclist_baton (cu, baton, attr);
24690
24691       if (cu->base_known == 0)
24692         complaint (_("Location list used without "
24693                      "specifying the CU base address."));
24694
24695       SYMBOL_ACLASS_INDEX (sym) = (is_block
24696                                    ? dwarf2_loclist_block_index
24697                                    : dwarf2_loclist_index);
24698       SYMBOL_LOCATION_BATON (sym) = baton;
24699     }
24700   else
24701     {
24702       struct dwarf2_locexpr_baton *baton;
24703
24704       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24705       baton->per_cu = cu->per_cu;
24706       gdb_assert (baton->per_cu);
24707
24708       if (attr_form_is_block (attr))
24709         {
24710           /* Note that we're just copying the block's data pointer
24711              here, not the actual data.  We're still pointing into the
24712              info_buffer for SYM's objfile; right now we never release
24713              that buffer, but when we do clean up properly this may
24714              need to change.  */
24715           baton->size = DW_BLOCK (attr)->size;
24716           baton->data = DW_BLOCK (attr)->data;
24717         }
24718       else
24719         {
24720           dwarf2_invalid_attrib_class_complaint ("location description",
24721                                                  SYMBOL_NATURAL_NAME (sym));
24722           baton->size = 0;
24723         }
24724
24725       SYMBOL_ACLASS_INDEX (sym) = (is_block
24726                                    ? dwarf2_locexpr_block_index
24727                                    : dwarf2_locexpr_index);
24728       SYMBOL_LOCATION_BATON (sym) = baton;
24729     }
24730 }
24731
24732 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24733    came from a separate debuginfo file, then the master objfile is
24734    returned.  */
24735
24736 struct objfile *
24737 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24738 {
24739   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24740
24741   /* Return the master objfile, so that we can report and look up the
24742      correct file containing this variable.  */
24743   if (objfile->separate_debug_objfile_backlink)
24744     objfile = objfile->separate_debug_objfile_backlink;
24745
24746   return objfile;
24747 }
24748
24749 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24750    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24751    CU_HEADERP first.  */
24752
24753 static const struct comp_unit_head *
24754 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24755                        struct dwarf2_per_cu_data *per_cu)
24756 {
24757   const gdb_byte *info_ptr;
24758
24759   if (per_cu->cu)
24760     return &per_cu->cu->header;
24761
24762   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24763
24764   memset (cu_headerp, 0, sizeof (*cu_headerp));
24765   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24766                        rcuh_kind::COMPILE);
24767
24768   return cu_headerp;
24769 }
24770
24771 /* Return the address size given in the compilation unit header for CU.  */
24772
24773 int
24774 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24775 {
24776   struct comp_unit_head cu_header_local;
24777   const struct comp_unit_head *cu_headerp;
24778
24779   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24780
24781   return cu_headerp->addr_size;
24782 }
24783
24784 /* Return the offset size given in the compilation unit header for CU.  */
24785
24786 int
24787 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24788 {
24789   struct comp_unit_head cu_header_local;
24790   const struct comp_unit_head *cu_headerp;
24791
24792   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24793
24794   return cu_headerp->offset_size;
24795 }
24796
24797 /* See its dwarf2loc.h declaration.  */
24798
24799 int
24800 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24801 {
24802   struct comp_unit_head cu_header_local;
24803   const struct comp_unit_head *cu_headerp;
24804
24805   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24806
24807   if (cu_headerp->version == 2)
24808     return cu_headerp->addr_size;
24809   else
24810     return cu_headerp->offset_size;
24811 }
24812
24813 /* Return the text offset of the CU.  The returned offset comes from
24814    this CU's objfile.  If this objfile came from a separate debuginfo
24815    file, then the offset may be different from the corresponding
24816    offset in the parent objfile.  */
24817
24818 CORE_ADDR
24819 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24820 {
24821   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24822
24823   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24824 }
24825
24826 /* Return DWARF version number of PER_CU.  */
24827
24828 short
24829 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24830 {
24831   return per_cu->dwarf_version;
24832 }
24833
24834 /* Locate the .debug_info compilation unit from CU's objfile which contains
24835    the DIE at OFFSET.  Raises an error on failure.  */
24836
24837 static struct dwarf2_per_cu_data *
24838 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24839                                   unsigned int offset_in_dwz,
24840                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24841 {
24842   struct dwarf2_per_cu_data *this_cu;
24843   int low, high;
24844   const sect_offset *cu_off;
24845
24846   low = 0;
24847   high = dwarf2_per_objfile->all_comp_units.size () - 1;
24848   while (high > low)
24849     {
24850       struct dwarf2_per_cu_data *mid_cu;
24851       int mid = low + (high - low) / 2;
24852
24853       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24854       cu_off = &mid_cu->sect_off;
24855       if (mid_cu->is_dwz > offset_in_dwz
24856           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24857         high = mid;
24858       else
24859         low = mid + 1;
24860     }
24861   gdb_assert (low == high);
24862   this_cu = dwarf2_per_objfile->all_comp_units[low];
24863   cu_off = &this_cu->sect_off;
24864   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24865     {
24866       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24867         error (_("Dwarf Error: could not find partial DIE containing "
24868                "offset %s [in module %s]"),
24869                sect_offset_str (sect_off),
24870                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
24871
24872       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24873                   <= sect_off);
24874       return dwarf2_per_objfile->all_comp_units[low-1];
24875     }
24876   else
24877     {
24878       this_cu = dwarf2_per_objfile->all_comp_units[low];
24879       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
24880           && sect_off >= this_cu->sect_off + this_cu->length)
24881         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
24882       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24883       return this_cu;
24884     }
24885 }
24886
24887 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24888
24889 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
24890   : per_cu (per_cu_),
24891     mark (0),
24892     has_loclist (0),
24893     checked_producer (0),
24894     producer_is_gxx_lt_4_6 (0),
24895     producer_is_gcc_lt_4_3 (0),
24896     producer_is_icc_lt_14 (0),
24897     processing_has_namespace_info (0)
24898 {
24899   per_cu->cu = this;
24900 }
24901
24902 /* Destroy a dwarf2_cu.  */
24903
24904 dwarf2_cu::~dwarf2_cu ()
24905 {
24906   per_cu->cu = NULL;
24907 }
24908
24909 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24910
24911 static void
24912 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24913                        enum language pretend_language)
24914 {
24915   struct attribute *attr;
24916
24917   /* Set the language we're debugging.  */
24918   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24919   if (attr)
24920     set_cu_language (DW_UNSND (attr), cu);
24921   else
24922     {
24923       cu->language = pretend_language;
24924       cu->language_defn = language_def (cu->language);
24925     }
24926
24927   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24928 }
24929
24930 /* Increase the age counter on each cached compilation unit, and free
24931    any that are too old.  */
24932
24933 static void
24934 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
24935 {
24936   struct dwarf2_per_cu_data *per_cu, **last_chain;
24937
24938   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
24939   per_cu = dwarf2_per_objfile->read_in_chain;
24940   while (per_cu != NULL)
24941     {
24942       per_cu->cu->last_used ++;
24943       if (per_cu->cu->last_used <= dwarf_max_cache_age)
24944         dwarf2_mark (per_cu->cu);
24945       per_cu = per_cu->cu->read_in_chain;
24946     }
24947
24948   per_cu = dwarf2_per_objfile->read_in_chain;
24949   last_chain = &dwarf2_per_objfile->read_in_chain;
24950   while (per_cu != NULL)
24951     {
24952       struct dwarf2_per_cu_data *next_cu;
24953
24954       next_cu = per_cu->cu->read_in_chain;
24955
24956       if (!per_cu->cu->mark)
24957         {
24958           delete per_cu->cu;
24959           *last_chain = next_cu;
24960         }
24961       else
24962         last_chain = &per_cu->cu->read_in_chain;
24963
24964       per_cu = next_cu;
24965     }
24966 }
24967
24968 /* Remove a single compilation unit from the cache.  */
24969
24970 static void
24971 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
24972 {
24973   struct dwarf2_per_cu_data *per_cu, **last_chain;
24974   struct dwarf2_per_objfile *dwarf2_per_objfile
24975     = target_per_cu->dwarf2_per_objfile;
24976
24977   per_cu = dwarf2_per_objfile->read_in_chain;
24978   last_chain = &dwarf2_per_objfile->read_in_chain;
24979   while (per_cu != NULL)
24980     {
24981       struct dwarf2_per_cu_data *next_cu;
24982
24983       next_cu = per_cu->cu->read_in_chain;
24984
24985       if (per_cu == target_per_cu)
24986         {
24987           delete per_cu->cu;
24988           per_cu->cu = NULL;
24989           *last_chain = next_cu;
24990           break;
24991         }
24992       else
24993         last_chain = &per_cu->cu->read_in_chain;
24994
24995       per_cu = next_cu;
24996     }
24997 }
24998
24999 /* Cleanup function for the dwarf2_per_objfile data.  */
25000
25001 static void
25002 dwarf2_free_objfile (struct objfile *objfile, void *datum)
25003 {
25004   struct dwarf2_per_objfile *dwarf2_per_objfile
25005     = static_cast<struct dwarf2_per_objfile *> (datum);
25006
25007   delete dwarf2_per_objfile;
25008 }
25009
25010 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25011    We store these in a hash table separate from the DIEs, and preserve them
25012    when the DIEs are flushed out of cache.
25013
25014    The CU "per_cu" pointer is needed because offset alone is not enough to
25015    uniquely identify the type.  A file may have multiple .debug_types sections,
25016    or the type may come from a DWO file.  Furthermore, while it's more logical
25017    to use per_cu->section+offset, with Fission the section with the data is in
25018    the DWO file but we don't know that section at the point we need it.
25019    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25020    because we can enter the lookup routine, get_die_type_at_offset, from
25021    outside this file, and thus won't necessarily have PER_CU->cu.
25022    Fortunately, PER_CU is stable for the life of the objfile.  */
25023
25024 struct dwarf2_per_cu_offset_and_type
25025 {
25026   const struct dwarf2_per_cu_data *per_cu;
25027   sect_offset sect_off;
25028   struct type *type;
25029 };
25030
25031 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25032
25033 static hashval_t
25034 per_cu_offset_and_type_hash (const void *item)
25035 {
25036   const struct dwarf2_per_cu_offset_and_type *ofs
25037     = (const struct dwarf2_per_cu_offset_and_type *) item;
25038
25039   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25040 }
25041
25042 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25043
25044 static int
25045 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25046 {
25047   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25048     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25049   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25050     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25051
25052   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25053           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25054 }
25055
25056 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25057    table if necessary.  For convenience, return TYPE.
25058
25059    The DIEs reading must have careful ordering to:
25060     * Not cause infite loops trying to read in DIEs as a prerequisite for
25061       reading current DIE.
25062     * Not trying to dereference contents of still incompletely read in types
25063       while reading in other DIEs.
25064     * Enable referencing still incompletely read in types just by a pointer to
25065       the type without accessing its fields.
25066
25067    Therefore caller should follow these rules:
25068      * Try to fetch any prerequisite types we may need to build this DIE type
25069        before building the type and calling set_die_type.
25070      * After building type call set_die_type for current DIE as soon as
25071        possible before fetching more types to complete the current type.
25072      * Make the type as complete as possible before fetching more types.  */
25073
25074 static struct type *
25075 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25076 {
25077   struct dwarf2_per_objfile *dwarf2_per_objfile
25078     = cu->per_cu->dwarf2_per_objfile;
25079   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25080   struct objfile *objfile = dwarf2_per_objfile->objfile;
25081   struct attribute *attr;
25082   struct dynamic_prop prop;
25083
25084   /* For Ada types, make sure that the gnat-specific data is always
25085      initialized (if not already set).  There are a few types where
25086      we should not be doing so, because the type-specific area is
25087      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25088      where the type-specific area is used to store the floatformat).
25089      But this is not a problem, because the gnat-specific information
25090      is actually not needed for these types.  */
25091   if (need_gnat_info (cu)
25092       && TYPE_CODE (type) != TYPE_CODE_FUNC
25093       && TYPE_CODE (type) != TYPE_CODE_FLT
25094       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25095       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25096       && TYPE_CODE (type) != TYPE_CODE_METHOD
25097       && !HAVE_GNAT_AUX_INFO (type))
25098     INIT_GNAT_SPECIFIC (type);
25099
25100   /* Read DW_AT_allocated and set in type.  */
25101   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25102   if (attr_form_is_block (attr))
25103     {
25104       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25105         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25106     }
25107   else if (attr != NULL)
25108     {
25109       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25110                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25111                  sect_offset_str (die->sect_off));
25112     }
25113
25114   /* Read DW_AT_associated and set in type.  */
25115   attr = dwarf2_attr (die, DW_AT_associated, cu);
25116   if (attr_form_is_block (attr))
25117     {
25118       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25119         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25120     }
25121   else if (attr != NULL)
25122     {
25123       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25124                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25125                  sect_offset_str (die->sect_off));
25126     }
25127
25128   /* Read DW_AT_data_location and set in type.  */
25129   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25130   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25131     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25132
25133   if (dwarf2_per_objfile->die_type_hash == NULL)
25134     {
25135       dwarf2_per_objfile->die_type_hash =
25136         htab_create_alloc_ex (127,
25137                               per_cu_offset_and_type_hash,
25138                               per_cu_offset_and_type_eq,
25139                               NULL,
25140                               &objfile->objfile_obstack,
25141                               hashtab_obstack_allocate,
25142                               dummy_obstack_deallocate);
25143     }
25144
25145   ofs.per_cu = cu->per_cu;
25146   ofs.sect_off = die->sect_off;
25147   ofs.type = type;
25148   slot = (struct dwarf2_per_cu_offset_and_type **)
25149     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25150   if (*slot)
25151     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25152                sect_offset_str (die->sect_off));
25153   *slot = XOBNEW (&objfile->objfile_obstack,
25154                   struct dwarf2_per_cu_offset_and_type);
25155   **slot = ofs;
25156   return type;
25157 }
25158
25159 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25160    or return NULL if the die does not have a saved type.  */
25161
25162 static struct type *
25163 get_die_type_at_offset (sect_offset sect_off,
25164                         struct dwarf2_per_cu_data *per_cu)
25165 {
25166   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25167   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25168
25169   if (dwarf2_per_objfile->die_type_hash == NULL)
25170     return NULL;
25171
25172   ofs.per_cu = per_cu;
25173   ofs.sect_off = sect_off;
25174   slot = ((struct dwarf2_per_cu_offset_and_type *)
25175           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25176   if (slot)
25177     return slot->type;
25178   else
25179     return NULL;
25180 }
25181
25182 /* Look up the type for DIE in CU in die_type_hash,
25183    or return NULL if DIE does not have a saved type.  */
25184
25185 static struct type *
25186 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25187 {
25188   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25189 }
25190
25191 /* Add a dependence relationship from CU to REF_PER_CU.  */
25192
25193 static void
25194 dwarf2_add_dependence (struct dwarf2_cu *cu,
25195                        struct dwarf2_per_cu_data *ref_per_cu)
25196 {
25197   void **slot;
25198
25199   if (cu->dependencies == NULL)
25200     cu->dependencies
25201       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25202                               NULL, &cu->comp_unit_obstack,
25203                               hashtab_obstack_allocate,
25204                               dummy_obstack_deallocate);
25205
25206   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25207   if (*slot == NULL)
25208     *slot = ref_per_cu;
25209 }
25210
25211 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25212    Set the mark field in every compilation unit in the
25213    cache that we must keep because we are keeping CU.  */
25214
25215 static int
25216 dwarf2_mark_helper (void **slot, void *data)
25217 {
25218   struct dwarf2_per_cu_data *per_cu;
25219
25220   per_cu = (struct dwarf2_per_cu_data *) *slot;
25221
25222   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25223      reading of the chain.  As such dependencies remain valid it is not much
25224      useful to track and undo them during QUIT cleanups.  */
25225   if (per_cu->cu == NULL)
25226     return 1;
25227
25228   if (per_cu->cu->mark)
25229     return 1;
25230   per_cu->cu->mark = 1;
25231
25232   if (per_cu->cu->dependencies != NULL)
25233     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25234
25235   return 1;
25236 }
25237
25238 /* Set the mark field in CU and in every other compilation unit in the
25239    cache that we must keep because we are keeping CU.  */
25240
25241 static void
25242 dwarf2_mark (struct dwarf2_cu *cu)
25243 {
25244   if (cu->mark)
25245     return;
25246   cu->mark = 1;
25247   if (cu->dependencies != NULL)
25248     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25249 }
25250
25251 static void
25252 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25253 {
25254   while (per_cu)
25255     {
25256       per_cu->cu->mark = 0;
25257       per_cu = per_cu->cu->read_in_chain;
25258     }
25259 }
25260
25261 /* Trivial hash function for partial_die_info: the hash value of a DIE
25262    is its offset in .debug_info for this objfile.  */
25263
25264 static hashval_t
25265 partial_die_hash (const void *item)
25266 {
25267   const struct partial_die_info *part_die
25268     = (const struct partial_die_info *) item;
25269
25270   return to_underlying (part_die->sect_off);
25271 }
25272
25273 /* Trivial comparison function for partial_die_info structures: two DIEs
25274    are equal if they have the same offset.  */
25275
25276 static int
25277 partial_die_eq (const void *item_lhs, const void *item_rhs)
25278 {
25279   const struct partial_die_info *part_die_lhs
25280     = (const struct partial_die_info *) item_lhs;
25281   const struct partial_die_info *part_die_rhs
25282     = (const struct partial_die_info *) item_rhs;
25283
25284   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25285 }
25286
25287 static struct cmd_list_element *set_dwarf_cmdlist;
25288 static struct cmd_list_element *show_dwarf_cmdlist;
25289
25290 static void
25291 set_dwarf_cmd (const char *args, int from_tty)
25292 {
25293   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25294              gdb_stdout);
25295 }
25296
25297 static void
25298 show_dwarf_cmd (const char *args, int from_tty)
25299 {
25300   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25301 }
25302
25303 int dwarf_always_disassemble;
25304
25305 static void
25306 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25307                                struct cmd_list_element *c, const char *value)
25308 {
25309   fprintf_filtered (file,
25310                     _("Whether to always disassemble "
25311                       "DWARF expressions is %s.\n"),
25312                     value);
25313 }
25314
25315 static void
25316 show_check_physname (struct ui_file *file, int from_tty,
25317                      struct cmd_list_element *c, const char *value)
25318 {
25319   fprintf_filtered (file,
25320                     _("Whether to check \"physname\" is %s.\n"),
25321                     value);
25322 }
25323
25324 void
25325 _initialize_dwarf2_read (void)
25326 {
25327   dwarf2_objfile_data_key
25328     = register_objfile_data_with_cleanup (nullptr, dwarf2_free_objfile);
25329
25330   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25331 Set DWARF specific variables.\n\
25332 Configure DWARF variables such as the cache size"),
25333                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25334                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25335
25336   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25337 Show DWARF specific variables\n\
25338 Show DWARF variables such as the cache size"),
25339                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25340                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25341
25342   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25343                             &dwarf_max_cache_age, _("\
25344 Set the upper bound on the age of cached DWARF compilation units."), _("\
25345 Show the upper bound on the age of cached DWARF compilation units."), _("\
25346 A higher limit means that cached compilation units will be stored\n\
25347 in memory longer, and more total memory will be used.  Zero disables\n\
25348 caching, which can slow down startup."),
25349                             NULL,
25350                             show_dwarf_max_cache_age,
25351                             &set_dwarf_cmdlist,
25352                             &show_dwarf_cmdlist);
25353
25354   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25355                            &dwarf_always_disassemble, _("\
25356 Set whether `info address' always disassembles DWARF expressions."), _("\
25357 Show whether `info address' always disassembles DWARF expressions."), _("\
25358 When enabled, DWARF expressions are always printed in an assembly-like\n\
25359 syntax.  When disabled, expressions will be printed in a more\n\
25360 conversational style, when possible."),
25361                            NULL,
25362                            show_dwarf_always_disassemble,
25363                            &set_dwarf_cmdlist,
25364                            &show_dwarf_cmdlist);
25365
25366   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25367 Set debugging of the DWARF reader."), _("\
25368 Show debugging of the DWARF reader."), _("\
25369 When enabled (non-zero), debugging messages are printed during DWARF\n\
25370 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25371 information.  A value greater than 1 provides more verbose information."),
25372                             NULL,
25373                             NULL,
25374                             &setdebuglist, &showdebuglist);
25375
25376   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25377 Set debugging of the DWARF DIE reader."), _("\
25378 Show debugging of the DWARF DIE reader."), _("\
25379 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25380 The value is the maximum depth to print."),
25381                              NULL,
25382                              NULL,
25383                              &setdebuglist, &showdebuglist);
25384
25385   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25386 Set debugging of the dwarf line reader."), _("\
25387 Show debugging of the dwarf line reader."), _("\
25388 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25389 A value of 1 (one) provides basic information.\n\
25390 A value greater than 1 provides more verbose information."),
25391                              NULL,
25392                              NULL,
25393                              &setdebuglist, &showdebuglist);
25394
25395   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25396 Set cross-checking of \"physname\" code against demangler."), _("\
25397 Show cross-checking of \"physname\" code against demangler."), _("\
25398 When enabled, GDB's internal \"physname\" code is checked against\n\
25399 the demangler."),
25400                            NULL, show_check_physname,
25401                            &setdebuglist, &showdebuglist);
25402
25403   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25404                            no_class, &use_deprecated_index_sections, _("\
25405 Set whether to use deprecated gdb_index sections."), _("\
25406 Show whether to use deprecated gdb_index sections."), _("\
25407 When enabled, deprecated .gdb_index sections are used anyway.\n\
25408 Normally they are ignored either because of a missing feature or\n\
25409 performance issue.\n\
25410 Warning: This option must be enabled before gdb reads the file."),
25411                            NULL,
25412                            NULL,
25413                            &setlist, &showlist);
25414
25415   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25416                                                         &dwarf2_locexpr_funcs);
25417   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25418                                                         &dwarf2_loclist_funcs);
25419
25420   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25421                                         &dwarf2_block_frame_base_locexpr_funcs);
25422   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25423                                         &dwarf2_block_frame_base_loclist_funcs);
25424
25425 #if GDB_SELF_TEST
25426   selftests::register_test ("dw2_expand_symtabs_matching",
25427                             selftests::dw2_expand_symtabs_matching::run_test);
25428 #endif
25429 }