Do not look at file symbols when reading psymtabs
[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   /* Allocate a new partial symbol table structure.  */
7912   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7913   if (filename == NULL)
7914     filename = "";
7915
7916   pst = create_partial_symtab (per_cu, filename);
7917
7918   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7919   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7920
7921   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7922
7923   dwarf2_find_base_address (comp_unit_die, cu);
7924
7925   /* Possibly set the default values of LOWPC and HIGHPC from
7926      `DW_AT_ranges'.  */
7927   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7928                                          &best_highpc, cu, pst);
7929   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7930     /* Store the contiguous range if it is not empty; it can be empty for
7931        CUs with no code.  */
7932     addrmap_set_empty (objfile->psymtabs_addrmap,
7933                        gdbarch_adjust_dwarf2_addr (gdbarch,
7934                                                    best_lowpc + baseaddr),
7935                        gdbarch_adjust_dwarf2_addr (gdbarch,
7936                                                    best_highpc + baseaddr) - 1,
7937                        pst);
7938
7939   /* Check if comp unit has_children.
7940      If so, read the rest of the partial symbols from this comp unit.
7941      If not, there's no more debug_info for this comp unit.  */
7942   if (has_children)
7943     {
7944       struct partial_die_info *first_die;
7945       CORE_ADDR lowpc, highpc;
7946
7947       lowpc = ((CORE_ADDR) -1);
7948       highpc = ((CORE_ADDR) 0);
7949
7950       first_die = load_partial_dies (reader, info_ptr, 1);
7951
7952       scan_partial_symbols (first_die, &lowpc, &highpc,
7953                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7954
7955       /* If we didn't find a lowpc, set it to highpc to avoid
7956          complaints from `maint check'.  */
7957       if (lowpc == ((CORE_ADDR) -1))
7958         lowpc = highpc;
7959
7960       /* If the compilation unit didn't have an explicit address range,
7961          then use the information extracted from its child dies.  */
7962       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7963         {
7964           best_lowpc = lowpc;
7965           best_highpc = highpc;
7966         }
7967     }
7968   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
7969   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
7970
7971   end_psymtab_common (objfile, pst);
7972
7973   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
7974     {
7975       int i;
7976       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7977       struct dwarf2_per_cu_data *iter;
7978
7979       /* Fill in 'dependencies' here; we fill in 'users' in a
7980          post-pass.  */
7981       pst->number_of_dependencies = len;
7982       pst->dependencies =
7983         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7984       for (i = 0;
7985            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7986                         i, iter);
7987            ++i)
7988         pst->dependencies[i] = iter->v.psymtab;
7989
7990       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7991     }
7992
7993   /* Get the list of files included in the current compilation unit,
7994      and build a psymtab for each of them.  */
7995   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7996
7997   if (dwarf_read_debug)
7998     {
7999       struct gdbarch *gdbarch = get_objfile_arch (objfile);
8000
8001       fprintf_unfiltered (gdb_stdlog,
8002                           "Psymtab for %s unit @%s: %s - %s"
8003                           ", %d global, %d static syms\n",
8004                           per_cu->is_debug_types ? "type" : "comp",
8005                           sect_offset_str (per_cu->sect_off),
8006                           paddress (gdbarch, pst->textlow),
8007                           paddress (gdbarch, pst->texthigh),
8008                           pst->n_global_syms, pst->n_static_syms);
8009     }
8010 }
8011
8012 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8013    Process compilation unit THIS_CU for a psymtab.  */
8014
8015 static void
8016 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
8017                            int want_partial_unit,
8018                            enum language pretend_language)
8019 {
8020   /* If this compilation unit was already read in, free the
8021      cached copy in order to read it in again.  This is
8022      necessary because we skipped some symbols when we first
8023      read in the compilation unit (see load_partial_dies).
8024      This problem could be avoided, but the benefit is unclear.  */
8025   if (this_cu->cu != NULL)
8026     free_one_cached_comp_unit (this_cu);
8027
8028   if (this_cu->is_debug_types)
8029     init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8030                              build_type_psymtabs_reader, NULL);
8031   else
8032     {
8033       process_psymtab_comp_unit_data info;
8034       info.want_partial_unit = want_partial_unit;
8035       info.pretend_language = pretend_language;
8036       init_cutu_and_read_dies (this_cu, NULL, 0, 0, false,
8037                                process_psymtab_comp_unit_reader, &info);
8038     }
8039
8040   /* Age out any secondary CUs.  */
8041   age_cached_comp_units (this_cu->dwarf2_per_objfile);
8042 }
8043
8044 /* Reader function for build_type_psymtabs.  */
8045
8046 static void
8047 build_type_psymtabs_reader (const struct die_reader_specs *reader,
8048                             const gdb_byte *info_ptr,
8049                             struct die_info *type_unit_die,
8050                             int has_children,
8051                             void *data)
8052 {
8053   struct dwarf2_per_objfile *dwarf2_per_objfile
8054     = reader->cu->per_cu->dwarf2_per_objfile;
8055   struct objfile *objfile = dwarf2_per_objfile->objfile;
8056   struct dwarf2_cu *cu = reader->cu;
8057   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
8058   struct signatured_type *sig_type;
8059   struct type_unit_group *tu_group;
8060   struct attribute *attr;
8061   struct partial_die_info *first_die;
8062   CORE_ADDR lowpc, highpc;
8063   struct partial_symtab *pst;
8064
8065   gdb_assert (data == NULL);
8066   gdb_assert (per_cu->is_debug_types);
8067   sig_type = (struct signatured_type *) per_cu;
8068
8069   if (! has_children)
8070     return;
8071
8072   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
8073   tu_group = get_type_unit_group (cu, attr);
8074
8075   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
8076
8077   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
8078   pst = create_partial_symtab (per_cu, "");
8079   pst->anonymous = 1;
8080
8081   first_die = load_partial_dies (reader, info_ptr, 1);
8082
8083   lowpc = (CORE_ADDR) -1;
8084   highpc = (CORE_ADDR) 0;
8085   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
8086
8087   end_psymtab_common (objfile, pst);
8088 }
8089
8090 /* Struct used to sort TUs by their abbreviation table offset.  */
8091
8092 struct tu_abbrev_offset
8093 {
8094   tu_abbrev_offset (signatured_type *sig_type_, sect_offset abbrev_offset_)
8095   : sig_type (sig_type_), abbrev_offset (abbrev_offset_)
8096   {}
8097
8098   signatured_type *sig_type;
8099   sect_offset abbrev_offset;
8100 };
8101
8102 /* Helper routine for build_type_psymtabs_1, passed to std::sort.  */
8103
8104 static bool
8105 sort_tu_by_abbrev_offset (const struct tu_abbrev_offset &a,
8106                           const struct tu_abbrev_offset &b)
8107 {
8108   return a.abbrev_offset < b.abbrev_offset;
8109 }
8110
8111 /* Efficiently read all the type units.
8112    This does the bulk of the work for build_type_psymtabs.
8113
8114    The efficiency is because we sort TUs by the abbrev table they use and
8115    only read each abbrev table once.  In one program there are 200K TUs
8116    sharing 8K abbrev tables.
8117
8118    The main purpose of this function is to support building the
8119    dwarf2_per_objfile->type_unit_groups table.
8120    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
8121    can collapse the search space by grouping them by stmt_list.
8122    The savings can be significant, in the same program from above the 200K TUs
8123    share 8K stmt_list tables.
8124
8125    FUNC is expected to call get_type_unit_group, which will create the
8126    struct type_unit_group if necessary and add it to
8127    dwarf2_per_objfile->type_unit_groups.  */
8128
8129 static void
8130 build_type_psymtabs_1 (struct dwarf2_per_objfile *dwarf2_per_objfile)
8131 {
8132   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8133   abbrev_table_up abbrev_table;
8134   sect_offset abbrev_offset;
8135
8136   /* It's up to the caller to not call us multiple times.  */
8137   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
8138
8139   if (dwarf2_per_objfile->all_type_units.empty ())
8140     return;
8141
8142   /* TUs typically share abbrev tables, and there can be way more TUs than
8143      abbrev tables.  Sort by abbrev table to reduce the number of times we
8144      read each abbrev table in.
8145      Alternatives are to punt or to maintain a cache of abbrev tables.
8146      This is simpler and efficient enough for now.
8147
8148      Later we group TUs by their DW_AT_stmt_list value (as this defines the
8149      symtab to use).  Typically TUs with the same abbrev offset have the same
8150      stmt_list value too so in practice this should work well.
8151
8152      The basic algorithm here is:
8153
8154       sort TUs by abbrev table
8155       for each TU with same abbrev table:
8156         read abbrev table if first user
8157         read TU top level DIE
8158           [IWBN if DWO skeletons had DW_AT_stmt_list]
8159         call FUNC  */
8160
8161   if (dwarf_read_debug)
8162     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
8163
8164   /* Sort in a separate table to maintain the order of all_type_units
8165      for .gdb_index: TU indices directly index all_type_units.  */
8166   std::vector<tu_abbrev_offset> sorted_by_abbrev;
8167   sorted_by_abbrev.reserve (dwarf2_per_objfile->all_type_units.size ());
8168
8169   for (signatured_type *sig_type : dwarf2_per_objfile->all_type_units)
8170     sorted_by_abbrev.emplace_back
8171       (sig_type, read_abbrev_offset (dwarf2_per_objfile,
8172                                      sig_type->per_cu.section,
8173                                      sig_type->per_cu.sect_off));
8174
8175   std::sort (sorted_by_abbrev.begin (), sorted_by_abbrev.end (),
8176              sort_tu_by_abbrev_offset);
8177
8178   abbrev_offset = (sect_offset) ~(unsigned) 0;
8179
8180   for (const tu_abbrev_offset &tu : sorted_by_abbrev)
8181     {
8182       /* Switch to the next abbrev table if necessary.  */
8183       if (abbrev_table == NULL
8184           || tu.abbrev_offset != abbrev_offset)
8185         {
8186           abbrev_offset = tu.abbrev_offset;
8187           abbrev_table =
8188             abbrev_table_read_table (dwarf2_per_objfile,
8189                                      &dwarf2_per_objfile->abbrev,
8190                                      abbrev_offset);
8191           ++tu_stats->nr_uniq_abbrev_tables;
8192         }
8193
8194       init_cutu_and_read_dies (&tu.sig_type->per_cu, abbrev_table.get (),
8195                                0, 0, false, build_type_psymtabs_reader, NULL);
8196     }
8197 }
8198
8199 /* Print collected type unit statistics.  */
8200
8201 static void
8202 print_tu_stats (struct dwarf2_per_objfile *dwarf2_per_objfile)
8203 {
8204   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
8205
8206   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
8207   fprintf_unfiltered (gdb_stdlog, "  %zu TUs\n",
8208                       dwarf2_per_objfile->all_type_units.size ());
8209   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
8210                       tu_stats->nr_uniq_abbrev_tables);
8211   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
8212                       tu_stats->nr_symtabs);
8213   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
8214                       tu_stats->nr_symtab_sharers);
8215   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
8216                       tu_stats->nr_stmt_less_type_units);
8217   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
8218                       tu_stats->nr_all_type_units_reallocs);
8219 }
8220
8221 /* Traversal function for build_type_psymtabs.  */
8222
8223 static int
8224 build_type_psymtab_dependencies (void **slot, void *info)
8225 {
8226   struct dwarf2_per_objfile *dwarf2_per_objfile
8227     = (struct dwarf2_per_objfile *) info;
8228   struct objfile *objfile = dwarf2_per_objfile->objfile;
8229   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
8230   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
8231   struct partial_symtab *pst = per_cu->v.psymtab;
8232   int len = VEC_length (sig_type_ptr, tu_group->tus);
8233   struct signatured_type *iter;
8234   int i;
8235
8236   gdb_assert (len > 0);
8237   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
8238
8239   pst->number_of_dependencies = len;
8240   pst->dependencies =
8241     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
8242   for (i = 0;
8243        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
8244        ++i)
8245     {
8246       gdb_assert (iter->per_cu.is_debug_types);
8247       pst->dependencies[i] = iter->per_cu.v.psymtab;
8248       iter->type_unit_group = tu_group;
8249     }
8250
8251   VEC_free (sig_type_ptr, tu_group->tus);
8252
8253   return 1;
8254 }
8255
8256 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
8257    Build partial symbol tables for the .debug_types comp-units.  */
8258
8259 static void
8260 build_type_psymtabs (struct dwarf2_per_objfile *dwarf2_per_objfile)
8261 {
8262   if (! create_all_type_units (dwarf2_per_objfile))
8263     return;
8264
8265   build_type_psymtabs_1 (dwarf2_per_objfile);
8266 }
8267
8268 /* Traversal function for process_skeletonless_type_unit.
8269    Read a TU in a DWO file and build partial symbols for it.  */
8270
8271 static int
8272 process_skeletonless_type_unit (void **slot, void *info)
8273 {
8274   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
8275   struct dwarf2_per_objfile *dwarf2_per_objfile
8276     = (struct dwarf2_per_objfile *) info;
8277   struct signatured_type find_entry, *entry;
8278
8279   /* If this TU doesn't exist in the global table, add it and read it in.  */
8280
8281   if (dwarf2_per_objfile->signatured_types == NULL)
8282     {
8283       dwarf2_per_objfile->signatured_types
8284         = allocate_signatured_type_table (dwarf2_per_objfile->objfile);
8285     }
8286
8287   find_entry.signature = dwo_unit->signature;
8288   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
8289                          INSERT);
8290   /* If we've already seen this type there's nothing to do.  What's happening
8291      is we're doing our own version of comdat-folding here.  */
8292   if (*slot != NULL)
8293     return 1;
8294
8295   /* This does the job that create_all_type_units would have done for
8296      this TU.  */
8297   entry = add_type_unit (dwarf2_per_objfile, dwo_unit->signature, slot);
8298   fill_in_sig_entry_from_dwo_entry (dwarf2_per_objfile, entry, dwo_unit);
8299   *slot = entry;
8300
8301   /* This does the job that build_type_psymtabs_1 would have done.  */
8302   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0, false,
8303                            build_type_psymtabs_reader, NULL);
8304
8305   return 1;
8306 }
8307
8308 /* Traversal function for process_skeletonless_type_units.  */
8309
8310 static int
8311 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
8312 {
8313   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
8314
8315   if (dwo_file->tus != NULL)
8316     {
8317       htab_traverse_noresize (dwo_file->tus,
8318                               process_skeletonless_type_unit, info);
8319     }
8320
8321   return 1;
8322 }
8323
8324 /* Scan all TUs of DWO files, verifying we've processed them.
8325    This is needed in case a TU was emitted without its skeleton.
8326    Note: This can't be done until we know what all the DWO files are.  */
8327
8328 static void
8329 process_skeletonless_type_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8330 {
8331   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
8332   if (get_dwp_file (dwarf2_per_objfile) == NULL
8333       && dwarf2_per_objfile->dwo_files != NULL)
8334     {
8335       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
8336                               process_dwo_file_for_skeletonless_type_units,
8337                               dwarf2_per_objfile);
8338     }
8339 }
8340
8341 /* Compute the 'user' field for each psymtab in DWARF2_PER_OBJFILE.  */
8342
8343 static void
8344 set_partial_user (struct dwarf2_per_objfile *dwarf2_per_objfile)
8345 {
8346   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8347     {
8348       struct partial_symtab *pst = per_cu->v.psymtab;
8349
8350       if (pst == NULL)
8351         continue;
8352
8353       for (int j = 0; j < pst->number_of_dependencies; ++j)
8354         {
8355           /* Set the 'user' field only if it is not already set.  */
8356           if (pst->dependencies[j]->user == NULL)
8357             pst->dependencies[j]->user = pst;
8358         }
8359     }
8360 }
8361
8362 /* Build the partial symbol table by doing a quick pass through the
8363    .debug_info and .debug_abbrev sections.  */
8364
8365 static void
8366 dwarf2_build_psymtabs_hard (struct dwarf2_per_objfile *dwarf2_per_objfile)
8367 {
8368   struct objfile *objfile = dwarf2_per_objfile->objfile;
8369
8370   if (dwarf_read_debug)
8371     {
8372       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
8373                           objfile_name (objfile));
8374     }
8375
8376   dwarf2_per_objfile->reading_partial_symbols = 1;
8377
8378   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
8379
8380   /* Any cached compilation units will be linked by the per-objfile
8381      read_in_chain.  Make sure to free them when we're done.  */
8382   free_cached_comp_units freer (dwarf2_per_objfile);
8383
8384   build_type_psymtabs (dwarf2_per_objfile);
8385
8386   create_all_comp_units (dwarf2_per_objfile);
8387
8388   /* Create a temporary address map on a temporary obstack.  We later
8389      copy this to the final obstack.  */
8390   auto_obstack temp_obstack;
8391
8392   scoped_restore save_psymtabs_addrmap
8393     = make_scoped_restore (&objfile->psymtabs_addrmap,
8394                            addrmap_create_mutable (&temp_obstack));
8395
8396   for (dwarf2_per_cu_data *per_cu : dwarf2_per_objfile->all_comp_units)
8397     process_psymtab_comp_unit (per_cu, 0, language_minimal);
8398
8399   /* This has to wait until we read the CUs, we need the list of DWOs.  */
8400   process_skeletonless_type_units (dwarf2_per_objfile);
8401
8402   /* Now that all TUs have been processed we can fill in the dependencies.  */
8403   if (dwarf2_per_objfile->type_unit_groups != NULL)
8404     {
8405       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
8406                               build_type_psymtab_dependencies, dwarf2_per_objfile);
8407     }
8408
8409   if (dwarf_read_debug)
8410     print_tu_stats (dwarf2_per_objfile);
8411
8412   set_partial_user (dwarf2_per_objfile);
8413
8414   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
8415                                                     &objfile->objfile_obstack);
8416   /* At this point we want to keep the address map.  */
8417   save_psymtabs_addrmap.release ();
8418
8419   if (dwarf_read_debug)
8420     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
8421                         objfile_name (objfile));
8422 }
8423
8424 /* die_reader_func for load_partial_comp_unit.  */
8425
8426 static void
8427 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
8428                                const gdb_byte *info_ptr,
8429                                struct die_info *comp_unit_die,
8430                                int has_children,
8431                                void *data)
8432 {
8433   struct dwarf2_cu *cu = reader->cu;
8434
8435   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
8436
8437   /* Check if comp unit has_children.
8438      If so, read the rest of the partial symbols from this comp unit.
8439      If not, there's no more debug_info for this comp unit.  */
8440   if (has_children)
8441     load_partial_dies (reader, info_ptr, 0);
8442 }
8443
8444 /* Load the partial DIEs for a secondary CU into memory.
8445    This is also used when rereading a primary CU with load_all_dies.  */
8446
8447 static void
8448 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
8449 {
8450   init_cutu_and_read_dies (this_cu, NULL, 1, 1, false,
8451                            load_partial_comp_unit_reader, NULL);
8452 }
8453
8454 static void
8455 read_comp_units_from_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
8456                               struct dwarf2_section_info *section,
8457                               struct dwarf2_section_info *abbrev_section,
8458                               unsigned int is_dwz)
8459 {
8460   const gdb_byte *info_ptr;
8461   struct objfile *objfile = dwarf2_per_objfile->objfile;
8462
8463   if (dwarf_read_debug)
8464     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
8465                         get_section_name (section),
8466                         get_section_file_name (section));
8467
8468   dwarf2_read_section (objfile, section);
8469
8470   info_ptr = section->buffer;
8471
8472   while (info_ptr < section->buffer + section->size)
8473     {
8474       struct dwarf2_per_cu_data *this_cu;
8475
8476       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
8477
8478       comp_unit_head cu_header;
8479       read_and_check_comp_unit_head (dwarf2_per_objfile, &cu_header, section,
8480                                      abbrev_section, info_ptr,
8481                                      rcuh_kind::COMPILE);
8482
8483       /* Save the compilation unit for later lookup.  */
8484       if (cu_header.unit_type != DW_UT_type)
8485         {
8486           this_cu = XOBNEW (&objfile->objfile_obstack,
8487                             struct dwarf2_per_cu_data);
8488           memset (this_cu, 0, sizeof (*this_cu));
8489         }
8490       else
8491         {
8492           auto sig_type = XOBNEW (&objfile->objfile_obstack,
8493                                   struct signatured_type);
8494           memset (sig_type, 0, sizeof (*sig_type));
8495           sig_type->signature = cu_header.signature;
8496           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
8497           this_cu = &sig_type->per_cu;
8498         }
8499       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
8500       this_cu->sect_off = sect_off;
8501       this_cu->length = cu_header.length + cu_header.initial_length_size;
8502       this_cu->is_dwz = is_dwz;
8503       this_cu->dwarf2_per_objfile = dwarf2_per_objfile;
8504       this_cu->section = section;
8505
8506       dwarf2_per_objfile->all_comp_units.push_back (this_cu);
8507
8508       info_ptr = info_ptr + this_cu->length;
8509     }
8510 }
8511
8512 /* Create a list of all compilation units in OBJFILE.
8513    This is only done for -readnow and building partial symtabs.  */
8514
8515 static void
8516 create_all_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
8517 {
8518   gdb_assert (dwarf2_per_objfile->all_comp_units.empty ());
8519   read_comp_units_from_section (dwarf2_per_objfile, &dwarf2_per_objfile->info,
8520                                 &dwarf2_per_objfile->abbrev, 0);
8521
8522   dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
8523   if (dwz != NULL)
8524     read_comp_units_from_section (dwarf2_per_objfile, &dwz->info, &dwz->abbrev,
8525                                   1);
8526 }
8527
8528 /* Process all loaded DIEs for compilation unit CU, starting at
8529    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
8530    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
8531    DW_AT_ranges).  See the comments of add_partial_subprogram on how
8532    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
8533
8534 static void
8535 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
8536                       CORE_ADDR *highpc, int set_addrmap,
8537                       struct dwarf2_cu *cu)
8538 {
8539   struct partial_die_info *pdi;
8540
8541   /* Now, march along the PDI's, descending into ones which have
8542      interesting children but skipping the children of the other ones,
8543      until we reach the end of the compilation unit.  */
8544
8545   pdi = first_die;
8546
8547   while (pdi != NULL)
8548     {
8549       pdi->fixup (cu);
8550
8551       /* Anonymous namespaces or modules have no name but have interesting
8552          children, so we need to look at them.  Ditto for anonymous
8553          enums.  */
8554
8555       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
8556           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
8557           || pdi->tag == DW_TAG_imported_unit
8558           || pdi->tag == DW_TAG_inlined_subroutine)
8559         {
8560           switch (pdi->tag)
8561             {
8562             case DW_TAG_subprogram:
8563             case DW_TAG_inlined_subroutine:
8564               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8565               break;
8566             case DW_TAG_constant:
8567             case DW_TAG_variable:
8568             case DW_TAG_typedef:
8569             case DW_TAG_union_type:
8570               if (!pdi->is_declaration)
8571                 {
8572                   add_partial_symbol (pdi, cu);
8573                 }
8574               break;
8575             case DW_TAG_class_type:
8576             case DW_TAG_interface_type:
8577             case DW_TAG_structure_type:
8578               if (!pdi->is_declaration)
8579                 {
8580                   add_partial_symbol (pdi, cu);
8581                 }
8582               if ((cu->language == language_rust
8583                    || cu->language == language_cplus) && pdi->has_children)
8584                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
8585                                       set_addrmap, cu);
8586               break;
8587             case DW_TAG_enumeration_type:
8588               if (!pdi->is_declaration)
8589                 add_partial_enumeration (pdi, cu);
8590               break;
8591             case DW_TAG_base_type:
8592             case DW_TAG_subrange_type:
8593               /* File scope base type definitions are added to the partial
8594                  symbol table.  */
8595               add_partial_symbol (pdi, cu);
8596               break;
8597             case DW_TAG_namespace:
8598               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
8599               break;
8600             case DW_TAG_module:
8601               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
8602               break;
8603             case DW_TAG_imported_unit:
8604               {
8605                 struct dwarf2_per_cu_data *per_cu;
8606
8607                 /* For now we don't handle imported units in type units.  */
8608                 if (cu->per_cu->is_debug_types)
8609                   {
8610                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
8611                              " supported in type units [in module %s]"),
8612                            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
8613                   }
8614
8615                 per_cu = dwarf2_find_containing_comp_unit
8616                            (pdi->d.sect_off, pdi->is_dwz,
8617                             cu->per_cu->dwarf2_per_objfile);
8618
8619                 /* Go read the partial unit, if needed.  */
8620                 if (per_cu->v.psymtab == NULL)
8621                   process_psymtab_comp_unit (per_cu, 1, cu->language);
8622
8623                 VEC_safe_push (dwarf2_per_cu_ptr,
8624                                cu->per_cu->imported_symtabs, per_cu);
8625               }
8626               break;
8627             case DW_TAG_imported_declaration:
8628               add_partial_symbol (pdi, cu);
8629               break;
8630             default:
8631               break;
8632             }
8633         }
8634
8635       /* If the die has a sibling, skip to the sibling.  */
8636
8637       pdi = pdi->die_sibling;
8638     }
8639 }
8640
8641 /* Functions used to compute the fully scoped name of a partial DIE.
8642
8643    Normally, this is simple.  For C++, the parent DIE's fully scoped
8644    name is concatenated with "::" and the partial DIE's name.
8645    Enumerators are an exception; they use the scope of their parent
8646    enumeration type, i.e. the name of the enumeration type is not
8647    prepended to the enumerator.
8648
8649    There are two complexities.  One is DW_AT_specification; in this
8650    case "parent" means the parent of the target of the specification,
8651    instead of the direct parent of the DIE.  The other is compilers
8652    which do not emit DW_TAG_namespace; in this case we try to guess
8653    the fully qualified name of structure types from their members'
8654    linkage names.  This must be done using the DIE's children rather
8655    than the children of any DW_AT_specification target.  We only need
8656    to do this for structures at the top level, i.e. if the target of
8657    any DW_AT_specification (if any; otherwise the DIE itself) does not
8658    have a parent.  */
8659
8660 /* Compute the scope prefix associated with PDI's parent, in
8661    compilation unit CU.  The result will be allocated on CU's
8662    comp_unit_obstack, or a copy of the already allocated PDI->NAME
8663    field.  NULL is returned if no prefix is necessary.  */
8664 static const char *
8665 partial_die_parent_scope (struct partial_die_info *pdi,
8666                           struct dwarf2_cu *cu)
8667 {
8668   const char *grandparent_scope;
8669   struct partial_die_info *parent, *real_pdi;
8670
8671   /* We need to look at our parent DIE; if we have a DW_AT_specification,
8672      then this means the parent of the specification DIE.  */
8673
8674   real_pdi = pdi;
8675   while (real_pdi->has_specification)
8676     real_pdi = find_partial_die (real_pdi->spec_offset,
8677                                  real_pdi->spec_is_dwz, cu);
8678
8679   parent = real_pdi->die_parent;
8680   if (parent == NULL)
8681     return NULL;
8682
8683   if (parent->scope_set)
8684     return parent->scope;
8685
8686   parent->fixup (cu);
8687
8688   grandparent_scope = partial_die_parent_scope (parent, cu);
8689
8690   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
8691      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
8692      Work around this problem here.  */
8693   if (cu->language == language_cplus
8694       && parent->tag == DW_TAG_namespace
8695       && strcmp (parent->name, "::") == 0
8696       && grandparent_scope == NULL)
8697     {
8698       parent->scope = NULL;
8699       parent->scope_set = 1;
8700       return NULL;
8701     }
8702
8703   if (pdi->tag == DW_TAG_enumerator)
8704     /* Enumerators should not get the name of the enumeration as a prefix.  */
8705     parent->scope = grandparent_scope;
8706   else if (parent->tag == DW_TAG_namespace
8707       || parent->tag == DW_TAG_module
8708       || parent->tag == DW_TAG_structure_type
8709       || parent->tag == DW_TAG_class_type
8710       || parent->tag == DW_TAG_interface_type
8711       || parent->tag == DW_TAG_union_type
8712       || parent->tag == DW_TAG_enumeration_type)
8713     {
8714       if (grandparent_scope == NULL)
8715         parent->scope = parent->name;
8716       else
8717         parent->scope = typename_concat (&cu->comp_unit_obstack,
8718                                          grandparent_scope,
8719                                          parent->name, 0, cu);
8720     }
8721   else
8722     {
8723       /* FIXME drow/2004-04-01: What should we be doing with
8724          function-local names?  For partial symbols, we should probably be
8725          ignoring them.  */
8726       complaint (_("unhandled containing DIE tag %d for DIE at %s"),
8727                  parent->tag, sect_offset_str (pdi->sect_off));
8728       parent->scope = grandparent_scope;
8729     }
8730
8731   parent->scope_set = 1;
8732   return parent->scope;
8733 }
8734
8735 /* Return the fully scoped name associated with PDI, from compilation unit
8736    CU.  The result will be allocated with malloc.  */
8737
8738 static char *
8739 partial_die_full_name (struct partial_die_info *pdi,
8740                        struct dwarf2_cu *cu)
8741 {
8742   const char *parent_scope;
8743
8744   /* If this is a template instantiation, we can not work out the
8745      template arguments from partial DIEs.  So, unfortunately, we have
8746      to go through the full DIEs.  At least any work we do building
8747      types here will be reused if full symbols are loaded later.  */
8748   if (pdi->has_template_arguments)
8749     {
8750       pdi->fixup (cu);
8751
8752       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8753         {
8754           struct die_info *die;
8755           struct attribute attr;
8756           struct dwarf2_cu *ref_cu = cu;
8757
8758           /* DW_FORM_ref_addr is using section offset.  */
8759           attr.name = (enum dwarf_attribute) 0;
8760           attr.form = DW_FORM_ref_addr;
8761           attr.u.unsnd = to_underlying (pdi->sect_off);
8762           die = follow_die_ref (NULL, &attr, &ref_cu);
8763
8764           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8765         }
8766     }
8767
8768   parent_scope = partial_die_parent_scope (pdi, cu);
8769   if (parent_scope == NULL)
8770     return NULL;
8771   else
8772     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8773 }
8774
8775 static void
8776 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8777 {
8778   struct dwarf2_per_objfile *dwarf2_per_objfile
8779     = cu->per_cu->dwarf2_per_objfile;
8780   struct objfile *objfile = dwarf2_per_objfile->objfile;
8781   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8782   CORE_ADDR addr = 0;
8783   const char *actual_name = NULL;
8784   CORE_ADDR baseaddr;
8785   char *built_actual_name;
8786
8787   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8788
8789   built_actual_name = partial_die_full_name (pdi, cu);
8790   if (built_actual_name != NULL)
8791     actual_name = built_actual_name;
8792
8793   if (actual_name == NULL)
8794     actual_name = pdi->name;
8795
8796   switch (pdi->tag)
8797     {
8798     case DW_TAG_inlined_subroutine:
8799     case DW_TAG_subprogram:
8800       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
8801       if (pdi->is_external || cu->language == language_ada)
8802         {
8803           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8804              of the global scope.  But in Ada, we want to be able to access
8805              nested procedures globally.  So all Ada subprograms are stored
8806              in the global scope.  */
8807           add_psymbol_to_list (actual_name, strlen (actual_name),
8808                                built_actual_name != NULL,
8809                                VAR_DOMAIN, LOC_BLOCK,
8810                                &objfile->global_psymbols,
8811                                addr, cu->language, objfile);
8812         }
8813       else
8814         {
8815           add_psymbol_to_list (actual_name, strlen (actual_name),
8816                                built_actual_name != NULL,
8817                                VAR_DOMAIN, LOC_BLOCK,
8818                                &objfile->static_psymbols,
8819                                addr, cu->language, objfile);
8820         }
8821
8822       if (pdi->main_subprogram && actual_name != NULL)
8823         set_objfile_main_name (objfile, actual_name, cu->language);
8824       break;
8825     case DW_TAG_constant:
8826       {
8827         std::vector<partial_symbol *> *list;
8828
8829         if (pdi->is_external)
8830           list = &objfile->global_psymbols;
8831         else
8832           list = &objfile->static_psymbols;
8833         add_psymbol_to_list (actual_name, strlen (actual_name),
8834                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8835                              list, 0, cu->language, objfile);
8836       }
8837       break;
8838     case DW_TAG_variable:
8839       if (pdi->d.locdesc)
8840         addr = decode_locdesc (pdi->d.locdesc, cu);
8841
8842       if (pdi->d.locdesc
8843           && addr == 0
8844           && !dwarf2_per_objfile->has_section_at_zero)
8845         {
8846           /* A global or static variable may also have been stripped
8847              out by the linker if unused, in which case its address
8848              will be nullified; do not add such variables into partial
8849              symbol table then.  */
8850         }
8851       else if (pdi->is_external)
8852         {
8853           /* Global Variable.
8854              Don't enter into the minimal symbol tables as there is
8855              a minimal symbol table entry from the ELF symbols already.
8856              Enter into partial symbol table if it has a location
8857              descriptor or a type.
8858              If the location descriptor is missing, new_symbol will create
8859              a LOC_UNRESOLVED symbol, the address of the variable will then
8860              be determined from the minimal symbol table whenever the variable
8861              is referenced.
8862              The address for the partial symbol table entry is not
8863              used by GDB, but it comes in handy for debugging partial symbol
8864              table building.  */
8865
8866           if (pdi->d.locdesc || pdi->has_type)
8867             add_psymbol_to_list (actual_name, strlen (actual_name),
8868                                  built_actual_name != NULL,
8869                                  VAR_DOMAIN, LOC_STATIC,
8870                                  &objfile->global_psymbols,
8871                                  addr + baseaddr,
8872                                  cu->language, objfile);
8873         }
8874       else
8875         {
8876           int has_loc = pdi->d.locdesc != NULL;
8877
8878           /* Static Variable.  Skip symbols whose value we cannot know (those
8879              without location descriptors or constant values).  */
8880           if (!has_loc && !pdi->has_const_value)
8881             {
8882               xfree (built_actual_name);
8883               return;
8884             }
8885
8886           add_psymbol_to_list (actual_name, strlen (actual_name),
8887                                built_actual_name != NULL,
8888                                VAR_DOMAIN, LOC_STATIC,
8889                                &objfile->static_psymbols,
8890                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
8891                                cu->language, objfile);
8892         }
8893       break;
8894     case DW_TAG_typedef:
8895     case DW_TAG_base_type:
8896     case DW_TAG_subrange_type:
8897       add_psymbol_to_list (actual_name, strlen (actual_name),
8898                            built_actual_name != NULL,
8899                            VAR_DOMAIN, LOC_TYPEDEF,
8900                            &objfile->static_psymbols,
8901                            0, cu->language, objfile);
8902       break;
8903     case DW_TAG_imported_declaration:
8904     case DW_TAG_namespace:
8905       add_psymbol_to_list (actual_name, strlen (actual_name),
8906                            built_actual_name != NULL,
8907                            VAR_DOMAIN, LOC_TYPEDEF,
8908                            &objfile->global_psymbols,
8909                            0, cu->language, objfile);
8910       break;
8911     case DW_TAG_module:
8912       add_psymbol_to_list (actual_name, strlen (actual_name),
8913                            built_actual_name != NULL,
8914                            MODULE_DOMAIN, LOC_TYPEDEF,
8915                            &objfile->global_psymbols,
8916                            0, cu->language, objfile);
8917       break;
8918     case DW_TAG_class_type:
8919     case DW_TAG_interface_type:
8920     case DW_TAG_structure_type:
8921     case DW_TAG_union_type:
8922     case DW_TAG_enumeration_type:
8923       /* Skip external references.  The DWARF standard says in the section
8924          about "Structure, Union, and Class Type Entries": "An incomplete
8925          structure, union or class type is represented by a structure,
8926          union or class entry that does not have a byte size attribute
8927          and that has a DW_AT_declaration attribute."  */
8928       if (!pdi->has_byte_size && pdi->is_declaration)
8929         {
8930           xfree (built_actual_name);
8931           return;
8932         }
8933
8934       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8935          static vs. global.  */
8936       add_psymbol_to_list (actual_name, strlen (actual_name),
8937                            built_actual_name != NULL,
8938                            STRUCT_DOMAIN, LOC_TYPEDEF,
8939                            cu->language == language_cplus
8940                            ? &objfile->global_psymbols
8941                            : &objfile->static_psymbols,
8942                            0, cu->language, objfile);
8943
8944       break;
8945     case DW_TAG_enumerator:
8946       add_psymbol_to_list (actual_name, strlen (actual_name),
8947                            built_actual_name != NULL,
8948                            VAR_DOMAIN, LOC_CONST,
8949                            cu->language == language_cplus
8950                            ? &objfile->global_psymbols
8951                            : &objfile->static_psymbols,
8952                            0, cu->language, objfile);
8953       break;
8954     default:
8955       break;
8956     }
8957
8958   xfree (built_actual_name);
8959 }
8960
8961 /* Read a partial die corresponding to a namespace; also, add a symbol
8962    corresponding to that namespace to the symbol table.  NAMESPACE is
8963    the name of the enclosing namespace.  */
8964
8965 static void
8966 add_partial_namespace (struct partial_die_info *pdi,
8967                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8968                        int set_addrmap, struct dwarf2_cu *cu)
8969 {
8970   /* Add a symbol for the namespace.  */
8971
8972   add_partial_symbol (pdi, cu);
8973
8974   /* Now scan partial symbols in that namespace.  */
8975
8976   if (pdi->has_children)
8977     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8978 }
8979
8980 /* Read a partial die corresponding to a Fortran module.  */
8981
8982 static void
8983 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8984                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8985 {
8986   /* Add a symbol for the namespace.  */
8987
8988   add_partial_symbol (pdi, cu);
8989
8990   /* Now scan partial symbols in that module.  */
8991
8992   if (pdi->has_children)
8993     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8994 }
8995
8996 /* Read a partial die corresponding to a subprogram or an inlined
8997    subprogram and create a partial symbol for that subprogram.
8998    When the CU language allows it, this routine also defines a partial
8999    symbol for each nested subprogram that this subprogram contains.
9000    If SET_ADDRMAP is true, record the covered ranges in the addrmap.
9001    Set *LOWPC and *HIGHPC to the lowest and highest PC values found in PDI.
9002
9003    PDI may also be a lexical block, in which case we simply search
9004    recursively for subprograms defined inside that lexical block.
9005    Again, this is only performed when the CU language allows this
9006    type of definitions.  */
9007
9008 static void
9009 add_partial_subprogram (struct partial_die_info *pdi,
9010                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
9011                         int set_addrmap, struct dwarf2_cu *cu)
9012 {
9013   if (pdi->tag == DW_TAG_subprogram || pdi->tag == DW_TAG_inlined_subroutine)
9014     {
9015       if (pdi->has_pc_info)
9016         {
9017           if (pdi->lowpc < *lowpc)
9018             *lowpc = pdi->lowpc;
9019           if (pdi->highpc > *highpc)
9020             *highpc = pdi->highpc;
9021           if (set_addrmap)
9022             {
9023               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9024               struct gdbarch *gdbarch = get_objfile_arch (objfile);
9025               CORE_ADDR baseaddr;
9026               CORE_ADDR highpc;
9027               CORE_ADDR lowpc;
9028
9029               baseaddr = ANOFFSET (objfile->section_offsets,
9030                                    SECT_OFF_TEXT (objfile));
9031               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9032                                                   pdi->lowpc + baseaddr);
9033               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
9034                                                    pdi->highpc + baseaddr);
9035               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
9036                                  cu->per_cu->v.psymtab);
9037             }
9038         }
9039
9040       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
9041         {
9042           if (!pdi->is_declaration)
9043             /* Ignore subprogram DIEs that do not have a name, they are
9044                illegal.  Do not emit a complaint at this point, we will
9045                do so when we convert this psymtab into a symtab.  */
9046             if (pdi->name)
9047               add_partial_symbol (pdi, cu);
9048         }
9049     }
9050
9051   if (! pdi->has_children)
9052     return;
9053
9054   if (cu->language == language_ada)
9055     {
9056       pdi = pdi->die_child;
9057       while (pdi != NULL)
9058         {
9059           pdi->fixup (cu);
9060           if (pdi->tag == DW_TAG_subprogram
9061               || pdi->tag == DW_TAG_inlined_subroutine
9062               || pdi->tag == DW_TAG_lexical_block)
9063             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
9064           pdi = pdi->die_sibling;
9065         }
9066     }
9067 }
9068
9069 /* Read a partial die corresponding to an enumeration type.  */
9070
9071 static void
9072 add_partial_enumeration (struct partial_die_info *enum_pdi,
9073                          struct dwarf2_cu *cu)
9074 {
9075   struct partial_die_info *pdi;
9076
9077   if (enum_pdi->name != NULL)
9078     add_partial_symbol (enum_pdi, cu);
9079
9080   pdi = enum_pdi->die_child;
9081   while (pdi)
9082     {
9083       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
9084         complaint (_("malformed enumerator DIE ignored"));
9085       else
9086         add_partial_symbol (pdi, cu);
9087       pdi = pdi->die_sibling;
9088     }
9089 }
9090
9091 /* Return the initial uleb128 in the die at INFO_PTR.  */
9092
9093 static unsigned int
9094 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
9095 {
9096   unsigned int bytes_read;
9097
9098   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9099 }
9100
9101 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit
9102    READER::CU.  Use READER::ABBREV_TABLE to lookup any abbreviation.
9103
9104    Return the corresponding abbrev, or NULL if the number is zero (indicating
9105    an empty DIE).  In either case *BYTES_READ will be set to the length of
9106    the initial number.  */
9107
9108 static struct abbrev_info *
9109 peek_die_abbrev (const die_reader_specs &reader,
9110                  const gdb_byte *info_ptr, unsigned int *bytes_read)
9111 {
9112   dwarf2_cu *cu = reader.cu;
9113   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
9114   unsigned int abbrev_number
9115     = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
9116
9117   if (abbrev_number == 0)
9118     return NULL;
9119
9120   abbrev_info *abbrev = reader.abbrev_table->lookup_abbrev (abbrev_number);
9121   if (!abbrev)
9122     {
9123       error (_("Dwarf Error: Could not find abbrev number %d in %s"
9124                " at offset %s [in module %s]"),
9125              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
9126              sect_offset_str (cu->header.sect_off), bfd_get_filename (abfd));
9127     }
9128
9129   return abbrev;
9130 }
9131
9132 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9133    Returns a pointer to the end of a series of DIEs, terminated by an empty
9134    DIE.  Any children of the skipped DIEs will also be skipped.  */
9135
9136 static const gdb_byte *
9137 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
9138 {
9139   while (1)
9140     {
9141       unsigned int bytes_read;
9142       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
9143
9144       if (abbrev == NULL)
9145         return info_ptr + bytes_read;
9146       else
9147         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
9148     }
9149 }
9150
9151 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
9152    INFO_PTR should point just after the initial uleb128 of a DIE, and the
9153    abbrev corresponding to that skipped uleb128 should be passed in
9154    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
9155    children.  */
9156
9157 static const gdb_byte *
9158 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
9159               struct abbrev_info *abbrev)
9160 {
9161   unsigned int bytes_read;
9162   struct attribute attr;
9163   bfd *abfd = reader->abfd;
9164   struct dwarf2_cu *cu = reader->cu;
9165   const gdb_byte *buffer = reader->buffer;
9166   const gdb_byte *buffer_end = reader->buffer_end;
9167   unsigned int form, i;
9168
9169   for (i = 0; i < abbrev->num_attrs; i++)
9170     {
9171       /* The only abbrev we care about is DW_AT_sibling.  */
9172       if (abbrev->attrs[i].name == DW_AT_sibling)
9173         {
9174           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
9175           if (attr.form == DW_FORM_ref_addr)
9176             complaint (_("ignoring absolute DW_AT_sibling"));
9177           else
9178             {
9179               sect_offset off = dwarf2_get_ref_die_offset (&attr);
9180               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
9181
9182               if (sibling_ptr < info_ptr)
9183                 complaint (_("DW_AT_sibling points backwards"));
9184               else if (sibling_ptr > reader->buffer_end)
9185                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
9186               else
9187                 return sibling_ptr;
9188             }
9189         }
9190
9191       /* If it isn't DW_AT_sibling, skip this attribute.  */
9192       form = abbrev->attrs[i].form;
9193     skip_attribute:
9194       switch (form)
9195         {
9196         case DW_FORM_ref_addr:
9197           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
9198              and later it is offset sized.  */
9199           if (cu->header.version == 2)
9200             info_ptr += cu->header.addr_size;
9201           else
9202             info_ptr += cu->header.offset_size;
9203           break;
9204         case DW_FORM_GNU_ref_alt:
9205           info_ptr += cu->header.offset_size;
9206           break;
9207         case DW_FORM_addr:
9208           info_ptr += cu->header.addr_size;
9209           break;
9210         case DW_FORM_data1:
9211         case DW_FORM_ref1:
9212         case DW_FORM_flag:
9213           info_ptr += 1;
9214           break;
9215         case DW_FORM_flag_present:
9216         case DW_FORM_implicit_const:
9217           break;
9218         case DW_FORM_data2:
9219         case DW_FORM_ref2:
9220           info_ptr += 2;
9221           break;
9222         case DW_FORM_data4:
9223         case DW_FORM_ref4:
9224           info_ptr += 4;
9225           break;
9226         case DW_FORM_data8:
9227         case DW_FORM_ref8:
9228         case DW_FORM_ref_sig8:
9229           info_ptr += 8;
9230           break;
9231         case DW_FORM_data16:
9232           info_ptr += 16;
9233           break;
9234         case DW_FORM_string:
9235           read_direct_string (abfd, info_ptr, &bytes_read);
9236           info_ptr += bytes_read;
9237           break;
9238         case DW_FORM_sec_offset:
9239         case DW_FORM_strp:
9240         case DW_FORM_GNU_strp_alt:
9241           info_ptr += cu->header.offset_size;
9242           break;
9243         case DW_FORM_exprloc:
9244         case DW_FORM_block:
9245           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9246           info_ptr += bytes_read;
9247           break;
9248         case DW_FORM_block1:
9249           info_ptr += 1 + read_1_byte (abfd, info_ptr);
9250           break;
9251         case DW_FORM_block2:
9252           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
9253           break;
9254         case DW_FORM_block4:
9255           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
9256           break;
9257         case DW_FORM_sdata:
9258         case DW_FORM_udata:
9259         case DW_FORM_ref_udata:
9260         case DW_FORM_GNU_addr_index:
9261         case DW_FORM_GNU_str_index:
9262           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
9263           break;
9264         case DW_FORM_indirect:
9265           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
9266           info_ptr += bytes_read;
9267           /* We need to continue parsing from here, so just go back to
9268              the top.  */
9269           goto skip_attribute;
9270
9271         default:
9272           error (_("Dwarf Error: Cannot handle %s "
9273                    "in DWARF reader [in module %s]"),
9274                  dwarf_form_name (form),
9275                  bfd_get_filename (abfd));
9276         }
9277     }
9278
9279   if (abbrev->has_children)
9280     return skip_children (reader, info_ptr);
9281   else
9282     return info_ptr;
9283 }
9284
9285 /* Locate ORIG_PDI's sibling.
9286    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
9287
9288 static const gdb_byte *
9289 locate_pdi_sibling (const struct die_reader_specs *reader,
9290                     struct partial_die_info *orig_pdi,
9291                     const gdb_byte *info_ptr)
9292 {
9293   /* Do we know the sibling already?  */
9294
9295   if (orig_pdi->sibling)
9296     return orig_pdi->sibling;
9297
9298   /* Are there any children to deal with?  */
9299
9300   if (!orig_pdi->has_children)
9301     return info_ptr;
9302
9303   /* Skip the children the long way.  */
9304
9305   return skip_children (reader, info_ptr);
9306 }
9307
9308 /* Expand this partial symbol table into a full symbol table.  SELF is
9309    not NULL.  */
9310
9311 static void
9312 dwarf2_read_symtab (struct partial_symtab *self,
9313                     struct objfile *objfile)
9314 {
9315   struct dwarf2_per_objfile *dwarf2_per_objfile
9316     = get_dwarf2_per_objfile (objfile);
9317
9318   if (self->readin)
9319     {
9320       warning (_("bug: psymtab for %s is already read in."),
9321                self->filename);
9322     }
9323   else
9324     {
9325       if (info_verbose)
9326         {
9327           printf_filtered (_("Reading in symbols for %s..."),
9328                            self->filename);
9329           gdb_flush (gdb_stdout);
9330         }
9331
9332       /* If this psymtab is constructed from a debug-only objfile, the
9333          has_section_at_zero flag will not necessarily be correct.  We
9334          can get the correct value for this flag by looking at the data
9335          associated with the (presumably stripped) associated objfile.  */
9336       if (objfile->separate_debug_objfile_backlink)
9337         {
9338           struct dwarf2_per_objfile *dpo_backlink
9339             = get_dwarf2_per_objfile (objfile->separate_debug_objfile_backlink);
9340
9341           dwarf2_per_objfile->has_section_at_zero
9342             = dpo_backlink->has_section_at_zero;
9343         }
9344
9345       dwarf2_per_objfile->reading_partial_symbols = 0;
9346
9347       psymtab_to_symtab_1 (self);
9348
9349       /* Finish up the debug error message.  */
9350       if (info_verbose)
9351         printf_filtered (_("done.\n"));
9352     }
9353
9354   process_cu_includes (dwarf2_per_objfile);
9355 }
9356 \f
9357 /* Reading in full CUs.  */
9358
9359 /* Add PER_CU to the queue.  */
9360
9361 static void
9362 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
9363                  enum language pretend_language)
9364 {
9365   struct dwarf2_queue_item *item;
9366
9367   per_cu->queued = 1;
9368   item = XNEW (struct dwarf2_queue_item);
9369   item->per_cu = per_cu;
9370   item->pretend_language = pretend_language;
9371   item->next = NULL;
9372
9373   if (dwarf2_queue == NULL)
9374     dwarf2_queue = item;
9375   else
9376     dwarf2_queue_tail->next = item;
9377
9378   dwarf2_queue_tail = item;
9379 }
9380
9381 /* If PER_CU is not yet queued, add it to the queue.
9382    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
9383    dependency.
9384    The result is non-zero if PER_CU was queued, otherwise the result is zero
9385    meaning either PER_CU is already queued or it is already loaded.
9386
9387    N.B. There is an invariant here that if a CU is queued then it is loaded.
9388    The caller is required to load PER_CU if we return non-zero.  */
9389
9390 static int
9391 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
9392                        struct dwarf2_per_cu_data *per_cu,
9393                        enum language pretend_language)
9394 {
9395   /* We may arrive here during partial symbol reading, if we need full
9396      DIEs to process an unusual case (e.g. template arguments).  Do
9397      not queue PER_CU, just tell our caller to load its DIEs.  */
9398   if (per_cu->dwarf2_per_objfile->reading_partial_symbols)
9399     {
9400       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
9401         return 1;
9402       return 0;
9403     }
9404
9405   /* Mark the dependence relation so that we don't flush PER_CU
9406      too early.  */
9407   if (dependent_cu != NULL)
9408     dwarf2_add_dependence (dependent_cu, per_cu);
9409
9410   /* If it's already on the queue, we have nothing to do.  */
9411   if (per_cu->queued)
9412     return 0;
9413
9414   /* If the compilation unit is already loaded, just mark it as
9415      used.  */
9416   if (per_cu->cu != NULL)
9417     {
9418       per_cu->cu->last_used = 0;
9419       return 0;
9420     }
9421
9422   /* Add it to the queue.  */
9423   queue_comp_unit (per_cu, pretend_language);
9424
9425   return 1;
9426 }
9427
9428 /* Process the queue.  */
9429
9430 static void
9431 process_queue (struct dwarf2_per_objfile *dwarf2_per_objfile)
9432 {
9433   struct dwarf2_queue_item *item, *next_item;
9434
9435   if (dwarf_read_debug)
9436     {
9437       fprintf_unfiltered (gdb_stdlog,
9438                           "Expanding one or more symtabs of objfile %s ...\n",
9439                           objfile_name (dwarf2_per_objfile->objfile));
9440     }
9441
9442   /* The queue starts out with one item, but following a DIE reference
9443      may load a new CU, adding it to the end of the queue.  */
9444   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
9445     {
9446       if ((dwarf2_per_objfile->using_index
9447            ? !item->per_cu->v.quick->compunit_symtab
9448            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
9449           /* Skip dummy CUs.  */
9450           && item->per_cu->cu != NULL)
9451         {
9452           struct dwarf2_per_cu_data *per_cu = item->per_cu;
9453           unsigned int debug_print_threshold;
9454           char buf[100];
9455
9456           if (per_cu->is_debug_types)
9457             {
9458               struct signatured_type *sig_type =
9459                 (struct signatured_type *) per_cu;
9460
9461               sprintf (buf, "TU %s at offset %s",
9462                        hex_string (sig_type->signature),
9463                        sect_offset_str (per_cu->sect_off));
9464               /* There can be 100s of TUs.
9465                  Only print them in verbose mode.  */
9466               debug_print_threshold = 2;
9467             }
9468           else
9469             {
9470               sprintf (buf, "CU at offset %s",
9471                        sect_offset_str (per_cu->sect_off));
9472               debug_print_threshold = 1;
9473             }
9474
9475           if (dwarf_read_debug >= debug_print_threshold)
9476             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
9477
9478           if (per_cu->is_debug_types)
9479             process_full_type_unit (per_cu, item->pretend_language);
9480           else
9481             process_full_comp_unit (per_cu, item->pretend_language);
9482
9483           if (dwarf_read_debug >= debug_print_threshold)
9484             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
9485         }
9486
9487       item->per_cu->queued = 0;
9488       next_item = item->next;
9489       xfree (item);
9490     }
9491
9492   dwarf2_queue_tail = NULL;
9493
9494   if (dwarf_read_debug)
9495     {
9496       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
9497                           objfile_name (dwarf2_per_objfile->objfile));
9498     }
9499 }
9500
9501 /* Read in full symbols for PST, and anything it depends on.  */
9502
9503 static void
9504 psymtab_to_symtab_1 (struct partial_symtab *pst)
9505 {
9506   struct dwarf2_per_cu_data *per_cu;
9507   int i;
9508
9509   if (pst->readin)
9510     return;
9511
9512   for (i = 0; i < pst->number_of_dependencies; i++)
9513     if (!pst->dependencies[i]->readin
9514         && pst->dependencies[i]->user == NULL)
9515       {
9516         /* Inform about additional files that need to be read in.  */
9517         if (info_verbose)
9518           {
9519             /* FIXME: i18n: Need to make this a single string.  */
9520             fputs_filtered (" ", gdb_stdout);
9521             wrap_here ("");
9522             fputs_filtered ("and ", gdb_stdout);
9523             wrap_here ("");
9524             printf_filtered ("%s...", pst->dependencies[i]->filename);
9525             wrap_here ("");     /* Flush output.  */
9526             gdb_flush (gdb_stdout);
9527           }
9528         psymtab_to_symtab_1 (pst->dependencies[i]);
9529       }
9530
9531   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
9532
9533   if (per_cu == NULL)
9534     {
9535       /* It's an include file, no symbols to read for it.
9536          Everything is in the parent symtab.  */
9537       pst->readin = 1;
9538       return;
9539     }
9540
9541   dw2_do_instantiate_symtab (per_cu, false);
9542 }
9543
9544 /* Trivial hash function for die_info: the hash value of a DIE
9545    is its offset in .debug_info for this objfile.  */
9546
9547 static hashval_t
9548 die_hash (const void *item)
9549 {
9550   const struct die_info *die = (const struct die_info *) item;
9551
9552   return to_underlying (die->sect_off);
9553 }
9554
9555 /* Trivial comparison function for die_info structures: two DIEs
9556    are equal if they have the same offset.  */
9557
9558 static int
9559 die_eq (const void *item_lhs, const void *item_rhs)
9560 {
9561   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
9562   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
9563
9564   return die_lhs->sect_off == die_rhs->sect_off;
9565 }
9566
9567 /* die_reader_func for load_full_comp_unit.
9568    This is identical to read_signatured_type_reader,
9569    but is kept separate for now.  */
9570
9571 static void
9572 load_full_comp_unit_reader (const struct die_reader_specs *reader,
9573                             const gdb_byte *info_ptr,
9574                             struct die_info *comp_unit_die,
9575                             int has_children,
9576                             void *data)
9577 {
9578   struct dwarf2_cu *cu = reader->cu;
9579   enum language *language_ptr = (enum language *) data;
9580
9581   gdb_assert (cu->die_hash == NULL);
9582   cu->die_hash =
9583     htab_create_alloc_ex (cu->header.length / 12,
9584                           die_hash,
9585                           die_eq,
9586                           NULL,
9587                           &cu->comp_unit_obstack,
9588                           hashtab_obstack_allocate,
9589                           dummy_obstack_deallocate);
9590
9591   if (has_children)
9592     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
9593                                                   &info_ptr, comp_unit_die);
9594   cu->dies = comp_unit_die;
9595   /* comp_unit_die is not stored in die_hash, no need.  */
9596
9597   /* We try not to read any attributes in this function, because not
9598      all CUs needed for references have been loaded yet, and symbol
9599      table processing isn't initialized.  But we have to set the CU language,
9600      or we won't be able to build types correctly.
9601      Similarly, if we do not read the producer, we can not apply
9602      producer-specific interpretation.  */
9603   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
9604 }
9605
9606 /* Load the DIEs associated with PER_CU into memory.  */
9607
9608 static void
9609 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
9610                      bool skip_partial,
9611                      enum language pretend_language)
9612 {
9613   gdb_assert (! this_cu->is_debug_types);
9614
9615   init_cutu_and_read_dies (this_cu, NULL, 1, 1, skip_partial,
9616                            load_full_comp_unit_reader, &pretend_language);
9617 }
9618
9619 /* Add a DIE to the delayed physname list.  */
9620
9621 static void
9622 add_to_method_list (struct type *type, int fnfield_index, int index,
9623                     const char *name, struct die_info *die,
9624                     struct dwarf2_cu *cu)
9625 {
9626   struct delayed_method_info mi;
9627   mi.type = type;
9628   mi.fnfield_index = fnfield_index;
9629   mi.index = index;
9630   mi.name = name;
9631   mi.die = die;
9632   cu->method_list.push_back (mi);
9633 }
9634
9635 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
9636    "const" / "volatile".  If so, decrements LEN by the length of the
9637    modifier and return true.  Otherwise return false.  */
9638
9639 template<size_t N>
9640 static bool
9641 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
9642 {
9643   size_t mod_len = sizeof (mod) - 1;
9644   if (len > mod_len && startswith (physname + (len - mod_len), mod))
9645     {
9646       len -= mod_len;
9647       return true;
9648     }
9649   return false;
9650 }
9651
9652 /* Compute the physnames of any methods on the CU's method list.
9653
9654    The computation of method physnames is delayed in order to avoid the
9655    (bad) condition that one of the method's formal parameters is of an as yet
9656    incomplete type.  */
9657
9658 static void
9659 compute_delayed_physnames (struct dwarf2_cu *cu)
9660 {
9661   /* Only C++ delays computing physnames.  */
9662   if (cu->method_list.empty ())
9663     return;
9664   gdb_assert (cu->language == language_cplus);
9665
9666   for (const delayed_method_info &mi : cu->method_list)
9667     {
9668       const char *physname;
9669       struct fn_fieldlist *fn_flp
9670         = &TYPE_FN_FIELDLIST (mi.type, mi.fnfield_index);
9671       physname = dwarf2_physname (mi.name, mi.die, cu);
9672       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi.index)
9673         = physname ? physname : "";
9674
9675       /* Since there's no tag to indicate whether a method is a
9676          const/volatile overload, extract that information out of the
9677          demangled name.  */
9678       if (physname != NULL)
9679         {
9680           size_t len = strlen (physname);
9681
9682           while (1)
9683             {
9684               if (physname[len] == ')') /* shortcut */
9685                 break;
9686               else if (check_modifier (physname, len, " const"))
9687                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi.index) = 1;
9688               else if (check_modifier (physname, len, " volatile"))
9689                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi.index) = 1;
9690               else
9691                 break;
9692             }
9693         }
9694     }
9695
9696   /* The list is no longer needed.  */
9697   cu->method_list.clear ();
9698 }
9699
9700 /* Go objects should be embedded in a DW_TAG_module DIE,
9701    and it's not clear if/how imported objects will appear.
9702    To keep Go support simple until that's worked out,
9703    go back through what we've read and create something usable.
9704    We could do this while processing each DIE, and feels kinda cleaner,
9705    but that way is more invasive.
9706    This is to, for example, allow the user to type "p var" or "b main"
9707    without having to specify the package name, and allow lookups
9708    of module.object to work in contexts that use the expression
9709    parser.  */
9710
9711 static void
9712 fixup_go_packaging (struct dwarf2_cu *cu)
9713 {
9714   char *package_name = NULL;
9715   struct pending *list;
9716   int i;
9717
9718   for (list = global_symbols; list != NULL; list = list->next)
9719     {
9720       for (i = 0; i < list->nsyms; ++i)
9721         {
9722           struct symbol *sym = list->symbol[i];
9723
9724           if (SYMBOL_LANGUAGE (sym) == language_go
9725               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9726             {
9727               char *this_package_name = go_symbol_package_name (sym);
9728
9729               if (this_package_name == NULL)
9730                 continue;
9731               if (package_name == NULL)
9732                 package_name = this_package_name;
9733               else
9734                 {
9735                   struct objfile *objfile
9736                     = cu->per_cu->dwarf2_per_objfile->objfile;
9737                   if (strcmp (package_name, this_package_name) != 0)
9738                     complaint (_("Symtab %s has objects from two different Go packages: %s and %s"),
9739                                (symbol_symtab (sym) != NULL
9740                                 ? symtab_to_filename_for_display
9741                                     (symbol_symtab (sym))
9742                                 : objfile_name (objfile)),
9743                                this_package_name, package_name);
9744                   xfree (this_package_name);
9745                 }
9746             }
9747         }
9748     }
9749
9750   if (package_name != NULL)
9751     {
9752       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
9753       const char *saved_package_name
9754         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9755                                         package_name,
9756                                         strlen (package_name));
9757       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9758                                      saved_package_name);
9759       struct symbol *sym;
9760
9761       sym = allocate_symbol (objfile);
9762       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9763       SYMBOL_SET_NAMES (sym, saved_package_name,
9764                         strlen (saved_package_name), 0, objfile);
9765       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9766          e.g., "main" finds the "main" module and not C's main().  */
9767       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9768       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9769       SYMBOL_TYPE (sym) = type;
9770
9771       add_symbol_to_list (sym, &global_symbols);
9772
9773       xfree (package_name);
9774     }
9775 }
9776
9777 /* Allocate a fully-qualified name consisting of the two parts on the
9778    obstack.  */
9779
9780 static const char *
9781 rust_fully_qualify (struct obstack *obstack, const char *p1, const char *p2)
9782 {
9783   return obconcat (obstack, p1, "::", p2, (char *) NULL);
9784 }
9785
9786 /* A helper that allocates a struct discriminant_info to attach to a
9787    union type.  */
9788
9789 static struct discriminant_info *
9790 alloc_discriminant_info (struct type *type, int discriminant_index,
9791                          int default_index)
9792 {
9793   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9794   gdb_assert (discriminant_index == -1
9795               || (discriminant_index >= 0
9796                   && discriminant_index < TYPE_NFIELDS (type)));
9797   gdb_assert (default_index == -1
9798               || (default_index >= 0 && default_index < TYPE_NFIELDS (type)));
9799
9800   TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
9801
9802   struct discriminant_info *disc
9803     = ((struct discriminant_info *)
9804        TYPE_ZALLOC (type,
9805                     offsetof (struct discriminant_info, discriminants)
9806                     + TYPE_NFIELDS (type) * sizeof (disc->discriminants[0])));
9807   disc->default_index = default_index;
9808   disc->discriminant_index = discriminant_index;
9809
9810   struct dynamic_prop prop;
9811   prop.kind = PROP_UNDEFINED;
9812   prop.data.baton = disc;
9813
9814   add_dyn_prop (DYN_PROP_DISCRIMINATED, prop, type);
9815
9816   return disc;
9817 }
9818
9819 /* Some versions of rustc emitted enums in an unusual way.
9820
9821    Ordinary enums were emitted as unions.  The first element of each
9822    structure in the union was named "RUST$ENUM$DISR".  This element
9823    held the discriminant.
9824
9825    These versions of Rust also implemented the "non-zero"
9826    optimization.  When the enum had two values, and one is empty and
9827    the other holds a pointer that cannot be zero, the pointer is used
9828    as the discriminant, with a zero value meaning the empty variant.
9829    Here, the union's first member is of the form
9830    RUST$ENCODED$ENUM$<fieldno>$<fieldno>$...$<variantname>
9831    where the fieldnos are the indices of the fields that should be
9832    traversed in order to find the field (which may be several fields deep)
9833    and the variantname is the name of the variant of the case when the
9834    field is zero.
9835
9836    This function recognizes whether TYPE is of one of these forms,
9837    and, if so, smashes it to be a variant type.  */
9838
9839 static void
9840 quirk_rust_enum (struct type *type, struct objfile *objfile)
9841 {
9842   gdb_assert (TYPE_CODE (type) == TYPE_CODE_UNION);
9843
9844   /* We don't need to deal with empty enums.  */
9845   if (TYPE_NFIELDS (type) == 0)
9846     return;
9847
9848 #define RUST_ENUM_PREFIX "RUST$ENCODED$ENUM$"
9849   if (TYPE_NFIELDS (type) == 1
9850       && startswith (TYPE_FIELD_NAME (type, 0), RUST_ENUM_PREFIX))
9851     {
9852       const char *name = TYPE_FIELD_NAME (type, 0) + strlen (RUST_ENUM_PREFIX);
9853
9854       /* Decode the field name to find the offset of the
9855          discriminant.  */
9856       ULONGEST bit_offset = 0;
9857       struct type *field_type = TYPE_FIELD_TYPE (type, 0);
9858       while (name[0] >= '0' && name[0] <= '9')
9859         {
9860           char *tail;
9861           unsigned long index = strtoul (name, &tail, 10);
9862           name = tail;
9863           if (*name != '$'
9864               || index >= TYPE_NFIELDS (field_type)
9865               || (TYPE_FIELD_LOC_KIND (field_type, index)
9866                   != FIELD_LOC_KIND_BITPOS))
9867             {
9868               complaint (_("Could not parse Rust enum encoding string \"%s\""
9869                            "[in module %s]"),
9870                          TYPE_FIELD_NAME (type, 0),
9871                          objfile_name (objfile));
9872               return;
9873             }
9874           ++name;
9875
9876           bit_offset += TYPE_FIELD_BITPOS (field_type, index);
9877           field_type = TYPE_FIELD_TYPE (field_type, index);
9878         }
9879
9880       /* Make a union to hold the variants.  */
9881       struct type *union_type = alloc_type (objfile);
9882       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9883       TYPE_NFIELDS (union_type) = 3;
9884       TYPE_FIELDS (union_type)
9885         = (struct field *) TYPE_ZALLOC (type, 3 * sizeof (struct field));
9886       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9887       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9888
9889       /* Put the discriminant must at index 0.  */
9890       TYPE_FIELD_TYPE (union_type, 0) = field_type;
9891       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
9892       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
9893       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 0), bit_offset);
9894
9895       /* The order of fields doesn't really matter, so put the real
9896          field at index 1 and the data-less field at index 2.  */
9897       struct discriminant_info *disc
9898         = alloc_discriminant_info (union_type, 0, 1);
9899       TYPE_FIELD (union_type, 1) = TYPE_FIELD (type, 0);
9900       TYPE_FIELD_NAME (union_type, 1)
9901         = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1)));
9902       TYPE_NAME (TYPE_FIELD_TYPE (union_type, 1))
9903         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9904                               TYPE_FIELD_NAME (union_type, 1));
9905
9906       const char *dataless_name
9907         = rust_fully_qualify (&objfile->objfile_obstack, TYPE_NAME (type),
9908                               name);
9909       struct type *dataless_type = init_type (objfile, TYPE_CODE_VOID, 0,
9910                                               dataless_name);
9911       TYPE_FIELD_TYPE (union_type, 2) = dataless_type;
9912       /* NAME points into the original discriminant name, which
9913          already has the correct lifetime.  */
9914       TYPE_FIELD_NAME (union_type, 2) = name;
9915       SET_FIELD_BITPOS (TYPE_FIELD (union_type, 2), 0);
9916       disc->discriminants[2] = 0;
9917
9918       /* Smash this type to be a structure type.  We have to do this
9919          because the type has already been recorded.  */
9920       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9921       TYPE_NFIELDS (type) = 1;
9922       TYPE_FIELDS (type)
9923         = (struct field *) TYPE_ZALLOC (type, sizeof (struct field));
9924
9925       /* Install the variant part.  */
9926       TYPE_FIELD_TYPE (type, 0) = union_type;
9927       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9928       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9929     }
9930   else if (TYPE_NFIELDS (type) == 1)
9931     {
9932       /* We assume that a union with a single field is a univariant
9933          enum.  */
9934       /* Smash this type to be a structure type.  We have to do this
9935          because the type has already been recorded.  */
9936       TYPE_CODE (type) = TYPE_CODE_STRUCT;
9937
9938       /* Make a union to hold the variants.  */
9939       struct type *union_type = alloc_type (objfile);
9940       TYPE_CODE (union_type) = TYPE_CODE_UNION;
9941       TYPE_NFIELDS (union_type) = TYPE_NFIELDS (type);
9942       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
9943       set_type_align (union_type, TYPE_RAW_ALIGN (type));
9944       TYPE_FIELDS (union_type) = TYPE_FIELDS (type);
9945
9946       struct type *field_type = TYPE_FIELD_TYPE (union_type, 0);
9947       const char *variant_name
9948         = rust_last_path_segment (TYPE_NAME (field_type));
9949       TYPE_FIELD_NAME (union_type, 0) = variant_name;
9950       TYPE_NAME (field_type)
9951         = rust_fully_qualify (&objfile->objfile_obstack,
9952                               TYPE_NAME (type), variant_name);
9953
9954       /* Install the union in the outer struct type.  */
9955       TYPE_NFIELDS (type) = 1;
9956       TYPE_FIELDS (type)
9957         = (struct field *) TYPE_ZALLOC (union_type, sizeof (struct field));
9958       TYPE_FIELD_TYPE (type, 0) = union_type;
9959       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
9960       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
9961
9962       alloc_discriminant_info (union_type, -1, 0);
9963     }
9964   else
9965     {
9966       struct type *disr_type = nullptr;
9967       for (int i = 0; i < TYPE_NFIELDS (type); ++i)
9968         {
9969           disr_type = TYPE_FIELD_TYPE (type, i);
9970
9971           if (TYPE_CODE (disr_type) != TYPE_CODE_STRUCT)
9972             {
9973               /* All fields of a true enum will be structs.  */
9974               return;
9975             }
9976           else if (TYPE_NFIELDS (disr_type) == 0)
9977             {
9978               /* Could be data-less variant, so keep going.  */
9979               disr_type = nullptr;
9980             }
9981           else if (strcmp (TYPE_FIELD_NAME (disr_type, 0),
9982                            "RUST$ENUM$DISR") != 0)
9983             {
9984               /* Not a Rust enum.  */
9985               return;
9986             }
9987           else
9988             {
9989               /* Found one.  */
9990               break;
9991             }
9992         }
9993
9994       /* If we got here without a discriminant, then it's probably
9995          just a union.  */
9996       if (disr_type == nullptr)
9997         return;
9998
9999       /* Smash this type to be a structure type.  We have to do this
10000          because the type has already been recorded.  */
10001       TYPE_CODE (type) = TYPE_CODE_STRUCT;
10002
10003       /* Make a union to hold the variants.  */
10004       struct field *disr_field = &TYPE_FIELD (disr_type, 0);
10005       struct type *union_type = alloc_type (objfile);
10006       TYPE_CODE (union_type) = TYPE_CODE_UNION;
10007       TYPE_NFIELDS (union_type) = 1 + TYPE_NFIELDS (type);
10008       TYPE_LENGTH (union_type) = TYPE_LENGTH (type);
10009       set_type_align (union_type, TYPE_RAW_ALIGN (type));
10010       TYPE_FIELDS (union_type)
10011         = (struct field *) TYPE_ZALLOC (union_type,
10012                                         (TYPE_NFIELDS (union_type)
10013                                          * sizeof (struct field)));
10014
10015       memcpy (TYPE_FIELDS (union_type) + 1, TYPE_FIELDS (type),
10016               TYPE_NFIELDS (type) * sizeof (struct field));
10017
10018       /* Install the discriminant at index 0 in the union.  */
10019       TYPE_FIELD (union_type, 0) = *disr_field;
10020       TYPE_FIELD_ARTIFICIAL (union_type, 0) = 1;
10021       TYPE_FIELD_NAME (union_type, 0) = "<<discriminant>>";
10022
10023       /* Install the union in the outer struct type.  */
10024       TYPE_FIELD_TYPE (type, 0) = union_type;
10025       TYPE_FIELD_NAME (type, 0) = "<<variants>>";
10026       TYPE_NFIELDS (type) = 1;
10027
10028       /* Set the size and offset of the union type.  */
10029       SET_FIELD_BITPOS (TYPE_FIELD (type, 0), 0);
10030
10031       /* We need a way to find the correct discriminant given a
10032          variant name.  For convenience we build a map here.  */
10033       struct type *enum_type = FIELD_TYPE (*disr_field);
10034       std::unordered_map<std::string, ULONGEST> discriminant_map;
10035       for (int i = 0; i < TYPE_NFIELDS (enum_type); ++i)
10036         {
10037           if (TYPE_FIELD_LOC_KIND (enum_type, i) == FIELD_LOC_KIND_ENUMVAL)
10038             {
10039               const char *name
10040                 = rust_last_path_segment (TYPE_FIELD_NAME (enum_type, i));
10041               discriminant_map[name] = TYPE_FIELD_ENUMVAL (enum_type, i);
10042             }
10043         }
10044
10045       int n_fields = TYPE_NFIELDS (union_type);
10046       struct discriminant_info *disc
10047         = alloc_discriminant_info (union_type, 0, -1);
10048       /* Skip the discriminant here.  */
10049       for (int i = 1; i < n_fields; ++i)
10050         {
10051           /* Find the final word in the name of this variant's type.
10052              That name can be used to look up the correct
10053              discriminant.  */
10054           const char *variant_name
10055             = rust_last_path_segment (TYPE_NAME (TYPE_FIELD_TYPE (union_type,
10056                                                                   i)));
10057
10058           auto iter = discriminant_map.find (variant_name);
10059           if (iter != discriminant_map.end ())
10060             disc->discriminants[i] = iter->second;
10061
10062           /* Remove the discriminant field, if it exists.  */
10063           struct type *sub_type = TYPE_FIELD_TYPE (union_type, i);
10064           if (TYPE_NFIELDS (sub_type) > 0)
10065             {
10066               --TYPE_NFIELDS (sub_type);
10067               ++TYPE_FIELDS (sub_type);
10068             }
10069           TYPE_FIELD_NAME (union_type, i) = variant_name;
10070           TYPE_NAME (sub_type)
10071             = rust_fully_qualify (&objfile->objfile_obstack,
10072                                   TYPE_NAME (type), variant_name);
10073         }
10074     }
10075 }
10076
10077 /* Rewrite some Rust unions to be structures with variants parts.  */
10078
10079 static void
10080 rust_union_quirks (struct dwarf2_cu *cu)
10081 {
10082   gdb_assert (cu->language == language_rust);
10083   for (type *type_ : cu->rust_unions)
10084     quirk_rust_enum (type_, cu->per_cu->dwarf2_per_objfile->objfile);
10085   /* We don't need this any more.  */
10086   cu->rust_unions.clear ();
10087 }
10088
10089 /* Return the symtab for PER_CU.  This works properly regardless of
10090    whether we're using the index or psymtabs.  */
10091
10092 static struct compunit_symtab *
10093 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
10094 {
10095   return (per_cu->dwarf2_per_objfile->using_index
10096           ? per_cu->v.quick->compunit_symtab
10097           : per_cu->v.psymtab->compunit_symtab);
10098 }
10099
10100 /* A helper function for computing the list of all symbol tables
10101    included by PER_CU.  */
10102
10103 static void
10104 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
10105                                 htab_t all_children, htab_t all_type_symtabs,
10106                                 struct dwarf2_per_cu_data *per_cu,
10107                                 struct compunit_symtab *immediate_parent)
10108 {
10109   void **slot;
10110   int ix;
10111   struct compunit_symtab *cust;
10112   struct dwarf2_per_cu_data *iter;
10113
10114   slot = htab_find_slot (all_children, per_cu, INSERT);
10115   if (*slot != NULL)
10116     {
10117       /* This inclusion and its children have been processed.  */
10118       return;
10119     }
10120
10121   *slot = per_cu;
10122   /* Only add a CU if it has a symbol table.  */
10123   cust = get_compunit_symtab (per_cu);
10124   if (cust != NULL)
10125     {
10126       /* If this is a type unit only add its symbol table if we haven't
10127          seen it yet (type unit per_cu's can share symtabs).  */
10128       if (per_cu->is_debug_types)
10129         {
10130           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
10131           if (*slot == NULL)
10132             {
10133               *slot = cust;
10134               VEC_safe_push (compunit_symtab_ptr, *result, cust);
10135               if (cust->user == NULL)
10136                 cust->user = immediate_parent;
10137             }
10138         }
10139       else
10140         {
10141           VEC_safe_push (compunit_symtab_ptr, *result, cust);
10142           if (cust->user == NULL)
10143             cust->user = immediate_parent;
10144         }
10145     }
10146
10147   for (ix = 0;
10148        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
10149        ++ix)
10150     {
10151       recursively_compute_inclusions (result, all_children,
10152                                       all_type_symtabs, iter, cust);
10153     }
10154 }
10155
10156 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
10157    PER_CU.  */
10158
10159 static void
10160 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
10161 {
10162   gdb_assert (! per_cu->is_debug_types);
10163
10164   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
10165     {
10166       int ix, len;
10167       struct dwarf2_per_cu_data *per_cu_iter;
10168       struct compunit_symtab *compunit_symtab_iter;
10169       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
10170       htab_t all_children, all_type_symtabs;
10171       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
10172
10173       /* If we don't have a symtab, we can just skip this case.  */
10174       if (cust == NULL)
10175         return;
10176
10177       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10178                                         NULL, xcalloc, xfree);
10179       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
10180                                             NULL, xcalloc, xfree);
10181
10182       for (ix = 0;
10183            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
10184                         ix, per_cu_iter);
10185            ++ix)
10186         {
10187           recursively_compute_inclusions (&result_symtabs, all_children,
10188                                           all_type_symtabs, per_cu_iter,
10189                                           cust);
10190         }
10191
10192       /* Now we have a transitive closure of all the included symtabs.  */
10193       len = VEC_length (compunit_symtab_ptr, result_symtabs);
10194       cust->includes
10195         = XOBNEWVEC (&per_cu->dwarf2_per_objfile->objfile->objfile_obstack,
10196                      struct compunit_symtab *, len + 1);
10197       for (ix = 0;
10198            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
10199                         compunit_symtab_iter);
10200            ++ix)
10201         cust->includes[ix] = compunit_symtab_iter;
10202       cust->includes[len] = NULL;
10203
10204       VEC_free (compunit_symtab_ptr, result_symtabs);
10205       htab_delete (all_children);
10206       htab_delete (all_type_symtabs);
10207     }
10208 }
10209
10210 /* Compute the 'includes' field for the symtabs of all the CUs we just
10211    read.  */
10212
10213 static void
10214 process_cu_includes (struct dwarf2_per_objfile *dwarf2_per_objfile)
10215 {
10216   for (dwarf2_per_cu_data *iter : dwarf2_per_objfile->just_read_cus)
10217     {
10218       if (! iter->is_debug_types)
10219         compute_compunit_symtab_includes (iter);
10220     }
10221
10222   dwarf2_per_objfile->just_read_cus.clear ();
10223 }
10224
10225 /* Generate full symbol information for PER_CU, whose DIEs have
10226    already been loaded into memory.  */
10227
10228 static void
10229 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
10230                         enum language pretend_language)
10231 {
10232   struct dwarf2_cu *cu = per_cu->cu;
10233   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10234   struct objfile *objfile = dwarf2_per_objfile->objfile;
10235   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10236   CORE_ADDR lowpc, highpc;
10237   struct compunit_symtab *cust;
10238   CORE_ADDR baseaddr;
10239   struct block *static_block;
10240   CORE_ADDR addr;
10241
10242   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10243
10244   buildsym_init ();
10245   scoped_free_pendings free_pending;
10246
10247   /* Clear the list here in case something was left over.  */
10248   cu->method_list.clear ();
10249
10250   cu->list_in_scope = &file_symbols;
10251
10252   cu->language = pretend_language;
10253   cu->language_defn = language_def (cu->language);
10254
10255   /* Do line number decoding in read_file_scope () */
10256   process_die (cu->dies, cu);
10257
10258   /* For now fudge the Go package.  */
10259   if (cu->language == language_go)
10260     fixup_go_packaging (cu);
10261
10262   /* Now that we have processed all the DIEs in the CU, all the types 
10263      should be complete, and it should now be safe to compute all of the
10264      physnames.  */
10265   compute_delayed_physnames (cu);
10266
10267   if (cu->language == language_rust)
10268     rust_union_quirks (cu);
10269
10270   /* Some compilers don't define a DW_AT_high_pc attribute for the
10271      compilation unit.  If the DW_AT_high_pc is missing, synthesize
10272      it, by scanning the DIE's below the compilation unit.  */
10273   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
10274
10275   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
10276   static_block = end_symtab_get_static_block (addr, 0, 1);
10277
10278   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
10279      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
10280      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
10281      addrmap to help ensure it has an accurate map of pc values belonging to
10282      this comp unit.  */
10283   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
10284
10285   cust = end_symtab_from_static_block (static_block,
10286                                        SECT_OFF_TEXT (objfile), 0);
10287
10288   if (cust != NULL)
10289     {
10290       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
10291
10292       /* Set symtab language to language from DW_AT_language.  If the
10293          compilation is from a C file generated by language preprocessors, do
10294          not set the language if it was already deduced by start_subfile.  */
10295       if (!(cu->language == language_c
10296             && COMPUNIT_FILETABS (cust)->language != language_unknown))
10297         COMPUNIT_FILETABS (cust)->language = cu->language;
10298
10299       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
10300          produce DW_AT_location with location lists but it can be possibly
10301          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
10302          there were bugs in prologue debug info, fixed later in GCC-4.5
10303          by "unwind info for epilogues" patch (which is not directly related).
10304
10305          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
10306          needed, it would be wrong due to missing DW_AT_producer there.
10307
10308          Still one can confuse GDB by using non-standard GCC compilation
10309          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
10310          */ 
10311       if (cu->has_loclist && gcc_4_minor >= 5)
10312         cust->locations_valid = 1;
10313
10314       if (gcc_4_minor >= 5)
10315         cust->epilogue_unwind_valid = 1;
10316
10317       cust->call_site_htab = cu->call_site_htab;
10318     }
10319
10320   if (dwarf2_per_objfile->using_index)
10321     per_cu->v.quick->compunit_symtab = cust;
10322   else
10323     {
10324       struct partial_symtab *pst = per_cu->v.psymtab;
10325       pst->compunit_symtab = cust;
10326       pst->readin = 1;
10327     }
10328
10329   /* Push it for inclusion processing later.  */
10330   dwarf2_per_objfile->just_read_cus.push_back (per_cu);
10331 }
10332
10333 /* Generate full symbol information for type unit PER_CU, whose DIEs have
10334    already been loaded into memory.  */
10335
10336 static void
10337 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
10338                         enum language pretend_language)
10339 {
10340   struct dwarf2_cu *cu = per_cu->cu;
10341   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
10342   struct objfile *objfile = dwarf2_per_objfile->objfile;
10343   struct compunit_symtab *cust;
10344   struct signatured_type *sig_type;
10345
10346   gdb_assert (per_cu->is_debug_types);
10347   sig_type = (struct signatured_type *) per_cu;
10348
10349   buildsym_init ();
10350   scoped_free_pendings free_pending;
10351
10352   /* Clear the list here in case something was left over.  */
10353   cu->method_list.clear ();
10354
10355   cu->list_in_scope = &file_symbols;
10356
10357   cu->language = pretend_language;
10358   cu->language_defn = language_def (cu->language);
10359
10360   /* The symbol tables are set up in read_type_unit_scope.  */
10361   process_die (cu->dies, cu);
10362
10363   /* For now fudge the Go package.  */
10364   if (cu->language == language_go)
10365     fixup_go_packaging (cu);
10366
10367   /* Now that we have processed all the DIEs in the CU, all the types 
10368      should be complete, and it should now be safe to compute all of the
10369      physnames.  */
10370   compute_delayed_physnames (cu);
10371
10372   if (cu->language == language_rust)
10373     rust_union_quirks (cu);
10374
10375   /* TUs share symbol tables.
10376      If this is the first TU to use this symtab, complete the construction
10377      of it with end_expandable_symtab.  Otherwise, complete the addition of
10378      this TU's symbols to the existing symtab.  */
10379   if (sig_type->type_unit_group->compunit_symtab == NULL)
10380     {
10381       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
10382       sig_type->type_unit_group->compunit_symtab = cust;
10383
10384       if (cust != NULL)
10385         {
10386           /* Set symtab language to language from DW_AT_language.  If the
10387              compilation is from a C file generated by language preprocessors,
10388              do not set the language if it was already deduced by
10389              start_subfile.  */
10390           if (!(cu->language == language_c
10391                 && COMPUNIT_FILETABS (cust)->language != language_c))
10392             COMPUNIT_FILETABS (cust)->language = cu->language;
10393         }
10394     }
10395   else
10396     {
10397       augment_type_symtab ();
10398       cust = sig_type->type_unit_group->compunit_symtab;
10399     }
10400
10401   if (dwarf2_per_objfile->using_index)
10402     per_cu->v.quick->compunit_symtab = cust;
10403   else
10404     {
10405       struct partial_symtab *pst = per_cu->v.psymtab;
10406       pst->compunit_symtab = cust;
10407       pst->readin = 1;
10408     }
10409 }
10410
10411 /* Process an imported unit DIE.  */
10412
10413 static void
10414 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
10415 {
10416   struct attribute *attr;
10417
10418   /* For now we don't handle imported units in type units.  */
10419   if (cu->per_cu->is_debug_types)
10420     {
10421       error (_("Dwarf Error: DW_TAG_imported_unit is not"
10422                " supported in type units [in module %s]"),
10423              objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
10424     }
10425
10426   attr = dwarf2_attr (die, DW_AT_import, cu);
10427   if (attr != NULL)
10428     {
10429       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10430       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
10431       dwarf2_per_cu_data *per_cu
10432         = dwarf2_find_containing_comp_unit (sect_off, is_dwz,
10433                                             cu->per_cu->dwarf2_per_objfile);
10434
10435       /* If necessary, add it to the queue and load its DIEs.  */
10436       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
10437         load_full_comp_unit (per_cu, false, cu->language);
10438
10439       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
10440                      per_cu);
10441     }
10442 }
10443
10444 /* RAII object that represents a process_die scope: i.e.,
10445    starts/finishes processing a DIE.  */
10446 class process_die_scope
10447 {
10448 public:
10449   process_die_scope (die_info *die, dwarf2_cu *cu)
10450     : m_die (die), m_cu (cu)
10451   {
10452     /* We should only be processing DIEs not already in process.  */
10453     gdb_assert (!m_die->in_process);
10454     m_die->in_process = true;
10455   }
10456
10457   ~process_die_scope ()
10458   {
10459     m_die->in_process = false;
10460
10461     /* If we're done processing the DIE for the CU that owns the line
10462        header, we don't need the line header anymore.  */
10463     if (m_cu->line_header_die_owner == m_die)
10464       {
10465         delete m_cu->line_header;
10466         m_cu->line_header = NULL;
10467         m_cu->line_header_die_owner = NULL;
10468       }
10469   }
10470
10471 private:
10472   die_info *m_die;
10473   dwarf2_cu *m_cu;
10474 };
10475
10476 /* Process a die and its children.  */
10477
10478 static void
10479 process_die (struct die_info *die, struct dwarf2_cu *cu)
10480 {
10481   process_die_scope scope (die, cu);
10482
10483   switch (die->tag)
10484     {
10485     case DW_TAG_padding:
10486       break;
10487     case DW_TAG_compile_unit:
10488     case DW_TAG_partial_unit:
10489       read_file_scope (die, cu);
10490       break;
10491     case DW_TAG_type_unit:
10492       read_type_unit_scope (die, cu);
10493       break;
10494     case DW_TAG_subprogram:
10495     case DW_TAG_inlined_subroutine:
10496       read_func_scope (die, cu);
10497       break;
10498     case DW_TAG_lexical_block:
10499     case DW_TAG_try_block:
10500     case DW_TAG_catch_block:
10501       read_lexical_block_scope (die, cu);
10502       break;
10503     case DW_TAG_call_site:
10504     case DW_TAG_GNU_call_site:
10505       read_call_site_scope (die, cu);
10506       break;
10507     case DW_TAG_class_type:
10508     case DW_TAG_interface_type:
10509     case DW_TAG_structure_type:
10510     case DW_TAG_union_type:
10511       process_structure_scope (die, cu);
10512       break;
10513     case DW_TAG_enumeration_type:
10514       process_enumeration_scope (die, cu);
10515       break;
10516
10517     /* These dies have a type, but processing them does not create
10518        a symbol or recurse to process the children.  Therefore we can
10519        read them on-demand through read_type_die.  */
10520     case DW_TAG_subroutine_type:
10521     case DW_TAG_set_type:
10522     case DW_TAG_array_type:
10523     case DW_TAG_pointer_type:
10524     case DW_TAG_ptr_to_member_type:
10525     case DW_TAG_reference_type:
10526     case DW_TAG_rvalue_reference_type:
10527     case DW_TAG_string_type:
10528       break;
10529
10530     case DW_TAG_base_type:
10531     case DW_TAG_subrange_type:
10532     case DW_TAG_typedef:
10533       /* Add a typedef symbol for the type definition, if it has a
10534          DW_AT_name.  */
10535       new_symbol (die, read_type_die (die, cu), cu);
10536       break;
10537     case DW_TAG_common_block:
10538       read_common_block (die, cu);
10539       break;
10540     case DW_TAG_common_inclusion:
10541       break;
10542     case DW_TAG_namespace:
10543       cu->processing_has_namespace_info = 1;
10544       read_namespace (die, cu);
10545       break;
10546     case DW_TAG_module:
10547       cu->processing_has_namespace_info = 1;
10548       read_module (die, cu);
10549       break;
10550     case DW_TAG_imported_declaration:
10551       cu->processing_has_namespace_info = 1;
10552       if (read_namespace_alias (die, cu))
10553         break;
10554       /* The declaration is not a global namespace alias.  */
10555       /* Fall through.  */
10556     case DW_TAG_imported_module:
10557       cu->processing_has_namespace_info = 1;
10558       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
10559                                  || cu->language != language_fortran))
10560         complaint (_("Tag '%s' has unexpected children"),
10561                    dwarf_tag_name (die->tag));
10562       read_import_statement (die, cu);
10563       break;
10564
10565     case DW_TAG_imported_unit:
10566       process_imported_unit_die (die, cu);
10567       break;
10568
10569     case DW_TAG_variable:
10570       read_variable (die, cu);
10571       break;
10572
10573     default:
10574       new_symbol (die, NULL, cu);
10575       break;
10576     }
10577 }
10578 \f
10579 /* DWARF name computation.  */
10580
10581 /* A helper function for dwarf2_compute_name which determines whether DIE
10582    needs to have the name of the scope prepended to the name listed in the
10583    die.  */
10584
10585 static int
10586 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
10587 {
10588   struct attribute *attr;
10589
10590   switch (die->tag)
10591     {
10592     case DW_TAG_namespace:
10593     case DW_TAG_typedef:
10594     case DW_TAG_class_type:
10595     case DW_TAG_interface_type:
10596     case DW_TAG_structure_type:
10597     case DW_TAG_union_type:
10598     case DW_TAG_enumeration_type:
10599     case DW_TAG_enumerator:
10600     case DW_TAG_subprogram:
10601     case DW_TAG_inlined_subroutine:
10602     case DW_TAG_member:
10603     case DW_TAG_imported_declaration:
10604       return 1;
10605
10606     case DW_TAG_variable:
10607     case DW_TAG_constant:
10608       /* We only need to prefix "globally" visible variables.  These include
10609          any variable marked with DW_AT_external or any variable that
10610          lives in a namespace.  [Variables in anonymous namespaces
10611          require prefixing, but they are not DW_AT_external.]  */
10612
10613       if (dwarf2_attr (die, DW_AT_specification, cu))
10614         {
10615           struct dwarf2_cu *spec_cu = cu;
10616
10617           return die_needs_namespace (die_specification (die, &spec_cu),
10618                                       spec_cu);
10619         }
10620
10621       attr = dwarf2_attr (die, DW_AT_external, cu);
10622       if (attr == NULL && die->parent->tag != DW_TAG_namespace
10623           && die->parent->tag != DW_TAG_module)
10624         return 0;
10625       /* A variable in a lexical block of some kind does not need a
10626          namespace, even though in C++ such variables may be external
10627          and have a mangled name.  */
10628       if (die->parent->tag ==  DW_TAG_lexical_block
10629           || die->parent->tag ==  DW_TAG_try_block
10630           || die->parent->tag ==  DW_TAG_catch_block
10631           || die->parent->tag == DW_TAG_subprogram)
10632         return 0;
10633       return 1;
10634
10635     default:
10636       return 0;
10637     }
10638 }
10639
10640 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
10641    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10642    defined for the given DIE.  */
10643
10644 static struct attribute *
10645 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
10646 {
10647   struct attribute *attr;
10648
10649   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
10650   if (attr == NULL)
10651     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
10652
10653   return attr;
10654 }
10655
10656 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
10657    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
10658    defined for the given DIE.  */
10659
10660 static const char *
10661 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
10662 {
10663   const char *linkage_name;
10664
10665   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
10666   if (linkage_name == NULL)
10667     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
10668
10669   return linkage_name;
10670 }
10671
10672 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
10673    compute the physname for the object, which include a method's:
10674    - formal parameters (C++),
10675    - receiver type (Go),
10676
10677    The term "physname" is a bit confusing.
10678    For C++, for example, it is the demangled name.
10679    For Go, for example, it's the mangled name.
10680
10681    For Ada, return the DIE's linkage name rather than the fully qualified
10682    name.  PHYSNAME is ignored..
10683
10684    The result is allocated on the objfile_obstack and canonicalized.  */
10685
10686 static const char *
10687 dwarf2_compute_name (const char *name,
10688                      struct die_info *die, struct dwarf2_cu *cu,
10689                      int physname)
10690 {
10691   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10692
10693   if (name == NULL)
10694     name = dwarf2_name (die, cu);
10695
10696   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
10697      but otherwise compute it by typename_concat inside GDB.
10698      FIXME: Actually this is not really true, or at least not always true.
10699      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
10700      Fortran names because there is no mangling standard.  So new_symbol
10701      will set the demangled name to the result of dwarf2_full_name, and it is
10702      the demangled name that GDB uses if it exists.  */
10703   if (cu->language == language_ada
10704       || (cu->language == language_fortran && physname))
10705     {
10706       /* For Ada unit, we prefer the linkage name over the name, as
10707          the former contains the exported name, which the user expects
10708          to be able to reference.  Ideally, we want the user to be able
10709          to reference this entity using either natural or linkage name,
10710          but we haven't started looking at this enhancement yet.  */
10711       const char *linkage_name = dw2_linkage_name (die, cu);
10712
10713       if (linkage_name != NULL)
10714         return linkage_name;
10715     }
10716
10717   /* These are the only languages we know how to qualify names in.  */
10718   if (name != NULL
10719       && (cu->language == language_cplus
10720           || cu->language == language_fortran || cu->language == language_d
10721           || cu->language == language_rust))
10722     {
10723       if (die_needs_namespace (die, cu))
10724         {
10725           const char *prefix;
10726           const char *canonical_name = NULL;
10727
10728           string_file buf;
10729
10730           prefix = determine_prefix (die, cu);
10731           if (*prefix != '\0')
10732             {
10733               char *prefixed_name = typename_concat (NULL, prefix, name,
10734                                                      physname, cu);
10735
10736               buf.puts (prefixed_name);
10737               xfree (prefixed_name);
10738             }
10739           else
10740             buf.puts (name);
10741
10742           /* Template parameters may be specified in the DIE's DW_AT_name, or
10743              as children with DW_TAG_template_type_param or
10744              DW_TAG_value_type_param.  If the latter, add them to the name
10745              here.  If the name already has template parameters, then
10746              skip this step; some versions of GCC emit both, and
10747              it is more efficient to use the pre-computed name.
10748
10749              Something to keep in mind about this process: it is very
10750              unlikely, or in some cases downright impossible, to produce
10751              something that will match the mangled name of a function.
10752              If the definition of the function has the same debug info,
10753              we should be able to match up with it anyway.  But fallbacks
10754              using the minimal symbol, for instance to find a method
10755              implemented in a stripped copy of libstdc++, will not work.
10756              If we do not have debug info for the definition, we will have to
10757              match them up some other way.
10758
10759              When we do name matching there is a related problem with function
10760              templates; two instantiated function templates are allowed to
10761              differ only by their return types, which we do not add here.  */
10762
10763           if (cu->language == language_cplus && strchr (name, '<') == NULL)
10764             {
10765               struct attribute *attr;
10766               struct die_info *child;
10767               int first = 1;
10768
10769               die->building_fullname = 1;
10770
10771               for (child = die->child; child != NULL; child = child->sibling)
10772                 {
10773                   struct type *type;
10774                   LONGEST value;
10775                   const gdb_byte *bytes;
10776                   struct dwarf2_locexpr_baton *baton;
10777                   struct value *v;
10778
10779                   if (child->tag != DW_TAG_template_type_param
10780                       && child->tag != DW_TAG_template_value_param)
10781                     continue;
10782
10783                   if (first)
10784                     {
10785                       buf.puts ("<");
10786                       first = 0;
10787                     }
10788                   else
10789                     buf.puts (", ");
10790
10791                   attr = dwarf2_attr (child, DW_AT_type, cu);
10792                   if (attr == NULL)
10793                     {
10794                       complaint (_("template parameter missing DW_AT_type"));
10795                       buf.puts ("UNKNOWN_TYPE");
10796                       continue;
10797                     }
10798                   type = die_type (child, cu);
10799
10800                   if (child->tag == DW_TAG_template_type_param)
10801                     {
10802                       c_print_type (type, "", &buf, -1, 0, cu->language,
10803                                     &type_print_raw_options);
10804                       continue;
10805                     }
10806
10807                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
10808                   if (attr == NULL)
10809                     {
10810                       complaint (_("template parameter missing "
10811                                    "DW_AT_const_value"));
10812                       buf.puts ("UNKNOWN_VALUE");
10813                       continue;
10814                     }
10815
10816                   dwarf2_const_value_attr (attr, type, name,
10817                                            &cu->comp_unit_obstack, cu,
10818                                            &value, &bytes, &baton);
10819
10820                   if (TYPE_NOSIGN (type))
10821                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
10822                        changed, this can use value_print instead.  */
10823                     c_printchar (value, type, &buf);
10824                   else
10825                     {
10826                       struct value_print_options opts;
10827
10828                       if (baton != NULL)
10829                         v = dwarf2_evaluate_loc_desc (type, NULL,
10830                                                       baton->data,
10831                                                       baton->size,
10832                                                       baton->per_cu);
10833                       else if (bytes != NULL)
10834                         {
10835                           v = allocate_value (type);
10836                           memcpy (value_contents_writeable (v), bytes,
10837                                   TYPE_LENGTH (type));
10838                         }
10839                       else
10840                         v = value_from_longest (type, value);
10841
10842                       /* Specify decimal so that we do not depend on
10843                          the radix.  */
10844                       get_formatted_print_options (&opts, 'd');
10845                       opts.raw = 1;
10846                       value_print (v, &buf, &opts);
10847                       release_value (v);
10848                     }
10849                 }
10850
10851               die->building_fullname = 0;
10852
10853               if (!first)
10854                 {
10855                   /* Close the argument list, with a space if necessary
10856                      (nested templates).  */
10857                   if (!buf.empty () && buf.string ().back () == '>')
10858                     buf.puts (" >");
10859                   else
10860                     buf.puts (">");
10861                 }
10862             }
10863
10864           /* For C++ methods, append formal parameter type
10865              information, if PHYSNAME.  */
10866
10867           if (physname && die->tag == DW_TAG_subprogram
10868               && cu->language == language_cplus)
10869             {
10870               struct type *type = read_type_die (die, cu);
10871
10872               c_type_print_args (type, &buf, 1, cu->language,
10873                                  &type_print_raw_options);
10874
10875               if (cu->language == language_cplus)
10876                 {
10877                   /* Assume that an artificial first parameter is
10878                      "this", but do not crash if it is not.  RealView
10879                      marks unnamed (and thus unused) parameters as
10880                      artificial; there is no way to differentiate
10881                      the two cases.  */
10882                   if (TYPE_NFIELDS (type) > 0
10883                       && TYPE_FIELD_ARTIFICIAL (type, 0)
10884                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
10885                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
10886                                                                         0))))
10887                     buf.puts (" const");
10888                 }
10889             }
10890
10891           const std::string &intermediate_name = buf.string ();
10892
10893           if (cu->language == language_cplus)
10894             canonical_name
10895               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
10896                                           &objfile->per_bfd->storage_obstack);
10897
10898           /* If we only computed INTERMEDIATE_NAME, or if
10899              INTERMEDIATE_NAME is already canonical, then we need to
10900              copy it to the appropriate obstack.  */
10901           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
10902             name = ((const char *)
10903                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
10904                                    intermediate_name.c_str (),
10905                                    intermediate_name.length ()));
10906           else
10907             name = canonical_name;
10908         }
10909     }
10910
10911   return name;
10912 }
10913
10914 /* Return the fully qualified name of DIE, based on its DW_AT_name.
10915    If scope qualifiers are appropriate they will be added.  The result
10916    will be allocated on the storage_obstack, or NULL if the DIE does
10917    not have a name.  NAME may either be from a previous call to
10918    dwarf2_name or NULL.
10919
10920    The output string will be canonicalized (if C++).  */
10921
10922 static const char *
10923 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10924 {
10925   return dwarf2_compute_name (name, die, cu, 0);
10926 }
10927
10928 /* Construct a physname for the given DIE in CU.  NAME may either be
10929    from a previous call to dwarf2_name or NULL.  The result will be
10930    allocated on the objfile_objstack or NULL if the DIE does not have a
10931    name.
10932
10933    The output string will be canonicalized (if C++).  */
10934
10935 static const char *
10936 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
10937 {
10938   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
10939   const char *retval, *mangled = NULL, *canon = NULL;
10940   int need_copy = 1;
10941
10942   /* In this case dwarf2_compute_name is just a shortcut not building anything
10943      on its own.  */
10944   if (!die_needs_namespace (die, cu))
10945     return dwarf2_compute_name (name, die, cu, 1);
10946
10947   mangled = dw2_linkage_name (die, cu);
10948
10949   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
10950      See https://github.com/rust-lang/rust/issues/32925.  */
10951   if (cu->language == language_rust && mangled != NULL
10952       && strchr (mangled, '{') != NULL)
10953     mangled = NULL;
10954
10955   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
10956      has computed.  */
10957   gdb::unique_xmalloc_ptr<char> demangled;
10958   if (mangled != NULL)
10959     {
10960
10961       if (language_def (cu->language)->la_store_sym_names_in_linkage_form_p)
10962         {
10963           /* Do nothing (do not demangle the symbol name).  */
10964         }
10965       else if (cu->language == language_go)
10966         {
10967           /* This is a lie, but we already lie to the caller new_symbol.
10968              new_symbol assumes we return the mangled name.
10969              This just undoes that lie until things are cleaned up.  */
10970         }
10971       else
10972         {
10973           /* Use DMGL_RET_DROP for C++ template functions to suppress
10974              their return type.  It is easier for GDB users to search
10975              for such functions as `name(params)' than `long name(params)'.
10976              In such case the minimal symbol names do not match the full
10977              symbol names but for template functions there is never a need
10978              to look up their definition from their declaration so
10979              the only disadvantage remains the minimal symbol variant
10980              `long name(params)' does not have the proper inferior type.  */
10981           demangled.reset (gdb_demangle (mangled,
10982                                          (DMGL_PARAMS | DMGL_ANSI
10983                                           | DMGL_RET_DROP)));
10984         }
10985       if (demangled)
10986         canon = demangled.get ();
10987       else
10988         {
10989           canon = mangled;
10990           need_copy = 0;
10991         }
10992     }
10993
10994   if (canon == NULL || check_physname)
10995     {
10996       const char *physname = dwarf2_compute_name (name, die, cu, 1);
10997
10998       if (canon != NULL && strcmp (physname, canon) != 0)
10999         {
11000           /* It may not mean a bug in GDB.  The compiler could also
11001              compute DW_AT_linkage_name incorrectly.  But in such case
11002              GDB would need to be bug-to-bug compatible.  */
11003
11004           complaint (_("Computed physname <%s> does not match demangled <%s> "
11005                        "(from linkage <%s>) - DIE at %s [in module %s]"),
11006                      physname, canon, mangled, sect_offset_str (die->sect_off),
11007                      objfile_name (objfile));
11008
11009           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
11010              is available here - over computed PHYSNAME.  It is safer
11011              against both buggy GDB and buggy compilers.  */
11012
11013           retval = canon;
11014         }
11015       else
11016         {
11017           retval = physname;
11018           need_copy = 0;
11019         }
11020     }
11021   else
11022     retval = canon;
11023
11024   if (need_copy)
11025     retval = ((const char *)
11026               obstack_copy0 (&objfile->per_bfd->storage_obstack,
11027                              retval, strlen (retval)));
11028
11029   return retval;
11030 }
11031
11032 /* Inspect DIE in CU for a namespace alias.  If one exists, record
11033    a new symbol for it.
11034
11035    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
11036
11037 static int
11038 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
11039 {
11040   struct attribute *attr;
11041
11042   /* If the die does not have a name, this is not a namespace
11043      alias.  */
11044   attr = dwarf2_attr (die, DW_AT_name, cu);
11045   if (attr != NULL)
11046     {
11047       int num;
11048       struct die_info *d = die;
11049       struct dwarf2_cu *imported_cu = cu;
11050
11051       /* If the compiler has nested DW_AT_imported_declaration DIEs,
11052          keep inspecting DIEs until we hit the underlying import.  */
11053 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
11054       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
11055         {
11056           attr = dwarf2_attr (d, DW_AT_import, cu);
11057           if (attr == NULL)
11058             break;
11059
11060           d = follow_die_ref (d, attr, &imported_cu);
11061           if (d->tag != DW_TAG_imported_declaration)
11062             break;
11063         }
11064
11065       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
11066         {
11067           complaint (_("DIE at %s has too many recursively imported "
11068                        "declarations"), sect_offset_str (d->sect_off));
11069           return 0;
11070         }
11071
11072       if (attr != NULL)
11073         {
11074           struct type *type;
11075           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
11076
11077           type = get_die_type_at_offset (sect_off, cu->per_cu);
11078           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
11079             {
11080               /* This declaration is a global namespace alias.  Add
11081                  a symbol for it whose type is the aliased namespace.  */
11082               new_symbol (die, type, cu);
11083               return 1;
11084             }
11085         }
11086     }
11087
11088   return 0;
11089 }
11090
11091 /* Return the using directives repository (global or local?) to use in the
11092    current context for LANGUAGE.
11093
11094    For Ada, imported declarations can materialize renamings, which *may* be
11095    global.  However it is impossible (for now?) in DWARF to distinguish
11096    "external" imported declarations and "static" ones.  As all imported
11097    declarations seem to be static in all other languages, make them all CU-wide
11098    global only in Ada.  */
11099
11100 static struct using_direct **
11101 using_directives (enum language language)
11102 {
11103   if (language == language_ada && outermost_context_p ())
11104     return get_global_using_directives ();
11105   else
11106     return get_local_using_directives ();
11107 }
11108
11109 /* Read the import statement specified by the given die and record it.  */
11110
11111 static void
11112 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
11113 {
11114   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
11115   struct attribute *import_attr;
11116   struct die_info *imported_die, *child_die;
11117   struct dwarf2_cu *imported_cu;
11118   const char *imported_name;
11119   const char *imported_name_prefix;
11120   const char *canonical_name;
11121   const char *import_alias;
11122   const char *imported_declaration = NULL;
11123   const char *import_prefix;
11124   std::vector<const char *> excludes;
11125
11126   import_attr = dwarf2_attr (die, DW_AT_import, cu);
11127   if (import_attr == NULL)
11128     {
11129       complaint (_("Tag '%s' has no DW_AT_import"),
11130                  dwarf_tag_name (die->tag));
11131       return;
11132     }
11133
11134   imported_cu = cu;
11135   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
11136   imported_name = dwarf2_name (imported_die, imported_cu);
11137   if (imported_name == NULL)
11138     {
11139       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
11140
11141         The import in the following code:
11142         namespace A
11143           {
11144             typedef int B;
11145           }
11146
11147         int main ()
11148           {
11149             using A::B;
11150             B b;
11151             return b;
11152           }
11153
11154         ...
11155          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
11156             <52>   DW_AT_decl_file   : 1
11157             <53>   DW_AT_decl_line   : 6
11158             <54>   DW_AT_import      : <0x75>
11159          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
11160             <59>   DW_AT_name        : B
11161             <5b>   DW_AT_decl_file   : 1
11162             <5c>   DW_AT_decl_line   : 2
11163             <5d>   DW_AT_type        : <0x6e>
11164         ...
11165          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
11166             <76>   DW_AT_byte_size   : 4
11167             <77>   DW_AT_encoding    : 5        (signed)
11168
11169         imports the wrong die ( 0x75 instead of 0x58 ).
11170         This case will be ignored until the gcc bug is fixed.  */
11171       return;
11172     }
11173
11174   /* Figure out the local name after import.  */
11175   import_alias = dwarf2_name (die, cu);
11176
11177   /* Figure out where the statement is being imported to.  */
11178   import_prefix = determine_prefix (die, cu);
11179
11180   /* Figure out what the scope of the imported die is and prepend it
11181      to the name of the imported die.  */
11182   imported_name_prefix = determine_prefix (imported_die, imported_cu);
11183
11184   if (imported_die->tag != DW_TAG_namespace
11185       && imported_die->tag != DW_TAG_module)
11186     {
11187       imported_declaration = imported_name;
11188       canonical_name = imported_name_prefix;
11189     }
11190   else if (strlen (imported_name_prefix) > 0)
11191     canonical_name = obconcat (&objfile->objfile_obstack,
11192                                imported_name_prefix,
11193                                (cu->language == language_d ? "." : "::"),
11194                                imported_name, (char *) NULL);
11195   else
11196     canonical_name = imported_name;
11197
11198   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
11199     for (child_die = die->child; child_die && child_die->tag;
11200          child_die = sibling_die (child_die))
11201       {
11202         /* DWARF-4: A Fortran use statement with a “rename list” may be
11203            represented by an imported module entry with an import attribute
11204            referring to the module and owned entries corresponding to those
11205            entities that are renamed as part of being imported.  */
11206
11207         if (child_die->tag != DW_TAG_imported_declaration)
11208           {
11209             complaint (_("child DW_TAG_imported_declaration expected "
11210                          "- DIE at %s [in module %s]"),
11211                        sect_offset_str (child_die->sect_off),
11212                        objfile_name (objfile));
11213             continue;
11214           }
11215
11216         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
11217         if (import_attr == NULL)
11218           {
11219             complaint (_("Tag '%s' has no DW_AT_import"),
11220                        dwarf_tag_name (child_die->tag));
11221             continue;
11222           }
11223
11224         imported_cu = cu;
11225         imported_die = follow_die_ref_or_sig (child_die, import_attr,
11226                                               &imported_cu);
11227         imported_name = dwarf2_name (imported_die, imported_cu);
11228         if (imported_name == NULL)
11229           {
11230             complaint (_("child DW_TAG_imported_declaration has unknown "
11231                          "imported name - DIE at %s [in module %s]"),
11232                        sect_offset_str (child_die->sect_off),
11233                        objfile_name (objfile));
11234             continue;
11235           }
11236
11237         excludes.push_back (imported_name);
11238
11239         process_die (child_die, cu);
11240       }
11241
11242   add_using_directive (using_directives (cu->language),
11243                        import_prefix,
11244                        canonical_name,
11245                        import_alias,
11246                        imported_declaration,
11247                        excludes,
11248                        0,
11249                        &objfile->objfile_obstack);
11250 }
11251
11252 /* ICC<14 does not output the required DW_AT_declaration on incomplete
11253    types, but gives them a size of zero.  Starting with version 14,
11254    ICC is compatible with GCC.  */
11255
11256 static int
11257 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
11258 {
11259   if (!cu->checked_producer)
11260     check_producer (cu);
11261
11262   return cu->producer_is_icc_lt_14;
11263 }
11264
11265 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
11266    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
11267    this, it was first present in GCC release 4.3.0.  */
11268
11269 static int
11270 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
11271 {
11272   if (!cu->checked_producer)
11273     check_producer (cu);
11274
11275   return cu->producer_is_gcc_lt_4_3;
11276 }
11277
11278 static file_and_directory
11279 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
11280 {
11281   file_and_directory res;
11282
11283   /* Find the filename.  Do not use dwarf2_name here, since the filename
11284      is not a source language identifier.  */
11285   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
11286   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
11287
11288   if (res.comp_dir == NULL
11289       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
11290       && IS_ABSOLUTE_PATH (res.name))
11291     {
11292       res.comp_dir_storage = ldirname (res.name);
11293       if (!res.comp_dir_storage.empty ())
11294         res.comp_dir = res.comp_dir_storage.c_str ();
11295     }
11296   if (res.comp_dir != NULL)
11297     {
11298       /* Irix 6.2 native cc prepends <machine>.: to the compilation
11299          directory, get rid of it.  */
11300       const char *cp = strchr (res.comp_dir, ':');
11301
11302       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
11303         res.comp_dir = cp + 1;
11304     }
11305
11306   if (res.name == NULL)
11307     res.name = "<unknown>";
11308
11309   return res;
11310 }
11311
11312 /* Handle DW_AT_stmt_list for a compilation unit.
11313    DIE is the DW_TAG_compile_unit die for CU.
11314    COMP_DIR is the compilation directory.  LOWPC is passed to
11315    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
11316
11317 static void
11318 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
11319                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
11320 {
11321   struct dwarf2_per_objfile *dwarf2_per_objfile
11322     = cu->per_cu->dwarf2_per_objfile;
11323   struct objfile *objfile = dwarf2_per_objfile->objfile;
11324   struct attribute *attr;
11325   struct line_header line_header_local;
11326   hashval_t line_header_local_hash;
11327   void **slot;
11328   int decode_mapping;
11329
11330   gdb_assert (! cu->per_cu->is_debug_types);
11331
11332   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11333   if (attr == NULL)
11334     return;
11335
11336   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11337
11338   /* The line header hash table is only created if needed (it exists to
11339      prevent redundant reading of the line table for partial_units).
11340      If we're given a partial_unit, we'll need it.  If we're given a
11341      compile_unit, then use the line header hash table if it's already
11342      created, but don't create one just yet.  */
11343
11344   if (dwarf2_per_objfile->line_header_hash == NULL
11345       && die->tag == DW_TAG_partial_unit)
11346     {
11347       dwarf2_per_objfile->line_header_hash
11348         = htab_create_alloc_ex (127, line_header_hash_voidp,
11349                                 line_header_eq_voidp,
11350                                 free_line_header_voidp,
11351                                 &objfile->objfile_obstack,
11352                                 hashtab_obstack_allocate,
11353                                 dummy_obstack_deallocate);
11354     }
11355
11356   line_header_local.sect_off = line_offset;
11357   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
11358   line_header_local_hash = line_header_hash (&line_header_local);
11359   if (dwarf2_per_objfile->line_header_hash != NULL)
11360     {
11361       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11362                                        &line_header_local,
11363                                        line_header_local_hash, NO_INSERT);
11364
11365       /* For DW_TAG_compile_unit we need info like symtab::linetable which
11366          is not present in *SLOT (since if there is something in *SLOT then
11367          it will be for a partial_unit).  */
11368       if (die->tag == DW_TAG_partial_unit && slot != NULL)
11369         {
11370           gdb_assert (*slot != NULL);
11371           cu->line_header = (struct line_header *) *slot;
11372           return;
11373         }
11374     }
11375
11376   /* dwarf_decode_line_header does not yet provide sufficient information.
11377      We always have to call also dwarf_decode_lines for it.  */
11378   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
11379   if (lh == NULL)
11380     return;
11381
11382   cu->line_header = lh.release ();
11383   cu->line_header_die_owner = die;
11384
11385   if (dwarf2_per_objfile->line_header_hash == NULL)
11386     slot = NULL;
11387   else
11388     {
11389       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
11390                                        &line_header_local,
11391                                        line_header_local_hash, INSERT);
11392       gdb_assert (slot != NULL);
11393     }
11394   if (slot != NULL && *slot == NULL)
11395     {
11396       /* This newly decoded line number information unit will be owned
11397          by line_header_hash hash table.  */
11398       *slot = cu->line_header;
11399       cu->line_header_die_owner = NULL;
11400     }
11401   else
11402     {
11403       /* We cannot free any current entry in (*slot) as that struct line_header
11404          may be already used by multiple CUs.  Create only temporary decoded
11405          line_header for this CU - it may happen at most once for each line
11406          number information unit.  And if we're not using line_header_hash
11407          then this is what we want as well.  */
11408       gdb_assert (die->tag != DW_TAG_partial_unit);
11409     }
11410   decode_mapping = (die->tag != DW_TAG_partial_unit);
11411   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
11412                       decode_mapping);
11413
11414 }
11415
11416 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
11417
11418 static void
11419 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
11420 {
11421   struct dwarf2_per_objfile *dwarf2_per_objfile
11422     = cu->per_cu->dwarf2_per_objfile;
11423   struct objfile *objfile = dwarf2_per_objfile->objfile;
11424   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11425   CORE_ADDR lowpc = ((CORE_ADDR) -1);
11426   CORE_ADDR highpc = ((CORE_ADDR) 0);
11427   struct attribute *attr;
11428   struct die_info *child_die;
11429   CORE_ADDR baseaddr;
11430
11431   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11432
11433   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
11434
11435   /* If we didn't find a lowpc, set it to highpc to avoid complaints
11436      from finish_block.  */
11437   if (lowpc == ((CORE_ADDR) -1))
11438     lowpc = highpc;
11439   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11440
11441   file_and_directory fnd = find_file_and_directory (die, cu);
11442
11443   prepare_one_comp_unit (cu, die, cu->language);
11444
11445   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
11446      standardised yet.  As a workaround for the language detection we fall
11447      back to the DW_AT_producer string.  */
11448   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
11449     cu->language = language_opencl;
11450
11451   /* Similar hack for Go.  */
11452   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
11453     set_cu_language (DW_LANG_Go, cu);
11454
11455   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
11456
11457   /* Decode line number information if present.  We do this before
11458      processing child DIEs, so that the line header table is available
11459      for DW_AT_decl_file.  */
11460   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
11461
11462   /* Process all dies in compilation unit.  */
11463   if (die->child != NULL)
11464     {
11465       child_die = die->child;
11466       while (child_die && child_die->tag)
11467         {
11468           process_die (child_die, cu);
11469           child_die = sibling_die (child_die);
11470         }
11471     }
11472
11473   /* Decode macro information, if present.  Dwarf 2 macro information
11474      refers to information in the line number info statement program
11475      header, so we can only read it if we've read the header
11476      successfully.  */
11477   attr = dwarf2_attr (die, DW_AT_macros, cu);
11478   if (attr == NULL)
11479     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
11480   if (attr && cu->line_header)
11481     {
11482       if (dwarf2_attr (die, DW_AT_macro_info, cu))
11483         complaint (_("CU refers to both DW_AT_macros and DW_AT_macro_info"));
11484
11485       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
11486     }
11487   else
11488     {
11489       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
11490       if (attr && cu->line_header)
11491         {
11492           unsigned int macro_offset = DW_UNSND (attr);
11493
11494           dwarf_decode_macros (cu, macro_offset, 0);
11495         }
11496     }
11497 }
11498
11499 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
11500    Create the set of symtabs used by this TU, or if this TU is sharing
11501    symtabs with another TU and the symtabs have already been created
11502    then restore those symtabs in the line header.
11503    We don't need the pc/line-number mapping for type units.  */
11504
11505 static void
11506 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
11507 {
11508   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
11509   struct type_unit_group *tu_group;
11510   int first_time;
11511   struct attribute *attr;
11512   unsigned int i;
11513   struct signatured_type *sig_type;
11514
11515   gdb_assert (per_cu->is_debug_types);
11516   sig_type = (struct signatured_type *) per_cu;
11517
11518   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
11519
11520   /* If we're using .gdb_index (includes -readnow) then
11521      per_cu->type_unit_group may not have been set up yet.  */
11522   if (sig_type->type_unit_group == NULL)
11523     sig_type->type_unit_group = get_type_unit_group (cu, attr);
11524   tu_group = sig_type->type_unit_group;
11525
11526   /* If we've already processed this stmt_list there's no real need to
11527      do it again, we could fake it and just recreate the part we need
11528      (file name,index -> symtab mapping).  If data shows this optimization
11529      is useful we can do it then.  */
11530   first_time = tu_group->compunit_symtab == NULL;
11531
11532   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
11533      debug info.  */
11534   line_header_up lh;
11535   if (attr != NULL)
11536     {
11537       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
11538       lh = dwarf_decode_line_header (line_offset, cu);
11539     }
11540   if (lh == NULL)
11541     {
11542       if (first_time)
11543         dwarf2_start_symtab (cu, "", NULL, 0);
11544       else
11545         {
11546           gdb_assert (tu_group->symtabs == NULL);
11547           restart_symtab (tu_group->compunit_symtab, "", 0);
11548         }
11549       return;
11550     }
11551
11552   cu->line_header = lh.release ();
11553   cu->line_header_die_owner = die;
11554
11555   if (first_time)
11556     {
11557       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
11558
11559       /* Note: We don't assign tu_group->compunit_symtab yet because we're
11560          still initializing it, and our caller (a few levels up)
11561          process_full_type_unit still needs to know if this is the first
11562          time.  */
11563
11564       tu_group->num_symtabs = cu->line_header->file_names.size ();
11565       tu_group->symtabs = XNEWVEC (struct symtab *,
11566                                    cu->line_header->file_names.size ());
11567
11568       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11569         {
11570           file_entry &fe = cu->line_header->file_names[i];
11571
11572           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
11573
11574           if (get_current_subfile ()->symtab == NULL)
11575             {
11576               /* NOTE: start_subfile will recognize when it's been
11577                  passed a file it has already seen.  So we can't
11578                  assume there's a simple mapping from
11579                  cu->line_header->file_names to subfiles, plus
11580                  cu->line_header->file_names may contain dups.  */
11581               get_current_subfile ()->symtab
11582                 = allocate_symtab (cust, get_current_subfile ()->name);
11583             }
11584
11585           fe.symtab = get_current_subfile ()->symtab;
11586           tu_group->symtabs[i] = fe.symtab;
11587         }
11588     }
11589   else
11590     {
11591       restart_symtab (tu_group->compunit_symtab, "", 0);
11592
11593       for (i = 0; i < cu->line_header->file_names.size (); ++i)
11594         {
11595           file_entry &fe = cu->line_header->file_names[i];
11596
11597           fe.symtab = tu_group->symtabs[i];
11598         }
11599     }
11600
11601   /* The main symtab is allocated last.  Type units don't have DW_AT_name
11602      so they don't have a "real" (so to speak) symtab anyway.
11603      There is later code that will assign the main symtab to all symbols
11604      that don't have one.  We need to handle the case of a symbol with a
11605      missing symtab (DW_AT_decl_file) anyway.  */
11606 }
11607
11608 /* Process DW_TAG_type_unit.
11609    For TUs we want to skip the first top level sibling if it's not the
11610    actual type being defined by this TU.  In this case the first top
11611    level sibling is there to provide context only.  */
11612
11613 static void
11614 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
11615 {
11616   struct die_info *child_die;
11617
11618   prepare_one_comp_unit (cu, die, language_minimal);
11619
11620   /* Initialize (or reinitialize) the machinery for building symtabs.
11621      We do this before processing child DIEs, so that the line header table
11622      is available for DW_AT_decl_file.  */
11623   setup_type_unit_groups (die, cu);
11624
11625   if (die->child != NULL)
11626     {
11627       child_die = die->child;
11628       while (child_die && child_die->tag)
11629         {
11630           process_die (child_die, cu);
11631           child_die = sibling_die (child_die);
11632         }
11633     }
11634 }
11635 \f
11636 /* DWO/DWP files.
11637
11638    http://gcc.gnu.org/wiki/DebugFission
11639    http://gcc.gnu.org/wiki/DebugFissionDWP
11640
11641    To simplify handling of both DWO files ("object" files with the DWARF info)
11642    and DWP files (a file with the DWOs packaged up into one file), we treat
11643    DWP files as having a collection of virtual DWO files.  */
11644
11645 static hashval_t
11646 hash_dwo_file (const void *item)
11647 {
11648   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
11649   hashval_t hash;
11650
11651   hash = htab_hash_string (dwo_file->dwo_name);
11652   if (dwo_file->comp_dir != NULL)
11653     hash += htab_hash_string (dwo_file->comp_dir);
11654   return hash;
11655 }
11656
11657 static int
11658 eq_dwo_file (const void *item_lhs, const void *item_rhs)
11659 {
11660   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
11661   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
11662
11663   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
11664     return 0;
11665   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
11666     return lhs->comp_dir == rhs->comp_dir;
11667   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
11668 }
11669
11670 /* Allocate a hash table for DWO files.  */
11671
11672 static htab_t
11673 allocate_dwo_file_hash_table (struct objfile *objfile)
11674 {
11675   return htab_create_alloc_ex (41,
11676                                hash_dwo_file,
11677                                eq_dwo_file,
11678                                NULL,
11679                                &objfile->objfile_obstack,
11680                                hashtab_obstack_allocate,
11681                                dummy_obstack_deallocate);
11682 }
11683
11684 /* Lookup DWO file DWO_NAME.  */
11685
11686 static void **
11687 lookup_dwo_file_slot (struct dwarf2_per_objfile *dwarf2_per_objfile,
11688                       const char *dwo_name,
11689                       const char *comp_dir)
11690 {
11691   struct dwo_file find_entry;
11692   void **slot;
11693
11694   if (dwarf2_per_objfile->dwo_files == NULL)
11695     dwarf2_per_objfile->dwo_files
11696       = allocate_dwo_file_hash_table (dwarf2_per_objfile->objfile);
11697
11698   memset (&find_entry, 0, sizeof (find_entry));
11699   find_entry.dwo_name = dwo_name;
11700   find_entry.comp_dir = comp_dir;
11701   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
11702
11703   return slot;
11704 }
11705
11706 static hashval_t
11707 hash_dwo_unit (const void *item)
11708 {
11709   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11710
11711   /* This drops the top 32 bits of the id, but is ok for a hash.  */
11712   return dwo_unit->signature;
11713 }
11714
11715 static int
11716 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
11717 {
11718   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
11719   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
11720
11721   /* The signature is assumed to be unique within the DWO file.
11722      So while object file CU dwo_id's always have the value zero,
11723      that's OK, assuming each object file DWO file has only one CU,
11724      and that's the rule for now.  */
11725   return lhs->signature == rhs->signature;
11726 }
11727
11728 /* Allocate a hash table for DWO CUs,TUs.
11729    There is one of these tables for each of CUs,TUs for each DWO file.  */
11730
11731 static htab_t
11732 allocate_dwo_unit_table (struct objfile *objfile)
11733 {
11734   /* Start out with a pretty small number.
11735      Generally DWO files contain only one CU and maybe some TUs.  */
11736   return htab_create_alloc_ex (3,
11737                                hash_dwo_unit,
11738                                eq_dwo_unit,
11739                                NULL,
11740                                &objfile->objfile_obstack,
11741                                hashtab_obstack_allocate,
11742                                dummy_obstack_deallocate);
11743 }
11744
11745 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
11746
11747 struct create_dwo_cu_data
11748 {
11749   struct dwo_file *dwo_file;
11750   struct dwo_unit dwo_unit;
11751 };
11752
11753 /* die_reader_func for create_dwo_cu.  */
11754
11755 static void
11756 create_dwo_cu_reader (const struct die_reader_specs *reader,
11757                       const gdb_byte *info_ptr,
11758                       struct die_info *comp_unit_die,
11759                       int has_children,
11760                       void *datap)
11761 {
11762   struct dwarf2_cu *cu = reader->cu;
11763   sect_offset sect_off = cu->per_cu->sect_off;
11764   struct dwarf2_section_info *section = cu->per_cu->section;
11765   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
11766   struct dwo_file *dwo_file = data->dwo_file;
11767   struct dwo_unit *dwo_unit = &data->dwo_unit;
11768   struct attribute *attr;
11769
11770   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
11771   if (attr == NULL)
11772     {
11773       complaint (_("Dwarf Error: debug entry at offset %s is missing"
11774                    " its dwo_id [in module %s]"),
11775                  sect_offset_str (sect_off), dwo_file->dwo_name);
11776       return;
11777     }
11778
11779   dwo_unit->dwo_file = dwo_file;
11780   dwo_unit->signature = DW_UNSND (attr);
11781   dwo_unit->section = section;
11782   dwo_unit->sect_off = sect_off;
11783   dwo_unit->length = cu->per_cu->length;
11784
11785   if (dwarf_read_debug)
11786     fprintf_unfiltered (gdb_stdlog, "  offset %s, dwo_id %s\n",
11787                         sect_offset_str (sect_off),
11788                         hex_string (dwo_unit->signature));
11789 }
11790
11791 /* Create the dwo_units for the CUs in a DWO_FILE.
11792    Note: This function processes DWO files only, not DWP files.  */
11793
11794 static void
11795 create_cus_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
11796                        struct dwo_file &dwo_file, dwarf2_section_info &section,
11797                        htab_t &cus_htab)
11798 {
11799   struct objfile *objfile = dwarf2_per_objfile->objfile;
11800   const gdb_byte *info_ptr, *end_ptr;
11801
11802   dwarf2_read_section (objfile, &section);
11803   info_ptr = section.buffer;
11804
11805   if (info_ptr == NULL)
11806     return;
11807
11808   if (dwarf_read_debug)
11809     {
11810       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
11811                           get_section_name (&section),
11812                           get_section_file_name (&section));
11813     }
11814
11815   end_ptr = info_ptr + section.size;
11816   while (info_ptr < end_ptr)
11817     {
11818       struct dwarf2_per_cu_data per_cu;
11819       struct create_dwo_cu_data create_dwo_cu_data;
11820       struct dwo_unit *dwo_unit;
11821       void **slot;
11822       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
11823
11824       memset (&create_dwo_cu_data.dwo_unit, 0,
11825               sizeof (create_dwo_cu_data.dwo_unit));
11826       memset (&per_cu, 0, sizeof (per_cu));
11827       per_cu.dwarf2_per_objfile = dwarf2_per_objfile;
11828       per_cu.is_debug_types = 0;
11829       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
11830       per_cu.section = &section;
11831       create_dwo_cu_data.dwo_file = &dwo_file;
11832
11833       init_cutu_and_read_dies_no_follow (
11834           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
11835       info_ptr += per_cu.length;
11836
11837       // If the unit could not be parsed, skip it.
11838       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
11839         continue;
11840
11841       if (cus_htab == NULL)
11842         cus_htab = allocate_dwo_unit_table (objfile);
11843
11844       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11845       *dwo_unit = create_dwo_cu_data.dwo_unit;
11846       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
11847       gdb_assert (slot != NULL);
11848       if (*slot != NULL)
11849         {
11850           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
11851           sect_offset dup_sect_off = dup_cu->sect_off;
11852
11853           complaint (_("debug cu entry at offset %s is duplicate to"
11854                        " the entry at offset %s, signature %s"),
11855                      sect_offset_str (sect_off), sect_offset_str (dup_sect_off),
11856                      hex_string (dwo_unit->signature));
11857         }
11858       *slot = (void *)dwo_unit;
11859     }
11860 }
11861
11862 /* DWP file .debug_{cu,tu}_index section format:
11863    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
11864
11865    DWP Version 1:
11866
11867    Both index sections have the same format, and serve to map a 64-bit
11868    signature to a set of section numbers.  Each section begins with a header,
11869    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
11870    indexes, and a pool of 32-bit section numbers.  The index sections will be
11871    aligned at 8-byte boundaries in the file.
11872
11873    The index section header consists of:
11874
11875     V, 32 bit version number
11876     -, 32 bits unused
11877     N, 32 bit number of compilation units or type units in the index
11878     M, 32 bit number of slots in the hash table
11879
11880    Numbers are recorded using the byte order of the application binary.
11881
11882    The hash table begins at offset 16 in the section, and consists of an array
11883    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
11884    order of the application binary).  Unused slots in the hash table are 0.
11885    (We rely on the extreme unlikeliness of a signature being exactly 0.)
11886
11887    The parallel table begins immediately after the hash table
11888    (at offset 16 + 8 * M from the beginning of the section), and consists of an
11889    array of 32-bit indexes (using the byte order of the application binary),
11890    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
11891    table contains a 32-bit index into the pool of section numbers.  For unused
11892    hash table slots, the corresponding entry in the parallel table will be 0.
11893
11894    The pool of section numbers begins immediately following the hash table
11895    (at offset 16 + 12 * M from the beginning of the section).  The pool of
11896    section numbers consists of an array of 32-bit words (using the byte order
11897    of the application binary).  Each item in the array is indexed starting
11898    from 0.  The hash table entry provides the index of the first section
11899    number in the set.  Additional section numbers in the set follow, and the
11900    set is terminated by a 0 entry (section number 0 is not used in ELF).
11901
11902    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
11903    section must be the first entry in the set, and the .debug_abbrev.dwo must
11904    be the second entry. Other members of the set may follow in any order.
11905
11906    ---
11907
11908    DWP Version 2:
11909
11910    DWP Version 2 combines all the .debug_info, etc. sections into one,
11911    and the entries in the index tables are now offsets into these sections.
11912    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
11913    section.
11914
11915    Index Section Contents:
11916     Header
11917     Hash Table of Signatures   dwp_hash_table.hash_table
11918     Parallel Table of Indices  dwp_hash_table.unit_table
11919     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
11920     Table of Section Sizes     dwp_hash_table.v2.sizes
11921
11922    The index section header consists of:
11923
11924     V, 32 bit version number
11925     L, 32 bit number of columns in the table of section offsets
11926     N, 32 bit number of compilation units or type units in the index
11927     M, 32 bit number of slots in the hash table
11928
11929    Numbers are recorded using the byte order of the application binary.
11930
11931    The hash table has the same format as version 1.
11932    The parallel table of indices has the same format as version 1,
11933    except that the entries are origin-1 indices into the table of sections
11934    offsets and the table of section sizes.
11935
11936    The table of offsets begins immediately following the parallel table
11937    (at offset 16 + 12 * M from the beginning of the section).  The table is
11938    a two-dimensional array of 32-bit words (using the byte order of the
11939    application binary), with L columns and N+1 rows, in row-major order.
11940    Each row in the array is indexed starting from 0.  The first row provides
11941    a key to the remaining rows: each column in this row provides an identifier
11942    for a debug section, and the offsets in the same column of subsequent rows
11943    refer to that section.  The section identifiers are:
11944
11945     DW_SECT_INFO         1  .debug_info.dwo
11946     DW_SECT_TYPES        2  .debug_types.dwo
11947     DW_SECT_ABBREV       3  .debug_abbrev.dwo
11948     DW_SECT_LINE         4  .debug_line.dwo
11949     DW_SECT_LOC          5  .debug_loc.dwo
11950     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
11951     DW_SECT_MACINFO      7  .debug_macinfo.dwo
11952     DW_SECT_MACRO        8  .debug_macro.dwo
11953
11954    The offsets provided by the CU and TU index sections are the base offsets
11955    for the contributions made by each CU or TU to the corresponding section
11956    in the package file.  Each CU and TU header contains an abbrev_offset
11957    field, used to find the abbreviations table for that CU or TU within the
11958    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
11959    be interpreted as relative to the base offset given in the index section.
11960    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
11961    should be interpreted as relative to the base offset for .debug_line.dwo,
11962    and offsets into other debug sections obtained from DWARF attributes should
11963    also be interpreted as relative to the corresponding base offset.
11964
11965    The table of sizes begins immediately following the table of offsets.
11966    Like the table of offsets, it is a two-dimensional array of 32-bit words,
11967    with L columns and N rows, in row-major order.  Each row in the array is
11968    indexed starting from 1 (row 0 is shared by the two tables).
11969
11970    ---
11971
11972    Hash table lookup is handled the same in version 1 and 2:
11973
11974    We assume that N and M will not exceed 2^32 - 1.
11975    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
11976
11977    Given a 64-bit compilation unit signature or a type signature S, an entry
11978    in the hash table is located as follows:
11979
11980    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
11981       the low-order k bits all set to 1.
11982
11983    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
11984
11985    3) If the hash table entry at index H matches the signature, use that
11986       entry.  If the hash table entry at index H is unused (all zeroes),
11987       terminate the search: the signature is not present in the table.
11988
11989    4) Let H = (H + H') modulo M. Repeat at Step 3.
11990
11991    Because M > N and H' and M are relatively prime, the search is guaranteed
11992    to stop at an unused slot or find the match.  */
11993
11994 /* Create a hash table to map DWO IDs to their CU/TU entry in
11995    .debug_{info,types}.dwo in DWP_FILE.
11996    Returns NULL if there isn't one.
11997    Note: This function processes DWP files only, not DWO files.  */
11998
11999 static struct dwp_hash_table *
12000 create_dwp_hash_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
12001                        struct dwp_file *dwp_file, int is_debug_types)
12002 {
12003   struct objfile *objfile = dwarf2_per_objfile->objfile;
12004   bfd *dbfd = dwp_file->dbfd.get ();
12005   const gdb_byte *index_ptr, *index_end;
12006   struct dwarf2_section_info *index;
12007   uint32_t version, nr_columns, nr_units, nr_slots;
12008   struct dwp_hash_table *htab;
12009
12010   if (is_debug_types)
12011     index = &dwp_file->sections.tu_index;
12012   else
12013     index = &dwp_file->sections.cu_index;
12014
12015   if (dwarf2_section_empty_p (index))
12016     return NULL;
12017   dwarf2_read_section (objfile, index);
12018
12019   index_ptr = index->buffer;
12020   index_end = index_ptr + index->size;
12021
12022   version = read_4_bytes (dbfd, index_ptr);
12023   index_ptr += 4;
12024   if (version == 2)
12025     nr_columns = read_4_bytes (dbfd, index_ptr);
12026   else
12027     nr_columns = 0;
12028   index_ptr += 4;
12029   nr_units = read_4_bytes (dbfd, index_ptr);
12030   index_ptr += 4;
12031   nr_slots = read_4_bytes (dbfd, index_ptr);
12032   index_ptr += 4;
12033
12034   if (version != 1 && version != 2)
12035     {
12036       error (_("Dwarf Error: unsupported DWP file version (%s)"
12037                " [in module %s]"),
12038              pulongest (version), dwp_file->name);
12039     }
12040   if (nr_slots != (nr_slots & -nr_slots))
12041     {
12042       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
12043                " is not power of 2 [in module %s]"),
12044              pulongest (nr_slots), dwp_file->name);
12045     }
12046
12047   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
12048   htab->version = version;
12049   htab->nr_columns = nr_columns;
12050   htab->nr_units = nr_units;
12051   htab->nr_slots = nr_slots;
12052   htab->hash_table = index_ptr;
12053   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
12054
12055   /* Exit early if the table is empty.  */
12056   if (nr_slots == 0 || nr_units == 0
12057       || (version == 2 && nr_columns == 0))
12058     {
12059       /* All must be zero.  */
12060       if (nr_slots != 0 || nr_units != 0
12061           || (version == 2 && nr_columns != 0))
12062         {
12063           complaint (_("Empty DWP but nr_slots,nr_units,nr_columns not"
12064                        " all zero [in modules %s]"),
12065                      dwp_file->name);
12066         }
12067       return htab;
12068     }
12069
12070   if (version == 1)
12071     {
12072       htab->section_pool.v1.indices =
12073         htab->unit_table + sizeof (uint32_t) * nr_slots;
12074       /* It's harder to decide whether the section is too small in v1.
12075          V1 is deprecated anyway so we punt.  */
12076     }
12077   else
12078     {
12079       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
12080       int *ids = htab->section_pool.v2.section_ids;
12081       /* Reverse map for error checking.  */
12082       int ids_seen[DW_SECT_MAX + 1];
12083       int i;
12084
12085       if (nr_columns < 2)
12086         {
12087           error (_("Dwarf Error: bad DWP hash table, too few columns"
12088                    " in section table [in module %s]"),
12089                  dwp_file->name);
12090         }
12091       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
12092         {
12093           error (_("Dwarf Error: bad DWP hash table, too many columns"
12094                    " in section table [in module %s]"),
12095                  dwp_file->name);
12096         }
12097       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12098       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
12099       for (i = 0; i < nr_columns; ++i)
12100         {
12101           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
12102
12103           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
12104             {
12105               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
12106                        " in section table [in module %s]"),
12107                      id, dwp_file->name);
12108             }
12109           if (ids_seen[id] != -1)
12110             {
12111               error (_("Dwarf Error: bad DWP hash table, duplicate section"
12112                        " id %d in section table [in module %s]"),
12113                      id, dwp_file->name);
12114             }
12115           ids_seen[id] = i;
12116           ids[i] = id;
12117         }
12118       /* Must have exactly one info or types section.  */
12119       if (((ids_seen[DW_SECT_INFO] != -1)
12120            + (ids_seen[DW_SECT_TYPES] != -1))
12121           != 1)
12122         {
12123           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
12124                    " DWO info/types section [in module %s]"),
12125                  dwp_file->name);
12126         }
12127       /* Must have an abbrev section.  */
12128       if (ids_seen[DW_SECT_ABBREV] == -1)
12129         {
12130           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
12131                    " section [in module %s]"),
12132                  dwp_file->name);
12133         }
12134       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
12135       htab->section_pool.v2.sizes =
12136         htab->section_pool.v2.offsets + (sizeof (uint32_t)
12137                                          * nr_units * nr_columns);
12138       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
12139                                           * nr_units * nr_columns))
12140           > index_end)
12141         {
12142           error (_("Dwarf Error: DWP index section is corrupt (too small)"
12143                    " [in module %s]"),
12144                  dwp_file->name);
12145         }
12146     }
12147
12148   return htab;
12149 }
12150
12151 /* Update SECTIONS with the data from SECTP.
12152
12153    This function is like the other "locate" section routines that are
12154    passed to bfd_map_over_sections, but in this context the sections to
12155    read comes from the DWP V1 hash table, not the full ELF section table.
12156
12157    The result is non-zero for success, or zero if an error was found.  */
12158
12159 static int
12160 locate_v1_virtual_dwo_sections (asection *sectp,
12161                                 struct virtual_v1_dwo_sections *sections)
12162 {
12163   const struct dwop_section_names *names = &dwop_section_names;
12164
12165   if (section_is_p (sectp->name, &names->abbrev_dwo))
12166     {
12167       /* There can be only one.  */
12168       if (sections->abbrev.s.section != NULL)
12169         return 0;
12170       sections->abbrev.s.section = sectp;
12171       sections->abbrev.size = bfd_get_section_size (sectp);
12172     }
12173   else if (section_is_p (sectp->name, &names->info_dwo)
12174            || section_is_p (sectp->name, &names->types_dwo))
12175     {
12176       /* There can be only one.  */
12177       if (sections->info_or_types.s.section != NULL)
12178         return 0;
12179       sections->info_or_types.s.section = sectp;
12180       sections->info_or_types.size = bfd_get_section_size (sectp);
12181     }
12182   else if (section_is_p (sectp->name, &names->line_dwo))
12183     {
12184       /* There can be only one.  */
12185       if (sections->line.s.section != NULL)
12186         return 0;
12187       sections->line.s.section = sectp;
12188       sections->line.size = bfd_get_section_size (sectp);
12189     }
12190   else if (section_is_p (sectp->name, &names->loc_dwo))
12191     {
12192       /* There can be only one.  */
12193       if (sections->loc.s.section != NULL)
12194         return 0;
12195       sections->loc.s.section = sectp;
12196       sections->loc.size = bfd_get_section_size (sectp);
12197     }
12198   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12199     {
12200       /* There can be only one.  */
12201       if (sections->macinfo.s.section != NULL)
12202         return 0;
12203       sections->macinfo.s.section = sectp;
12204       sections->macinfo.size = bfd_get_section_size (sectp);
12205     }
12206   else if (section_is_p (sectp->name, &names->macro_dwo))
12207     {
12208       /* There can be only one.  */
12209       if (sections->macro.s.section != NULL)
12210         return 0;
12211       sections->macro.s.section = sectp;
12212       sections->macro.size = bfd_get_section_size (sectp);
12213     }
12214   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12215     {
12216       /* There can be only one.  */
12217       if (sections->str_offsets.s.section != NULL)
12218         return 0;
12219       sections->str_offsets.s.section = sectp;
12220       sections->str_offsets.size = bfd_get_section_size (sectp);
12221     }
12222   else
12223     {
12224       /* No other kind of section is valid.  */
12225       return 0;
12226     }
12227
12228   return 1;
12229 }
12230
12231 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12232    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12233    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12234    This is for DWP version 1 files.  */
12235
12236 static struct dwo_unit *
12237 create_dwo_unit_in_dwp_v1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12238                            struct dwp_file *dwp_file,
12239                            uint32_t unit_index,
12240                            const char *comp_dir,
12241                            ULONGEST signature, int is_debug_types)
12242 {
12243   struct objfile *objfile = dwarf2_per_objfile->objfile;
12244   const struct dwp_hash_table *dwp_htab =
12245     is_debug_types ? dwp_file->tus : dwp_file->cus;
12246   bfd *dbfd = dwp_file->dbfd.get ();
12247   const char *kind = is_debug_types ? "TU" : "CU";
12248   struct dwo_file *dwo_file;
12249   struct dwo_unit *dwo_unit;
12250   struct virtual_v1_dwo_sections sections;
12251   void **dwo_file_slot;
12252   int i;
12253
12254   gdb_assert (dwp_file->version == 1);
12255
12256   if (dwarf_read_debug)
12257     {
12258       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
12259                           kind,
12260                           pulongest (unit_index), hex_string (signature),
12261                           dwp_file->name);
12262     }
12263
12264   /* Fetch the sections of this DWO unit.
12265      Put a limit on the number of sections we look for so that bad data
12266      doesn't cause us to loop forever.  */
12267
12268 #define MAX_NR_V1_DWO_SECTIONS \
12269   (1 /* .debug_info or .debug_types */ \
12270    + 1 /* .debug_abbrev */ \
12271    + 1 /* .debug_line */ \
12272    + 1 /* .debug_loc */ \
12273    + 1 /* .debug_str_offsets */ \
12274    + 1 /* .debug_macro or .debug_macinfo */ \
12275    + 1 /* trailing zero */)
12276
12277   memset (&sections, 0, sizeof (sections));
12278
12279   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
12280     {
12281       asection *sectp;
12282       uint32_t section_nr =
12283         read_4_bytes (dbfd,
12284                       dwp_htab->section_pool.v1.indices
12285                       + (unit_index + i) * sizeof (uint32_t));
12286
12287       if (section_nr == 0)
12288         break;
12289       if (section_nr >= dwp_file->num_sections)
12290         {
12291           error (_("Dwarf Error: bad DWP hash table, section number too large"
12292                    " [in module %s]"),
12293                  dwp_file->name);
12294         }
12295
12296       sectp = dwp_file->elf_sections[section_nr];
12297       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
12298         {
12299           error (_("Dwarf Error: bad DWP hash table, invalid section found"
12300                    " [in module %s]"),
12301                  dwp_file->name);
12302         }
12303     }
12304
12305   if (i < 2
12306       || dwarf2_section_empty_p (&sections.info_or_types)
12307       || dwarf2_section_empty_p (&sections.abbrev))
12308     {
12309       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
12310                " [in module %s]"),
12311              dwp_file->name);
12312     }
12313   if (i == MAX_NR_V1_DWO_SECTIONS)
12314     {
12315       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
12316                " [in module %s]"),
12317              dwp_file->name);
12318     }
12319
12320   /* It's easier for the rest of the code if we fake a struct dwo_file and
12321      have dwo_unit "live" in that.  At least for now.
12322
12323      The DWP file can be made up of a random collection of CUs and TUs.
12324      However, for each CU + set of TUs that came from the same original DWO
12325      file, we can combine them back into a virtual DWO file to save space
12326      (fewer struct dwo_file objects to allocate).  Remember that for really
12327      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12328
12329   std::string virtual_dwo_name =
12330     string_printf ("virtual-dwo/%d-%d-%d-%d",
12331                    get_section_id (&sections.abbrev),
12332                    get_section_id (&sections.line),
12333                    get_section_id (&sections.loc),
12334                    get_section_id (&sections.str_offsets));
12335   /* Can we use an existing virtual DWO file?  */
12336   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12337                                         virtual_dwo_name.c_str (),
12338                                         comp_dir);
12339   /* Create one if necessary.  */
12340   if (*dwo_file_slot == NULL)
12341     {
12342       if (dwarf_read_debug)
12343         {
12344           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12345                               virtual_dwo_name.c_str ());
12346         }
12347       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12348       dwo_file->dwo_name
12349         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12350                                         virtual_dwo_name.c_str (),
12351                                         virtual_dwo_name.size ());
12352       dwo_file->comp_dir = comp_dir;
12353       dwo_file->sections.abbrev = sections.abbrev;
12354       dwo_file->sections.line = sections.line;
12355       dwo_file->sections.loc = sections.loc;
12356       dwo_file->sections.macinfo = sections.macinfo;
12357       dwo_file->sections.macro = sections.macro;
12358       dwo_file->sections.str_offsets = sections.str_offsets;
12359       /* The "str" section is global to the entire DWP file.  */
12360       dwo_file->sections.str = dwp_file->sections.str;
12361       /* The info or types section is assigned below to dwo_unit,
12362          there's no need to record it in dwo_file.
12363          Also, we can't simply record type sections in dwo_file because
12364          we record a pointer into the vector in dwo_unit.  As we collect more
12365          types we'll grow the vector and eventually have to reallocate space
12366          for it, invalidating all copies of pointers into the previous
12367          contents.  */
12368       *dwo_file_slot = dwo_file;
12369     }
12370   else
12371     {
12372       if (dwarf_read_debug)
12373         {
12374           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12375                               virtual_dwo_name.c_str ());
12376         }
12377       dwo_file = (struct dwo_file *) *dwo_file_slot;
12378     }
12379
12380   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12381   dwo_unit->dwo_file = dwo_file;
12382   dwo_unit->signature = signature;
12383   dwo_unit->section =
12384     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12385   *dwo_unit->section = sections.info_or_types;
12386   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12387
12388   return dwo_unit;
12389 }
12390
12391 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
12392    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
12393    piece within that section used by a TU/CU, return a virtual section
12394    of just that piece.  */
12395
12396 static struct dwarf2_section_info
12397 create_dwp_v2_section (struct dwarf2_per_objfile *dwarf2_per_objfile,
12398                        struct dwarf2_section_info *section,
12399                        bfd_size_type offset, bfd_size_type size)
12400 {
12401   struct dwarf2_section_info result;
12402   asection *sectp;
12403
12404   gdb_assert (section != NULL);
12405   gdb_assert (!section->is_virtual);
12406
12407   memset (&result, 0, sizeof (result));
12408   result.s.containing_section = section;
12409   result.is_virtual = 1;
12410
12411   if (size == 0)
12412     return result;
12413
12414   sectp = get_section_bfd_section (section);
12415
12416   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
12417      bounds of the real section.  This is a pretty-rare event, so just
12418      flag an error (easier) instead of a warning and trying to cope.  */
12419   if (sectp == NULL
12420       || offset + size > bfd_get_section_size (sectp))
12421     {
12422       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
12423                " in section %s [in module %s]"),
12424              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
12425              objfile_name (dwarf2_per_objfile->objfile));
12426     }
12427
12428   result.virtual_offset = offset;
12429   result.size = size;
12430   return result;
12431 }
12432
12433 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
12434    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
12435    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
12436    This is for DWP version 2 files.  */
12437
12438 static struct dwo_unit *
12439 create_dwo_unit_in_dwp_v2 (struct dwarf2_per_objfile *dwarf2_per_objfile,
12440                            struct dwp_file *dwp_file,
12441                            uint32_t unit_index,
12442                            const char *comp_dir,
12443                            ULONGEST signature, int is_debug_types)
12444 {
12445   struct objfile *objfile = dwarf2_per_objfile->objfile;
12446   const struct dwp_hash_table *dwp_htab =
12447     is_debug_types ? dwp_file->tus : dwp_file->cus;
12448   bfd *dbfd = dwp_file->dbfd.get ();
12449   const char *kind = is_debug_types ? "TU" : "CU";
12450   struct dwo_file *dwo_file;
12451   struct dwo_unit *dwo_unit;
12452   struct virtual_v2_dwo_sections sections;
12453   void **dwo_file_slot;
12454   int i;
12455
12456   gdb_assert (dwp_file->version == 2);
12457
12458   if (dwarf_read_debug)
12459     {
12460       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
12461                           kind,
12462                           pulongest (unit_index), hex_string (signature),
12463                           dwp_file->name);
12464     }
12465
12466   /* Fetch the section offsets of this DWO unit.  */
12467
12468   memset (&sections, 0, sizeof (sections));
12469
12470   for (i = 0; i < dwp_htab->nr_columns; ++i)
12471     {
12472       uint32_t offset = read_4_bytes (dbfd,
12473                                       dwp_htab->section_pool.v2.offsets
12474                                       + (((unit_index - 1) * dwp_htab->nr_columns
12475                                           + i)
12476                                          * sizeof (uint32_t)));
12477       uint32_t size = read_4_bytes (dbfd,
12478                                     dwp_htab->section_pool.v2.sizes
12479                                     + (((unit_index - 1) * dwp_htab->nr_columns
12480                                         + i)
12481                                        * sizeof (uint32_t)));
12482
12483       switch (dwp_htab->section_pool.v2.section_ids[i])
12484         {
12485         case DW_SECT_INFO:
12486         case DW_SECT_TYPES:
12487           sections.info_or_types_offset = offset;
12488           sections.info_or_types_size = size;
12489           break;
12490         case DW_SECT_ABBREV:
12491           sections.abbrev_offset = offset;
12492           sections.abbrev_size = size;
12493           break;
12494         case DW_SECT_LINE:
12495           sections.line_offset = offset;
12496           sections.line_size = size;
12497           break;
12498         case DW_SECT_LOC:
12499           sections.loc_offset = offset;
12500           sections.loc_size = size;
12501           break;
12502         case DW_SECT_STR_OFFSETS:
12503           sections.str_offsets_offset = offset;
12504           sections.str_offsets_size = size;
12505           break;
12506         case DW_SECT_MACINFO:
12507           sections.macinfo_offset = offset;
12508           sections.macinfo_size = size;
12509           break;
12510         case DW_SECT_MACRO:
12511           sections.macro_offset = offset;
12512           sections.macro_size = size;
12513           break;
12514         }
12515     }
12516
12517   /* It's easier for the rest of the code if we fake a struct dwo_file and
12518      have dwo_unit "live" in that.  At least for now.
12519
12520      The DWP file can be made up of a random collection of CUs and TUs.
12521      However, for each CU + set of TUs that came from the same original DWO
12522      file, we can combine them back into a virtual DWO file to save space
12523      (fewer struct dwo_file objects to allocate).  Remember that for really
12524      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
12525
12526   std::string virtual_dwo_name =
12527     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
12528                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
12529                    (long) (sections.line_size ? sections.line_offset : 0),
12530                    (long) (sections.loc_size ? sections.loc_offset : 0),
12531                    (long) (sections.str_offsets_size
12532                            ? sections.str_offsets_offset : 0));
12533   /* Can we use an existing virtual DWO file?  */
12534   dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
12535                                         virtual_dwo_name.c_str (),
12536                                         comp_dir);
12537   /* Create one if necessary.  */
12538   if (*dwo_file_slot == NULL)
12539     {
12540       if (dwarf_read_debug)
12541         {
12542           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
12543                               virtual_dwo_name.c_str ());
12544         }
12545       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
12546       dwo_file->dwo_name
12547         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
12548                                         virtual_dwo_name.c_str (),
12549                                         virtual_dwo_name.size ());
12550       dwo_file->comp_dir = comp_dir;
12551       dwo_file->sections.abbrev =
12552         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.abbrev,
12553                                sections.abbrev_offset, sections.abbrev_size);
12554       dwo_file->sections.line =
12555         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.line,
12556                                sections.line_offset, sections.line_size);
12557       dwo_file->sections.loc =
12558         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.loc,
12559                                sections.loc_offset, sections.loc_size);
12560       dwo_file->sections.macinfo =
12561         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macinfo,
12562                                sections.macinfo_offset, sections.macinfo_size);
12563       dwo_file->sections.macro =
12564         create_dwp_v2_section (dwarf2_per_objfile, &dwp_file->sections.macro,
12565                                sections.macro_offset, sections.macro_size);
12566       dwo_file->sections.str_offsets =
12567         create_dwp_v2_section (dwarf2_per_objfile,
12568                                &dwp_file->sections.str_offsets,
12569                                sections.str_offsets_offset,
12570                                sections.str_offsets_size);
12571       /* The "str" section is global to the entire DWP file.  */
12572       dwo_file->sections.str = dwp_file->sections.str;
12573       /* The info or types section is assigned below to dwo_unit,
12574          there's no need to record it in dwo_file.
12575          Also, we can't simply record type sections in dwo_file because
12576          we record a pointer into the vector in dwo_unit.  As we collect more
12577          types we'll grow the vector and eventually have to reallocate space
12578          for it, invalidating all copies of pointers into the previous
12579          contents.  */
12580       *dwo_file_slot = dwo_file;
12581     }
12582   else
12583     {
12584       if (dwarf_read_debug)
12585         {
12586           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
12587                               virtual_dwo_name.c_str ());
12588         }
12589       dwo_file = (struct dwo_file *) *dwo_file_slot;
12590     }
12591
12592   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
12593   dwo_unit->dwo_file = dwo_file;
12594   dwo_unit->signature = signature;
12595   dwo_unit->section =
12596     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
12597   *dwo_unit->section = create_dwp_v2_section (dwarf2_per_objfile,
12598                                               is_debug_types
12599                                               ? &dwp_file->sections.types
12600                                               : &dwp_file->sections.info,
12601                                               sections.info_or_types_offset,
12602                                               sections.info_or_types_size);
12603   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
12604
12605   return dwo_unit;
12606 }
12607
12608 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
12609    Returns NULL if the signature isn't found.  */
12610
12611 static struct dwo_unit *
12612 lookup_dwo_unit_in_dwp (struct dwarf2_per_objfile *dwarf2_per_objfile,
12613                         struct dwp_file *dwp_file, const char *comp_dir,
12614                         ULONGEST signature, int is_debug_types)
12615 {
12616   const struct dwp_hash_table *dwp_htab =
12617     is_debug_types ? dwp_file->tus : dwp_file->cus;
12618   bfd *dbfd = dwp_file->dbfd.get ();
12619   uint32_t mask = dwp_htab->nr_slots - 1;
12620   uint32_t hash = signature & mask;
12621   uint32_t hash2 = ((signature >> 32) & mask) | 1;
12622   unsigned int i;
12623   void **slot;
12624   struct dwo_unit find_dwo_cu;
12625
12626   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
12627   find_dwo_cu.signature = signature;
12628   slot = htab_find_slot (is_debug_types
12629                          ? dwp_file->loaded_tus
12630                          : dwp_file->loaded_cus,
12631                          &find_dwo_cu, INSERT);
12632
12633   if (*slot != NULL)
12634     return (struct dwo_unit *) *slot;
12635
12636   /* Use a for loop so that we don't loop forever on bad debug info.  */
12637   for (i = 0; i < dwp_htab->nr_slots; ++i)
12638     {
12639       ULONGEST signature_in_table;
12640
12641       signature_in_table =
12642         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
12643       if (signature_in_table == signature)
12644         {
12645           uint32_t unit_index =
12646             read_4_bytes (dbfd,
12647                           dwp_htab->unit_table + hash * sizeof (uint32_t));
12648
12649           if (dwp_file->version == 1)
12650             {
12651               *slot = create_dwo_unit_in_dwp_v1 (dwarf2_per_objfile,
12652                                                  dwp_file, unit_index,
12653                                                  comp_dir, signature,
12654                                                  is_debug_types);
12655             }
12656           else
12657             {
12658               *slot = create_dwo_unit_in_dwp_v2 (dwarf2_per_objfile,
12659                                                  dwp_file, unit_index,
12660                                                  comp_dir, signature,
12661                                                  is_debug_types);
12662             }
12663           return (struct dwo_unit *) *slot;
12664         }
12665       if (signature_in_table == 0)
12666         return NULL;
12667       hash = (hash + hash2) & mask;
12668     }
12669
12670   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
12671            " [in module %s]"),
12672          dwp_file->name);
12673 }
12674
12675 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
12676    Open the file specified by FILE_NAME and hand it off to BFD for
12677    preliminary analysis.  Return a newly initialized bfd *, which
12678    includes a canonicalized copy of FILE_NAME.
12679    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
12680    SEARCH_CWD is true if the current directory is to be searched.
12681    It will be searched before debug-file-directory.
12682    If successful, the file is added to the bfd include table of the
12683    objfile's bfd (see gdb_bfd_record_inclusion).
12684    If unable to find/open the file, return NULL.
12685    NOTE: This function is derived from symfile_bfd_open.  */
12686
12687 static gdb_bfd_ref_ptr
12688 try_open_dwop_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12689                     const char *file_name, int is_dwp, int search_cwd)
12690 {
12691   int desc;
12692   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
12693      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
12694      to debug_file_directory.  */
12695   const char *search_path;
12696   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
12697
12698   gdb::unique_xmalloc_ptr<char> search_path_holder;
12699   if (search_cwd)
12700     {
12701       if (*debug_file_directory != '\0')
12702         {
12703           search_path_holder.reset (concat (".", dirname_separator_string,
12704                                             debug_file_directory,
12705                                             (char *) NULL));
12706           search_path = search_path_holder.get ();
12707         }
12708       else
12709         search_path = ".";
12710     }
12711   else
12712     search_path = debug_file_directory;
12713
12714   openp_flags flags = OPF_RETURN_REALPATH;
12715   if (is_dwp)
12716     flags |= OPF_SEARCH_IN_PATH;
12717
12718   gdb::unique_xmalloc_ptr<char> absolute_name;
12719   desc = openp (search_path, flags, file_name,
12720                 O_RDONLY | O_BINARY, &absolute_name);
12721   if (desc < 0)
12722     return NULL;
12723
12724   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name.get (),
12725                                          gnutarget, desc));
12726   if (sym_bfd == NULL)
12727     return NULL;
12728   bfd_set_cacheable (sym_bfd.get (), 1);
12729
12730   if (!bfd_check_format (sym_bfd.get (), bfd_object))
12731     return NULL;
12732
12733   /* Success.  Record the bfd as having been included by the objfile's bfd.
12734      This is important because things like demangled_names_hash lives in the
12735      objfile's per_bfd space and may have references to things like symbol
12736      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
12737   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
12738
12739   return sym_bfd;
12740 }
12741
12742 /* Try to open DWO file FILE_NAME.
12743    COMP_DIR is the DW_AT_comp_dir attribute.
12744    The result is the bfd handle of the file.
12745    If there is a problem finding or opening the file, return NULL.
12746    Upon success, the canonicalized path of the file is stored in the bfd,
12747    same as symfile_bfd_open.  */
12748
12749 static gdb_bfd_ref_ptr
12750 open_dwo_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
12751                const char *file_name, const char *comp_dir)
12752 {
12753   if (IS_ABSOLUTE_PATH (file_name))
12754     return try_open_dwop_file (dwarf2_per_objfile, file_name,
12755                                0 /*is_dwp*/, 0 /*search_cwd*/);
12756
12757   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
12758
12759   if (comp_dir != NULL)
12760     {
12761       char *path_to_try = concat (comp_dir, SLASH_STRING,
12762                                   file_name, (char *) NULL);
12763
12764       /* NOTE: If comp_dir is a relative path, this will also try the
12765          search path, which seems useful.  */
12766       gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile,
12767                                                 path_to_try,
12768                                                 0 /*is_dwp*/,
12769                                                 1 /*search_cwd*/));
12770       xfree (path_to_try);
12771       if (abfd != NULL)
12772         return abfd;
12773     }
12774
12775   /* That didn't work, try debug-file-directory, which, despite its name,
12776      is a list of paths.  */
12777
12778   if (*debug_file_directory == '\0')
12779     return NULL;
12780
12781   return try_open_dwop_file (dwarf2_per_objfile, file_name,
12782                              0 /*is_dwp*/, 1 /*search_cwd*/);
12783 }
12784
12785 /* This function is mapped across the sections and remembers the offset and
12786    size of each of the DWO debugging sections we are interested in.  */
12787
12788 static void
12789 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
12790 {
12791   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
12792   const struct dwop_section_names *names = &dwop_section_names;
12793
12794   if (section_is_p (sectp->name, &names->abbrev_dwo))
12795     {
12796       dwo_sections->abbrev.s.section = sectp;
12797       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
12798     }
12799   else if (section_is_p (sectp->name, &names->info_dwo))
12800     {
12801       dwo_sections->info.s.section = sectp;
12802       dwo_sections->info.size = bfd_get_section_size (sectp);
12803     }
12804   else if (section_is_p (sectp->name, &names->line_dwo))
12805     {
12806       dwo_sections->line.s.section = sectp;
12807       dwo_sections->line.size = bfd_get_section_size (sectp);
12808     }
12809   else if (section_is_p (sectp->name, &names->loc_dwo))
12810     {
12811       dwo_sections->loc.s.section = sectp;
12812       dwo_sections->loc.size = bfd_get_section_size (sectp);
12813     }
12814   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12815     {
12816       dwo_sections->macinfo.s.section = sectp;
12817       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
12818     }
12819   else if (section_is_p (sectp->name, &names->macro_dwo))
12820     {
12821       dwo_sections->macro.s.section = sectp;
12822       dwo_sections->macro.size = bfd_get_section_size (sectp);
12823     }
12824   else if (section_is_p (sectp->name, &names->str_dwo))
12825     {
12826       dwo_sections->str.s.section = sectp;
12827       dwo_sections->str.size = bfd_get_section_size (sectp);
12828     }
12829   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12830     {
12831       dwo_sections->str_offsets.s.section = sectp;
12832       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
12833     }
12834   else if (section_is_p (sectp->name, &names->types_dwo))
12835     {
12836       struct dwarf2_section_info type_section;
12837
12838       memset (&type_section, 0, sizeof (type_section));
12839       type_section.s.section = sectp;
12840       type_section.size = bfd_get_section_size (sectp);
12841       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
12842                      &type_section);
12843     }
12844 }
12845
12846 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
12847    by PER_CU.  This is for the non-DWP case.
12848    The result is NULL if DWO_NAME can't be found.  */
12849
12850 static struct dwo_file *
12851 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
12852                         const char *dwo_name, const char *comp_dir)
12853 {
12854   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
12855   struct objfile *objfile = dwarf2_per_objfile->objfile;
12856
12857   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwarf2_per_objfile, dwo_name, comp_dir));
12858   if (dbfd == NULL)
12859     {
12860       if (dwarf_read_debug)
12861         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
12862       return NULL;
12863     }
12864
12865   /* We use a unique pointer here, despite the obstack allocation,
12866      because a dwo_file needs some cleanup if it is abandoned.  */
12867   dwo_file_up dwo_file (OBSTACK_ZALLOC (&objfile->objfile_obstack,
12868                                         struct dwo_file));
12869   dwo_file->dwo_name = dwo_name;
12870   dwo_file->comp_dir = comp_dir;
12871   dwo_file->dbfd = dbfd.release ();
12872
12873   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
12874                          &dwo_file->sections);
12875
12876   create_cus_hash_table (dwarf2_per_objfile, *dwo_file, dwo_file->sections.info,
12877                          dwo_file->cus);
12878
12879   create_debug_types_hash_table (dwarf2_per_objfile, dwo_file.get (),
12880                                  dwo_file->sections.types, dwo_file->tus);
12881
12882   if (dwarf_read_debug)
12883     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
12884
12885   return dwo_file.release ();
12886 }
12887
12888 /* This function is mapped across the sections and remembers the offset and
12889    size of each of the DWP debugging sections common to version 1 and 2 that
12890    we are interested in.  */
12891
12892 static void
12893 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
12894                                    void *dwp_file_ptr)
12895 {
12896   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12897   const struct dwop_section_names *names = &dwop_section_names;
12898   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12899
12900   /* Record the ELF section number for later lookup: this is what the
12901      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12902   gdb_assert (elf_section_nr < dwp_file->num_sections);
12903   dwp_file->elf_sections[elf_section_nr] = sectp;
12904
12905   /* Look for specific sections that we need.  */
12906   if (section_is_p (sectp->name, &names->str_dwo))
12907     {
12908       dwp_file->sections.str.s.section = sectp;
12909       dwp_file->sections.str.size = bfd_get_section_size (sectp);
12910     }
12911   else if (section_is_p (sectp->name, &names->cu_index))
12912     {
12913       dwp_file->sections.cu_index.s.section = sectp;
12914       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
12915     }
12916   else if (section_is_p (sectp->name, &names->tu_index))
12917     {
12918       dwp_file->sections.tu_index.s.section = sectp;
12919       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
12920     }
12921 }
12922
12923 /* This function is mapped across the sections and remembers the offset and
12924    size of each of the DWP version 2 debugging sections that we are interested
12925    in.  This is split into a separate function because we don't know if we
12926    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
12927
12928 static void
12929 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
12930 {
12931   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
12932   const struct dwop_section_names *names = &dwop_section_names;
12933   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
12934
12935   /* Record the ELF section number for later lookup: this is what the
12936      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
12937   gdb_assert (elf_section_nr < dwp_file->num_sections);
12938   dwp_file->elf_sections[elf_section_nr] = sectp;
12939
12940   /* Look for specific sections that we need.  */
12941   if (section_is_p (sectp->name, &names->abbrev_dwo))
12942     {
12943       dwp_file->sections.abbrev.s.section = sectp;
12944       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
12945     }
12946   else if (section_is_p (sectp->name, &names->info_dwo))
12947     {
12948       dwp_file->sections.info.s.section = sectp;
12949       dwp_file->sections.info.size = bfd_get_section_size (sectp);
12950     }
12951   else if (section_is_p (sectp->name, &names->line_dwo))
12952     {
12953       dwp_file->sections.line.s.section = sectp;
12954       dwp_file->sections.line.size = bfd_get_section_size (sectp);
12955     }
12956   else if (section_is_p (sectp->name, &names->loc_dwo))
12957     {
12958       dwp_file->sections.loc.s.section = sectp;
12959       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
12960     }
12961   else if (section_is_p (sectp->name, &names->macinfo_dwo))
12962     {
12963       dwp_file->sections.macinfo.s.section = sectp;
12964       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
12965     }
12966   else if (section_is_p (sectp->name, &names->macro_dwo))
12967     {
12968       dwp_file->sections.macro.s.section = sectp;
12969       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
12970     }
12971   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
12972     {
12973       dwp_file->sections.str_offsets.s.section = sectp;
12974       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
12975     }
12976   else if (section_is_p (sectp->name, &names->types_dwo))
12977     {
12978       dwp_file->sections.types.s.section = sectp;
12979       dwp_file->sections.types.size = bfd_get_section_size (sectp);
12980     }
12981 }
12982
12983 /* Hash function for dwp_file loaded CUs/TUs.  */
12984
12985 static hashval_t
12986 hash_dwp_loaded_cutus (const void *item)
12987 {
12988   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
12989
12990   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
12991   return dwo_unit->signature;
12992 }
12993
12994 /* Equality function for dwp_file loaded CUs/TUs.  */
12995
12996 static int
12997 eq_dwp_loaded_cutus (const void *a, const void *b)
12998 {
12999   const struct dwo_unit *dua = (const struct dwo_unit *) a;
13000   const struct dwo_unit *dub = (const struct dwo_unit *) b;
13001
13002   return dua->signature == dub->signature;
13003 }
13004
13005 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
13006
13007 static htab_t
13008 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
13009 {
13010   return htab_create_alloc_ex (3,
13011                                hash_dwp_loaded_cutus,
13012                                eq_dwp_loaded_cutus,
13013                                NULL,
13014                                &objfile->objfile_obstack,
13015                                hashtab_obstack_allocate,
13016                                dummy_obstack_deallocate);
13017 }
13018
13019 /* Try to open DWP file FILE_NAME.
13020    The result is the bfd handle of the file.
13021    If there is a problem finding or opening the file, return NULL.
13022    Upon success, the canonicalized path of the file is stored in the bfd,
13023    same as symfile_bfd_open.  */
13024
13025 static gdb_bfd_ref_ptr
13026 open_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile,
13027                const char *file_name)
13028 {
13029   gdb_bfd_ref_ptr abfd (try_open_dwop_file (dwarf2_per_objfile, file_name,
13030                                             1 /*is_dwp*/,
13031                                             1 /*search_cwd*/));
13032   if (abfd != NULL)
13033     return abfd;
13034
13035   /* Work around upstream bug 15652.
13036      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
13037      [Whether that's a "bug" is debatable, but it is getting in our way.]
13038      We have no real idea where the dwp file is, because gdb's realpath-ing
13039      of the executable's path may have discarded the needed info.
13040      [IWBN if the dwp file name was recorded in the executable, akin to
13041      .gnu_debuglink, but that doesn't exist yet.]
13042      Strip the directory from FILE_NAME and search again.  */
13043   if (*debug_file_directory != '\0')
13044     {
13045       /* Don't implicitly search the current directory here.
13046          If the user wants to search "." to handle this case,
13047          it must be added to debug-file-directory.  */
13048       return try_open_dwop_file (dwarf2_per_objfile,
13049                                  lbasename (file_name), 1 /*is_dwp*/,
13050                                  0 /*search_cwd*/);
13051     }
13052
13053   return NULL;
13054 }
13055
13056 /* Initialize the use of the DWP file for the current objfile.
13057    By convention the name of the DWP file is ${objfile}.dwp.
13058    The result is NULL if it can't be found.  */
13059
13060 static std::unique_ptr<struct dwp_file>
13061 open_and_init_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13062 {
13063   struct objfile *objfile = dwarf2_per_objfile->objfile;
13064
13065   /* Try to find first .dwp for the binary file before any symbolic links
13066      resolving.  */
13067
13068   /* If the objfile is a debug file, find the name of the real binary
13069      file and get the name of dwp file from there.  */
13070   std::string dwp_name;
13071   if (objfile->separate_debug_objfile_backlink != NULL)
13072     {
13073       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
13074       const char *backlink_basename = lbasename (backlink->original_name);
13075
13076       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
13077     }
13078   else
13079     dwp_name = objfile->original_name;
13080
13081   dwp_name += ".dwp";
13082
13083   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ()));
13084   if (dbfd == NULL
13085       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
13086     {
13087       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
13088       dwp_name = objfile_name (objfile);
13089       dwp_name += ".dwp";
13090       dbfd = open_dwp_file (dwarf2_per_objfile, dwp_name.c_str ());
13091     }
13092
13093   if (dbfd == NULL)
13094     {
13095       if (dwarf_read_debug)
13096         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
13097       return std::unique_ptr<dwp_file> ();
13098     }
13099
13100   const char *name = bfd_get_filename (dbfd.get ());
13101   std::unique_ptr<struct dwp_file> dwp_file
13102     (new struct dwp_file (name, std::move (dbfd)));
13103
13104   /* +1: section 0 is unused */
13105   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
13106   dwp_file->elf_sections =
13107     OBSTACK_CALLOC (&objfile->objfile_obstack,
13108                     dwp_file->num_sections, asection *);
13109
13110   bfd_map_over_sections (dwp_file->dbfd.get (),
13111                          dwarf2_locate_common_dwp_sections,
13112                          dwp_file.get ());
13113
13114   dwp_file->cus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13115                                          0);
13116
13117   dwp_file->tus = create_dwp_hash_table (dwarf2_per_objfile, dwp_file.get (),
13118                                          1);
13119
13120   /* The DWP file version is stored in the hash table.  Oh well.  */
13121   if (dwp_file->cus && dwp_file->tus
13122       && dwp_file->cus->version != dwp_file->tus->version)
13123     {
13124       /* Technically speaking, we should try to limp along, but this is
13125          pretty bizarre.  We use pulongest here because that's the established
13126          portability solution (e.g, we cannot use %u for uint32_t).  */
13127       error (_("Dwarf Error: DWP file CU version %s doesn't match"
13128                " TU version %s [in DWP file %s]"),
13129              pulongest (dwp_file->cus->version),
13130              pulongest (dwp_file->tus->version), dwp_name.c_str ());
13131     }
13132
13133   if (dwp_file->cus)
13134     dwp_file->version = dwp_file->cus->version;
13135   else if (dwp_file->tus)
13136     dwp_file->version = dwp_file->tus->version;
13137   else
13138     dwp_file->version = 2;
13139
13140   if (dwp_file->version == 2)
13141     bfd_map_over_sections (dwp_file->dbfd.get (),
13142                            dwarf2_locate_v2_dwp_sections,
13143                            dwp_file.get ());
13144
13145   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
13146   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
13147
13148   if (dwarf_read_debug)
13149     {
13150       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
13151       fprintf_unfiltered (gdb_stdlog,
13152                           "    %s CUs, %s TUs\n",
13153                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
13154                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
13155     }
13156
13157   return dwp_file;
13158 }
13159
13160 /* Wrapper around open_and_init_dwp_file, only open it once.  */
13161
13162 static struct dwp_file *
13163 get_dwp_file (struct dwarf2_per_objfile *dwarf2_per_objfile)
13164 {
13165   if (! dwarf2_per_objfile->dwp_checked)
13166     {
13167       dwarf2_per_objfile->dwp_file
13168         = open_and_init_dwp_file (dwarf2_per_objfile);
13169       dwarf2_per_objfile->dwp_checked = 1;
13170     }
13171   return dwarf2_per_objfile->dwp_file.get ();
13172 }
13173
13174 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
13175    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
13176    or in the DWP file for the objfile, referenced by THIS_UNIT.
13177    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
13178    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
13179
13180    This is called, for example, when wanting to read a variable with a
13181    complex location.  Therefore we don't want to do file i/o for every call.
13182    Therefore we don't want to look for a DWO file on every call.
13183    Therefore we first see if we've already seen SIGNATURE in a DWP file,
13184    then we check if we've already seen DWO_NAME, and only THEN do we check
13185    for a DWO file.
13186
13187    The result is a pointer to the dwo_unit object or NULL if we didn't find it
13188    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
13189
13190 static struct dwo_unit *
13191 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
13192                  const char *dwo_name, const char *comp_dir,
13193                  ULONGEST signature, int is_debug_types)
13194 {
13195   struct dwarf2_per_objfile *dwarf2_per_objfile = this_unit->dwarf2_per_objfile;
13196   struct objfile *objfile = dwarf2_per_objfile->objfile;
13197   const char *kind = is_debug_types ? "TU" : "CU";
13198   void **dwo_file_slot;
13199   struct dwo_file *dwo_file;
13200   struct dwp_file *dwp_file;
13201
13202   /* First see if there's a DWP file.
13203      If we have a DWP file but didn't find the DWO inside it, don't
13204      look for the original DWO file.  It makes gdb behave differently
13205      depending on whether one is debugging in the build tree.  */
13206
13207   dwp_file = get_dwp_file (dwarf2_per_objfile);
13208   if (dwp_file != NULL)
13209     {
13210       const struct dwp_hash_table *dwp_htab =
13211         is_debug_types ? dwp_file->tus : dwp_file->cus;
13212
13213       if (dwp_htab != NULL)
13214         {
13215           struct dwo_unit *dwo_cutu =
13216             lookup_dwo_unit_in_dwp (dwarf2_per_objfile, dwp_file, comp_dir,
13217                                     signature, is_debug_types);
13218
13219           if (dwo_cutu != NULL)
13220             {
13221               if (dwarf_read_debug)
13222                 {
13223                   fprintf_unfiltered (gdb_stdlog,
13224                                       "Virtual DWO %s %s found: @%s\n",
13225                                       kind, hex_string (signature),
13226                                       host_address_to_string (dwo_cutu));
13227                 }
13228               return dwo_cutu;
13229             }
13230         }
13231     }
13232   else
13233     {
13234       /* No DWP file, look for the DWO file.  */
13235
13236       dwo_file_slot = lookup_dwo_file_slot (dwarf2_per_objfile,
13237                                             dwo_name, comp_dir);
13238       if (*dwo_file_slot == NULL)
13239         {
13240           /* Read in the file and build a table of the CUs/TUs it contains.  */
13241           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
13242         }
13243       /* NOTE: This will be NULL if unable to open the file.  */
13244       dwo_file = (struct dwo_file *) *dwo_file_slot;
13245
13246       if (dwo_file != NULL)
13247         {
13248           struct dwo_unit *dwo_cutu = NULL;
13249
13250           if (is_debug_types && dwo_file->tus)
13251             {
13252               struct dwo_unit find_dwo_cutu;
13253
13254               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13255               find_dwo_cutu.signature = signature;
13256               dwo_cutu
13257                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
13258             }
13259           else if (!is_debug_types && dwo_file->cus)
13260             {
13261               struct dwo_unit find_dwo_cutu;
13262
13263               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
13264               find_dwo_cutu.signature = signature;
13265               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
13266                                                        &find_dwo_cutu);
13267             }
13268
13269           if (dwo_cutu != NULL)
13270             {
13271               if (dwarf_read_debug)
13272                 {
13273                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
13274                                       kind, dwo_name, hex_string (signature),
13275                                       host_address_to_string (dwo_cutu));
13276                 }
13277               return dwo_cutu;
13278             }
13279         }
13280     }
13281
13282   /* We didn't find it.  This could mean a dwo_id mismatch, or
13283      someone deleted the DWO/DWP file, or the search path isn't set up
13284      correctly to find the file.  */
13285
13286   if (dwarf_read_debug)
13287     {
13288       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
13289                           kind, dwo_name, hex_string (signature));
13290     }
13291
13292   /* This is a warning and not a complaint because it can be caused by
13293      pilot error (e.g., user accidentally deleting the DWO).  */
13294   {
13295     /* Print the name of the DWP file if we looked there, helps the user
13296        better diagnose the problem.  */
13297     std::string dwp_text;
13298
13299     if (dwp_file != NULL)
13300       dwp_text = string_printf (" [in DWP file %s]",
13301                                 lbasename (dwp_file->name));
13302
13303     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset %s"
13304                " [in module %s]"),
13305              kind, dwo_name, hex_string (signature),
13306              dwp_text.c_str (),
13307              this_unit->is_debug_types ? "TU" : "CU",
13308              sect_offset_str (this_unit->sect_off), objfile_name (objfile));
13309   }
13310   return NULL;
13311 }
13312
13313 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
13314    See lookup_dwo_cutu_unit for details.  */
13315
13316 static struct dwo_unit *
13317 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
13318                       const char *dwo_name, const char *comp_dir,
13319                       ULONGEST signature)
13320 {
13321   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
13322 }
13323
13324 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
13325    See lookup_dwo_cutu_unit for details.  */
13326
13327 static struct dwo_unit *
13328 lookup_dwo_type_unit (struct signatured_type *this_tu,
13329                       const char *dwo_name, const char *comp_dir)
13330 {
13331   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
13332 }
13333
13334 /* Traversal function for queue_and_load_all_dwo_tus.  */
13335
13336 static int
13337 queue_and_load_dwo_tu (void **slot, void *info)
13338 {
13339   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
13340   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
13341   ULONGEST signature = dwo_unit->signature;
13342   struct signatured_type *sig_type =
13343     lookup_dwo_signatured_type (per_cu->cu, signature);
13344
13345   if (sig_type != NULL)
13346     {
13347       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
13348
13349       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
13350          a real dependency of PER_CU on SIG_TYPE.  That is detected later
13351          while processing PER_CU.  */
13352       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
13353         load_full_type_unit (sig_cu);
13354       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
13355     }
13356
13357   return 1;
13358 }
13359
13360 /* Queue all TUs contained in the DWO of PER_CU to be read in.
13361    The DWO may have the only definition of the type, though it may not be
13362    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
13363    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
13364
13365 static void
13366 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
13367 {
13368   struct dwo_unit *dwo_unit;
13369   struct dwo_file *dwo_file;
13370
13371   gdb_assert (!per_cu->is_debug_types);
13372   gdb_assert (get_dwp_file (per_cu->dwarf2_per_objfile) == NULL);
13373   gdb_assert (per_cu->cu != NULL);
13374
13375   dwo_unit = per_cu->cu->dwo_unit;
13376   gdb_assert (dwo_unit != NULL);
13377
13378   dwo_file = dwo_unit->dwo_file;
13379   if (dwo_file->tus != NULL)
13380     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
13381 }
13382
13383 /* Free all resources associated with DWO_FILE.
13384    Close the DWO file and munmap the sections.  */
13385
13386 static void
13387 free_dwo_file (struct dwo_file *dwo_file)
13388 {
13389   /* Note: dbfd is NULL for virtual DWO files.  */
13390   gdb_bfd_unref (dwo_file->dbfd);
13391
13392   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
13393 }
13394
13395 /* Traversal function for free_dwo_files.  */
13396
13397 static int
13398 free_dwo_file_from_slot (void **slot, void *info)
13399 {
13400   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
13401
13402   free_dwo_file (dwo_file);
13403
13404   return 1;
13405 }
13406
13407 /* Free all resources associated with DWO_FILES.  */
13408
13409 static void
13410 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
13411 {
13412   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
13413 }
13414 \f
13415 /* Read in various DIEs.  */
13416
13417 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
13418    Inherit only the children of the DW_AT_abstract_origin DIE not being
13419    already referenced by DW_AT_abstract_origin from the children of the
13420    current DIE.  */
13421
13422 static void
13423 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
13424 {
13425   struct die_info *child_die;
13426   sect_offset *offsetp;
13427   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
13428   struct die_info *origin_die;
13429   /* Iterator of the ORIGIN_DIE children.  */
13430   struct die_info *origin_child_die;
13431   struct attribute *attr;
13432   struct dwarf2_cu *origin_cu;
13433   struct pending **origin_previous_list_in_scope;
13434
13435   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13436   if (!attr)
13437     return;
13438
13439   /* Note that following die references may follow to a die in a
13440      different cu.  */
13441
13442   origin_cu = cu;
13443   origin_die = follow_die_ref (die, attr, &origin_cu);
13444
13445   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
13446      symbols in.  */
13447   origin_previous_list_in_scope = origin_cu->list_in_scope;
13448   origin_cu->list_in_scope = cu->list_in_scope;
13449
13450   if (die->tag != origin_die->tag
13451       && !(die->tag == DW_TAG_inlined_subroutine
13452            && origin_die->tag == DW_TAG_subprogram))
13453     complaint (_("DIE %s and its abstract origin %s have different tags"),
13454                sect_offset_str (die->sect_off),
13455                sect_offset_str (origin_die->sect_off));
13456
13457   std::vector<sect_offset> offsets;
13458
13459   for (child_die = die->child;
13460        child_die && child_die->tag;
13461        child_die = sibling_die (child_die))
13462     {
13463       struct die_info *child_origin_die;
13464       struct dwarf2_cu *child_origin_cu;
13465
13466       /* We are trying to process concrete instance entries:
13467          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
13468          it's not relevant to our analysis here. i.e. detecting DIEs that are
13469          present in the abstract instance but not referenced in the concrete
13470          one.  */
13471       if (child_die->tag == DW_TAG_call_site
13472           || child_die->tag == DW_TAG_GNU_call_site)
13473         continue;
13474
13475       /* For each CHILD_DIE, find the corresponding child of
13476          ORIGIN_DIE.  If there is more than one layer of
13477          DW_AT_abstract_origin, follow them all; there shouldn't be,
13478          but GCC versions at least through 4.4 generate this (GCC PR
13479          40573).  */
13480       child_origin_die = child_die;
13481       child_origin_cu = cu;
13482       while (1)
13483         {
13484           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
13485                               child_origin_cu);
13486           if (attr == NULL)
13487             break;
13488           child_origin_die = follow_die_ref (child_origin_die, attr,
13489                                              &child_origin_cu);
13490         }
13491
13492       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
13493          counterpart may exist.  */
13494       if (child_origin_die != child_die)
13495         {
13496           if (child_die->tag != child_origin_die->tag
13497               && !(child_die->tag == DW_TAG_inlined_subroutine
13498                    && child_origin_die->tag == DW_TAG_subprogram))
13499             complaint (_("Child DIE %s and its abstract origin %s have "
13500                          "different tags"),
13501                        sect_offset_str (child_die->sect_off),
13502                        sect_offset_str (child_origin_die->sect_off));
13503           if (child_origin_die->parent != origin_die)
13504             complaint (_("Child DIE %s and its abstract origin %s have "
13505                          "different parents"),
13506                        sect_offset_str (child_die->sect_off),
13507                        sect_offset_str (child_origin_die->sect_off));
13508           else
13509             offsets.push_back (child_origin_die->sect_off);
13510         }
13511     }
13512   std::sort (offsets.begin (), offsets.end ());
13513   sect_offset *offsets_end = offsets.data () + offsets.size ();
13514   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
13515     if (offsetp[-1] == *offsetp)
13516       complaint (_("Multiple children of DIE %s refer "
13517                    "to DIE %s as their abstract origin"),
13518                  sect_offset_str (die->sect_off), sect_offset_str (*offsetp));
13519
13520   offsetp = offsets.data ();
13521   origin_child_die = origin_die->child;
13522   while (origin_child_die && origin_child_die->tag)
13523     {
13524       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
13525       while (offsetp < offsets_end
13526              && *offsetp < origin_child_die->sect_off)
13527         offsetp++;
13528       if (offsetp >= offsets_end
13529           || *offsetp > origin_child_die->sect_off)
13530         {
13531           /* Found that ORIGIN_CHILD_DIE is really not referenced.
13532              Check whether we're already processing ORIGIN_CHILD_DIE.
13533              This can happen with mutually referenced abstract_origins.
13534              PR 16581.  */
13535           if (!origin_child_die->in_process)
13536             process_die (origin_child_die, origin_cu);
13537         }
13538       origin_child_die = sibling_die (origin_child_die);
13539     }
13540   origin_cu->list_in_scope = origin_previous_list_in_scope;
13541 }
13542
13543 static void
13544 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
13545 {
13546   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13547   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13548   struct context_stack *newobj;
13549   CORE_ADDR lowpc;
13550   CORE_ADDR highpc;
13551   struct die_info *child_die;
13552   struct attribute *attr, *call_line, *call_file;
13553   const char *name;
13554   CORE_ADDR baseaddr;
13555   struct block *block;
13556   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
13557   std::vector<struct symbol *> template_args;
13558   struct template_symbol *templ_func = NULL;
13559
13560   if (inlined_func)
13561     {
13562       /* If we do not have call site information, we can't show the
13563          caller of this inlined function.  That's too confusing, so
13564          only use the scope for local variables.  */
13565       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
13566       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
13567       if (call_line == NULL || call_file == NULL)
13568         {
13569           read_lexical_block_scope (die, cu);
13570           return;
13571         }
13572     }
13573
13574   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13575
13576   name = dwarf2_name (die, cu);
13577
13578   /* Ignore functions with missing or empty names.  These are actually
13579      illegal according to the DWARF standard.  */
13580   if (name == NULL)
13581     {
13582       complaint (_("missing name for subprogram DIE at %s"),
13583                  sect_offset_str (die->sect_off));
13584       return;
13585     }
13586
13587   /* Ignore functions with missing or invalid low and high pc attributes.  */
13588   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
13589       <= PC_BOUNDS_INVALID)
13590     {
13591       attr = dwarf2_attr (die, DW_AT_external, cu);
13592       if (!attr || !DW_UNSND (attr))
13593         complaint (_("cannot get low and high bounds "
13594                      "for subprogram DIE at %s"),
13595                    sect_offset_str (die->sect_off));
13596       return;
13597     }
13598
13599   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13600   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13601
13602   /* If we have any template arguments, then we must allocate a
13603      different sort of symbol.  */
13604   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
13605     {
13606       if (child_die->tag == DW_TAG_template_type_param
13607           || child_die->tag == DW_TAG_template_value_param)
13608         {
13609           templ_func = allocate_template_symbol (objfile);
13610           templ_func->subclass = SYMBOL_TEMPLATE;
13611           break;
13612         }
13613     }
13614
13615   newobj = push_context (0, lowpc);
13616   newobj->name = new_symbol (die, read_type_die (die, cu), cu,
13617                              (struct symbol *) templ_func);
13618
13619   /* If there is a location expression for DW_AT_frame_base, record
13620      it.  */
13621   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
13622   if (attr)
13623     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
13624
13625   /* If there is a location for the static link, record it.  */
13626   newobj->static_link = NULL;
13627   attr = dwarf2_attr (die, DW_AT_static_link, cu);
13628   if (attr)
13629     {
13630       newobj->static_link
13631         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
13632       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
13633     }
13634
13635   cu->list_in_scope = &local_symbols;
13636
13637   if (die->child != NULL)
13638     {
13639       child_die = die->child;
13640       while (child_die && child_die->tag)
13641         {
13642           if (child_die->tag == DW_TAG_template_type_param
13643               || child_die->tag == DW_TAG_template_value_param)
13644             {
13645               struct symbol *arg = new_symbol (child_die, NULL, cu);
13646
13647               if (arg != NULL)
13648                 template_args.push_back (arg);
13649             }
13650           else
13651             process_die (child_die, cu);
13652           child_die = sibling_die (child_die);
13653         }
13654     }
13655
13656   inherit_abstract_dies (die, cu);
13657
13658   /* If we have a DW_AT_specification, we might need to import using
13659      directives from the context of the specification DIE.  See the
13660      comment in determine_prefix.  */
13661   if (cu->language == language_cplus
13662       && dwarf2_attr (die, DW_AT_specification, cu))
13663     {
13664       struct dwarf2_cu *spec_cu = cu;
13665       struct die_info *spec_die = die_specification (die, &spec_cu);
13666
13667       while (spec_die)
13668         {
13669           child_die = spec_die->child;
13670           while (child_die && child_die->tag)
13671             {
13672               if (child_die->tag == DW_TAG_imported_module)
13673                 process_die (child_die, spec_cu);
13674               child_die = sibling_die (child_die);
13675             }
13676
13677           /* In some cases, GCC generates specification DIEs that
13678              themselves contain DW_AT_specification attributes.  */
13679           spec_die = die_specification (spec_die, &spec_cu);
13680         }
13681     }
13682
13683   struct context_stack cstk = pop_context ();
13684   /* Make a block for the local symbols within.  */
13685   block = finish_block (cstk.name, cstk.old_blocks,
13686                         cstk.static_link, lowpc, highpc);
13687
13688   /* For C++, set the block's scope.  */
13689   if ((cu->language == language_cplus
13690        || cu->language == language_fortran
13691        || cu->language == language_d
13692        || cu->language == language_rust)
13693       && cu->processing_has_namespace_info)
13694     block_set_scope (block, determine_prefix (die, cu),
13695                      &objfile->objfile_obstack);
13696
13697   /* If we have address ranges, record them.  */
13698   dwarf2_record_block_ranges (die, block, baseaddr, cu);
13699
13700   gdbarch_make_symbol_special (gdbarch, cstk.name, objfile);
13701
13702   /* Attach template arguments to function.  */
13703   if (!template_args.empty ())
13704     {
13705       gdb_assert (templ_func != NULL);
13706
13707       templ_func->n_template_arguments = template_args.size ();
13708       templ_func->template_arguments
13709         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
13710                      templ_func->n_template_arguments);
13711       memcpy (templ_func->template_arguments,
13712               template_args.data (),
13713               (templ_func->n_template_arguments * sizeof (struct symbol *)));
13714     }
13715
13716   /* In C++, we can have functions nested inside functions (e.g., when
13717      a function declares a class that has methods).  This means that
13718      when we finish processing a function scope, we may need to go
13719      back to building a containing block's symbol lists.  */
13720   local_symbols = cstk.locals;
13721   set_local_using_directives (cstk.local_using_directives);
13722
13723   /* If we've finished processing a top-level function, subsequent
13724      symbols go in the file symbol list.  */
13725   if (outermost_context_p ())
13726     cu->list_in_scope = &file_symbols;
13727 }
13728
13729 /* Process all the DIES contained within a lexical block scope.  Start
13730    a new scope, process the dies, and then close the scope.  */
13731
13732 static void
13733 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
13734 {
13735   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13736   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13737   CORE_ADDR lowpc, highpc;
13738   struct die_info *child_die;
13739   CORE_ADDR baseaddr;
13740
13741   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13742
13743   /* Ignore blocks with missing or invalid low and high pc attributes.  */
13744   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
13745      as multiple lexical blocks?  Handling children in a sane way would
13746      be nasty.  Might be easier to properly extend generic blocks to
13747      describe ranges.  */
13748   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
13749     {
13750     case PC_BOUNDS_NOT_PRESENT:
13751       /* DW_TAG_lexical_block has no attributes, process its children as if
13752          there was no wrapping by that DW_TAG_lexical_block.
13753          GCC does no longer produces such DWARF since GCC r224161.  */
13754       for (child_die = die->child;
13755            child_die != NULL && child_die->tag;
13756            child_die = sibling_die (child_die))
13757         process_die (child_die, cu);
13758       return;
13759     case PC_BOUNDS_INVALID:
13760       return;
13761     }
13762   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13763   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
13764
13765   push_context (0, lowpc);
13766   if (die->child != NULL)
13767     {
13768       child_die = die->child;
13769       while (child_die && child_die->tag)
13770         {
13771           process_die (child_die, cu);
13772           child_die = sibling_die (child_die);
13773         }
13774     }
13775   inherit_abstract_dies (die, cu);
13776   struct context_stack cstk = pop_context ();
13777
13778   if (local_symbols != NULL || (*get_local_using_directives ()) != NULL)
13779     {
13780       struct block *block
13781         = finish_block (0, cstk.old_blocks, NULL,
13782                         cstk.start_addr, highpc);
13783
13784       /* Note that recording ranges after traversing children, as we
13785          do here, means that recording a parent's ranges entails
13786          walking across all its children's ranges as they appear in
13787          the address map, which is quadratic behavior.
13788
13789          It would be nicer to record the parent's ranges before
13790          traversing its children, simply overriding whatever you find
13791          there.  But since we don't even decide whether to create a
13792          block until after we've traversed its children, that's hard
13793          to do.  */
13794       dwarf2_record_block_ranges (die, block, baseaddr, cu);
13795     }
13796   local_symbols = cstk.locals;
13797   set_local_using_directives (cstk.local_using_directives);
13798 }
13799
13800 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
13801
13802 static void
13803 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
13804 {
13805   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
13806   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13807   CORE_ADDR pc, baseaddr;
13808   struct attribute *attr;
13809   struct call_site *call_site, call_site_local;
13810   void **slot;
13811   int nparams;
13812   struct die_info *child_die;
13813
13814   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13815
13816   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
13817   if (attr == NULL)
13818     {
13819       /* This was a pre-DWARF-5 GNU extension alias
13820          for DW_AT_call_return_pc.  */
13821       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13822     }
13823   if (!attr)
13824     {
13825       complaint (_("missing DW_AT_call_return_pc for DW_TAG_call_site "
13826                    "DIE %s [in module %s]"),
13827                  sect_offset_str (die->sect_off), objfile_name (objfile));
13828       return;
13829     }
13830   pc = attr_value_as_address (attr) + baseaddr;
13831   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
13832
13833   if (cu->call_site_htab == NULL)
13834     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
13835                                                NULL, &objfile->objfile_obstack,
13836                                                hashtab_obstack_allocate, NULL);
13837   call_site_local.pc = pc;
13838   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
13839   if (*slot != NULL)
13840     {
13841       complaint (_("Duplicate PC %s for DW_TAG_call_site "
13842                    "DIE %s [in module %s]"),
13843                  paddress (gdbarch, pc), sect_offset_str (die->sect_off),
13844                  objfile_name (objfile));
13845       return;
13846     }
13847
13848   /* Count parameters at the caller.  */
13849
13850   nparams = 0;
13851   for (child_die = die->child; child_die && child_die->tag;
13852        child_die = sibling_die (child_die))
13853     {
13854       if (child_die->tag != DW_TAG_call_site_parameter
13855           && child_die->tag != DW_TAG_GNU_call_site_parameter)
13856         {
13857           complaint (_("Tag %d is not DW_TAG_call_site_parameter in "
13858                        "DW_TAG_call_site child DIE %s [in module %s]"),
13859                      child_die->tag, sect_offset_str (child_die->sect_off),
13860                      objfile_name (objfile));
13861           continue;
13862         }
13863
13864       nparams++;
13865     }
13866
13867   call_site
13868     = ((struct call_site *)
13869        obstack_alloc (&objfile->objfile_obstack,
13870                       sizeof (*call_site)
13871                       + (sizeof (*call_site->parameter) * (nparams - 1))));
13872   *slot = call_site;
13873   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
13874   call_site->pc = pc;
13875
13876   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
13877       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
13878     {
13879       struct die_info *func_die;
13880
13881       /* Skip also over DW_TAG_inlined_subroutine.  */
13882       for (func_die = die->parent;
13883            func_die && func_die->tag != DW_TAG_subprogram
13884            && func_die->tag != DW_TAG_subroutine_type;
13885            func_die = func_die->parent);
13886
13887       /* DW_AT_call_all_calls is a superset
13888          of DW_AT_call_all_tail_calls.  */
13889       if (func_die
13890           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
13891           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
13892           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
13893           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
13894         {
13895           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
13896              not complete.  But keep CALL_SITE for look ups via call_site_htab,
13897              both the initial caller containing the real return address PC and
13898              the final callee containing the current PC of a chain of tail
13899              calls do not need to have the tail call list complete.  But any
13900              function candidate for a virtual tail call frame searched via
13901              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
13902              determined unambiguously.  */
13903         }
13904       else
13905         {
13906           struct type *func_type = NULL;
13907
13908           if (func_die)
13909             func_type = get_die_type (func_die, cu);
13910           if (func_type != NULL)
13911             {
13912               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
13913
13914               /* Enlist this call site to the function.  */
13915               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
13916               TYPE_TAIL_CALL_LIST (func_type) = call_site;
13917             }
13918           else
13919             complaint (_("Cannot find function owning DW_TAG_call_site "
13920                          "DIE %s [in module %s]"),
13921                        sect_offset_str (die->sect_off), objfile_name (objfile));
13922         }
13923     }
13924
13925   attr = dwarf2_attr (die, DW_AT_call_target, cu);
13926   if (attr == NULL)
13927     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
13928   if (attr == NULL)
13929     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
13930   if (attr == NULL)
13931     {
13932       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
13933       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
13934     }
13935   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
13936   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
13937     /* Keep NULL DWARF_BLOCK.  */;
13938   else if (attr_form_is_block (attr))
13939     {
13940       struct dwarf2_locexpr_baton *dlbaton;
13941
13942       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
13943       dlbaton->data = DW_BLOCK (attr)->data;
13944       dlbaton->size = DW_BLOCK (attr)->size;
13945       dlbaton->per_cu = cu->per_cu;
13946
13947       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
13948     }
13949   else if (attr_form_is_ref (attr))
13950     {
13951       struct dwarf2_cu *target_cu = cu;
13952       struct die_info *target_die;
13953
13954       target_die = follow_die_ref (die, attr, &target_cu);
13955       gdb_assert (target_cu->per_cu->dwarf2_per_objfile->objfile == objfile);
13956       if (die_is_declaration (target_die, target_cu))
13957         {
13958           const char *target_physname;
13959
13960           /* Prefer the mangled name; otherwise compute the demangled one.  */
13961           target_physname = dw2_linkage_name (target_die, target_cu);
13962           if (target_physname == NULL)
13963             target_physname = dwarf2_physname (NULL, target_die, target_cu);
13964           if (target_physname == NULL)
13965             complaint (_("DW_AT_call_target target DIE has invalid "
13966                          "physname, for referencing DIE %s [in module %s]"),
13967                        sect_offset_str (die->sect_off), objfile_name (objfile));
13968           else
13969             SET_FIELD_PHYSNAME (call_site->target, target_physname);
13970         }
13971       else
13972         {
13973           CORE_ADDR lowpc;
13974
13975           /* DW_AT_entry_pc should be preferred.  */
13976           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
13977               <= PC_BOUNDS_INVALID)
13978             complaint (_("DW_AT_call_target target DIE has invalid "
13979                          "low pc, for referencing DIE %s [in module %s]"),
13980                        sect_offset_str (die->sect_off), objfile_name (objfile));
13981           else
13982             {
13983               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
13984               SET_FIELD_PHYSADDR (call_site->target, lowpc);
13985             }
13986         }
13987     }
13988   else
13989     complaint (_("DW_TAG_call_site DW_AT_call_target is neither "
13990                  "block nor reference, for DIE %s [in module %s]"),
13991                sect_offset_str (die->sect_off), objfile_name (objfile));
13992
13993   call_site->per_cu = cu->per_cu;
13994
13995   for (child_die = die->child;
13996        child_die && child_die->tag;
13997        child_die = sibling_die (child_die))
13998     {
13999       struct call_site_parameter *parameter;
14000       struct attribute *loc, *origin;
14001
14002       if (child_die->tag != DW_TAG_call_site_parameter
14003           && child_die->tag != DW_TAG_GNU_call_site_parameter)
14004         {
14005           /* Already printed the complaint above.  */
14006           continue;
14007         }
14008
14009       gdb_assert (call_site->parameter_count < nparams);
14010       parameter = &call_site->parameter[call_site->parameter_count];
14011
14012       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
14013          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
14014          register is contained in DW_AT_call_value.  */
14015
14016       loc = dwarf2_attr (child_die, DW_AT_location, cu);
14017       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
14018       if (origin == NULL)
14019         {
14020           /* This was a pre-DWARF-5 GNU extension alias
14021              for DW_AT_call_parameter.  */
14022           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
14023         }
14024       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
14025         {
14026           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
14027
14028           sect_offset sect_off
14029             = (sect_offset) dwarf2_get_ref_die_offset (origin);
14030           if (!offset_in_cu_p (&cu->header, sect_off))
14031             {
14032               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
14033                  binding can be done only inside one CU.  Such referenced DIE
14034                  therefore cannot be even moved to DW_TAG_partial_unit.  */
14035               complaint (_("DW_AT_call_parameter offset is not in CU for "
14036                            "DW_TAG_call_site child DIE %s [in module %s]"),
14037                          sect_offset_str (child_die->sect_off),
14038                          objfile_name (objfile));
14039               continue;
14040             }
14041           parameter->u.param_cu_off
14042             = (cu_offset) (sect_off - cu->header.sect_off);
14043         }
14044       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
14045         {
14046           complaint (_("No DW_FORM_block* DW_AT_location for "
14047                        "DW_TAG_call_site child DIE %s [in module %s]"),
14048                      sect_offset_str (child_die->sect_off), objfile_name (objfile));
14049           continue;
14050         }
14051       else
14052         {
14053           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
14054             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
14055           if (parameter->u.dwarf_reg != -1)
14056             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
14057           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
14058                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
14059                                              &parameter->u.fb_offset))
14060             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
14061           else
14062             {
14063               complaint (_("Only single DW_OP_reg or DW_OP_fbreg is supported "
14064                            "for DW_FORM_block* DW_AT_location is supported for "
14065                            "DW_TAG_call_site child DIE %s "
14066                            "[in module %s]"),
14067                          sect_offset_str (child_die->sect_off),
14068                          objfile_name (objfile));
14069               continue;
14070             }
14071         }
14072
14073       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
14074       if (attr == NULL)
14075         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
14076       if (!attr_form_is_block (attr))
14077         {
14078           complaint (_("No DW_FORM_block* DW_AT_call_value for "
14079                        "DW_TAG_call_site child DIE %s [in module %s]"),
14080                      sect_offset_str (child_die->sect_off),
14081                      objfile_name (objfile));
14082           continue;
14083         }
14084       parameter->value = DW_BLOCK (attr)->data;
14085       parameter->value_size = DW_BLOCK (attr)->size;
14086
14087       /* Parameters are not pre-cleared by memset above.  */
14088       parameter->data_value = NULL;
14089       parameter->data_value_size = 0;
14090       call_site->parameter_count++;
14091
14092       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
14093       if (attr == NULL)
14094         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
14095       if (attr)
14096         {
14097           if (!attr_form_is_block (attr))
14098             complaint (_("No DW_FORM_block* DW_AT_call_data_value for "
14099                          "DW_TAG_call_site child DIE %s [in module %s]"),
14100                        sect_offset_str (child_die->sect_off),
14101                        objfile_name (objfile));
14102           else
14103             {
14104               parameter->data_value = DW_BLOCK (attr)->data;
14105               parameter->data_value_size = DW_BLOCK (attr)->size;
14106             }
14107         }
14108     }
14109 }
14110
14111 /* Helper function for read_variable.  If DIE represents a virtual
14112    table, then return the type of the concrete object that is
14113    associated with the virtual table.  Otherwise, return NULL.  */
14114
14115 static struct type *
14116 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
14117 {
14118   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
14119   if (attr == NULL)
14120     return NULL;
14121
14122   /* Find the type DIE.  */
14123   struct die_info *type_die = NULL;
14124   struct dwarf2_cu *type_cu = cu;
14125
14126   if (attr_form_is_ref (attr))
14127     type_die = follow_die_ref (die, attr, &type_cu);
14128   if (type_die == NULL)
14129     return NULL;
14130
14131   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
14132     return NULL;
14133   return die_containing_type (type_die, type_cu);
14134 }
14135
14136 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
14137
14138 static void
14139 read_variable (struct die_info *die, struct dwarf2_cu *cu)
14140 {
14141   struct rust_vtable_symbol *storage = NULL;
14142
14143   if (cu->language == language_rust)
14144     {
14145       struct type *containing_type = rust_containing_type (die, cu);
14146
14147       if (containing_type != NULL)
14148         {
14149           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14150
14151           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
14152                                     struct rust_vtable_symbol);
14153           initialize_objfile_symbol (storage);
14154           storage->concrete_type = containing_type;
14155           storage->subclass = SYMBOL_RUST_VTABLE;
14156         }
14157     }
14158
14159   new_symbol (die, NULL, cu, storage);
14160 }
14161
14162 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
14163    reading .debug_rnglists.
14164    Callback's type should be:
14165     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14166    Return true if the attributes are present and valid, otherwise,
14167    return false.  */
14168
14169 template <typename Callback>
14170 static bool
14171 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
14172                          Callback &&callback)
14173 {
14174   struct dwarf2_per_objfile *dwarf2_per_objfile
14175     = cu->per_cu->dwarf2_per_objfile;
14176   struct objfile *objfile = dwarf2_per_objfile->objfile;
14177   bfd *obfd = objfile->obfd;
14178   /* Base address selection entry.  */
14179   CORE_ADDR base;
14180   int found_base;
14181   const gdb_byte *buffer;
14182   CORE_ADDR baseaddr;
14183   bool overflow = false;
14184
14185   found_base = cu->base_known;
14186   base = cu->base_address;
14187
14188   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
14189   if (offset >= dwarf2_per_objfile->rnglists.size)
14190     {
14191       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14192                  offset);
14193       return false;
14194     }
14195   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
14196
14197   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14198
14199   while (1)
14200     {
14201       /* Initialize it due to a false compiler warning.  */
14202       CORE_ADDR range_beginning = 0, range_end = 0;
14203       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
14204                                  + dwarf2_per_objfile->rnglists.size);
14205       unsigned int bytes_read;
14206
14207       if (buffer == buf_end)
14208         {
14209           overflow = true;
14210           break;
14211         }
14212       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
14213       switch (rlet)
14214         {
14215         case DW_RLE_end_of_list:
14216           break;
14217         case DW_RLE_base_address:
14218           if (buffer + cu->header.addr_size > buf_end)
14219             {
14220               overflow = true;
14221               break;
14222             }
14223           base = read_address (obfd, buffer, cu, &bytes_read);
14224           found_base = 1;
14225           buffer += bytes_read;
14226           break;
14227         case DW_RLE_start_length:
14228           if (buffer + cu->header.addr_size > buf_end)
14229             {
14230               overflow = true;
14231               break;
14232             }
14233           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14234           buffer += bytes_read;
14235           range_end = (range_beginning
14236                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
14237           buffer += bytes_read;
14238           if (buffer > buf_end)
14239             {
14240               overflow = true;
14241               break;
14242             }
14243           break;
14244         case DW_RLE_offset_pair:
14245           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14246           buffer += bytes_read;
14247           if (buffer > buf_end)
14248             {
14249               overflow = true;
14250               break;
14251             }
14252           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
14253           buffer += bytes_read;
14254           if (buffer > buf_end)
14255             {
14256               overflow = true;
14257               break;
14258             }
14259           break;
14260         case DW_RLE_start_end:
14261           if (buffer + 2 * cu->header.addr_size > buf_end)
14262             {
14263               overflow = true;
14264               break;
14265             }
14266           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
14267           buffer += bytes_read;
14268           range_end = read_address (obfd, buffer, cu, &bytes_read);
14269           buffer += bytes_read;
14270           break;
14271         default:
14272           complaint (_("Invalid .debug_rnglists data (no base address)"));
14273           return false;
14274         }
14275       if (rlet == DW_RLE_end_of_list || overflow)
14276         break;
14277       if (rlet == DW_RLE_base_address)
14278         continue;
14279
14280       if (!found_base)
14281         {
14282           /* We have no valid base address for the ranges
14283              data.  */
14284           complaint (_("Invalid .debug_rnglists data (no base address)"));
14285           return false;
14286         }
14287
14288       if (range_beginning > range_end)
14289         {
14290           /* Inverted range entries are invalid.  */
14291           complaint (_("Invalid .debug_rnglists data (inverted range)"));
14292           return false;
14293         }
14294
14295       /* Empty range entries have no effect.  */
14296       if (range_beginning == range_end)
14297         continue;
14298
14299       range_beginning += base;
14300       range_end += base;
14301
14302       /* A not-uncommon case of bad debug info.
14303          Don't pollute the addrmap with bad data.  */
14304       if (range_beginning + baseaddr == 0
14305           && !dwarf2_per_objfile->has_section_at_zero)
14306         {
14307           complaint (_(".debug_rnglists entry has start address of zero"
14308                        " [in module %s]"), objfile_name (objfile));
14309           continue;
14310         }
14311
14312       callback (range_beginning, range_end);
14313     }
14314
14315   if (overflow)
14316     {
14317       complaint (_("Offset %d is not terminated "
14318                    "for DW_AT_ranges attribute"),
14319                  offset);
14320       return false;
14321     }
14322
14323   return true;
14324 }
14325
14326 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
14327    Callback's type should be:
14328     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
14329    Return 1 if the attributes are present and valid, otherwise, return 0.  */
14330
14331 template <typename Callback>
14332 static int
14333 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
14334                        Callback &&callback)
14335 {
14336   struct dwarf2_per_objfile *dwarf2_per_objfile
14337       = cu->per_cu->dwarf2_per_objfile;
14338   struct objfile *objfile = dwarf2_per_objfile->objfile;
14339   struct comp_unit_head *cu_header = &cu->header;
14340   bfd *obfd = objfile->obfd;
14341   unsigned int addr_size = cu_header->addr_size;
14342   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
14343   /* Base address selection entry.  */
14344   CORE_ADDR base;
14345   int found_base;
14346   unsigned int dummy;
14347   const gdb_byte *buffer;
14348   CORE_ADDR baseaddr;
14349
14350   if (cu_header->version >= 5)
14351     return dwarf2_rnglists_process (offset, cu, callback);
14352
14353   found_base = cu->base_known;
14354   base = cu->base_address;
14355
14356   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
14357   if (offset >= dwarf2_per_objfile->ranges.size)
14358     {
14359       complaint (_("Offset %d out of bounds for DW_AT_ranges attribute"),
14360                  offset);
14361       return 0;
14362     }
14363   buffer = dwarf2_per_objfile->ranges.buffer + offset;
14364
14365   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
14366
14367   while (1)
14368     {
14369       CORE_ADDR range_beginning, range_end;
14370
14371       range_beginning = read_address (obfd, buffer, cu, &dummy);
14372       buffer += addr_size;
14373       range_end = read_address (obfd, buffer, cu, &dummy);
14374       buffer += addr_size;
14375       offset += 2 * addr_size;
14376
14377       /* An end of list marker is a pair of zero addresses.  */
14378       if (range_beginning == 0 && range_end == 0)
14379         /* Found the end of list entry.  */
14380         break;
14381
14382       /* Each base address selection entry is a pair of 2 values.
14383          The first is the largest possible address, the second is
14384          the base address.  Check for a base address here.  */
14385       if ((range_beginning & mask) == mask)
14386         {
14387           /* If we found the largest possible address, then we already
14388              have the base address in range_end.  */
14389           base = range_end;
14390           found_base = 1;
14391           continue;
14392         }
14393
14394       if (!found_base)
14395         {
14396           /* We have no valid base address for the ranges
14397              data.  */
14398           complaint (_("Invalid .debug_ranges data (no base address)"));
14399           return 0;
14400         }
14401
14402       if (range_beginning > range_end)
14403         {
14404           /* Inverted range entries are invalid.  */
14405           complaint (_("Invalid .debug_ranges data (inverted range)"));
14406           return 0;
14407         }
14408
14409       /* Empty range entries have no effect.  */
14410       if (range_beginning == range_end)
14411         continue;
14412
14413       range_beginning += base;
14414       range_end += base;
14415
14416       /* A not-uncommon case of bad debug info.
14417          Don't pollute the addrmap with bad data.  */
14418       if (range_beginning + baseaddr == 0
14419           && !dwarf2_per_objfile->has_section_at_zero)
14420         {
14421           complaint (_(".debug_ranges entry has start address of zero"
14422                        " [in module %s]"), objfile_name (objfile));
14423           continue;
14424         }
14425
14426       callback (range_beginning, range_end);
14427     }
14428
14429   return 1;
14430 }
14431
14432 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
14433    Return 1 if the attributes are present and valid, otherwise, return 0.
14434    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
14435
14436 static int
14437 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
14438                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
14439                     struct partial_symtab *ranges_pst)
14440 {
14441   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14442   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14443   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
14444                                        SECT_OFF_TEXT (objfile));
14445   int low_set = 0;
14446   CORE_ADDR low = 0;
14447   CORE_ADDR high = 0;
14448   int retval;
14449
14450   retval = dwarf2_ranges_process (offset, cu,
14451     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
14452     {
14453       if (ranges_pst != NULL)
14454         {
14455           CORE_ADDR lowpc;
14456           CORE_ADDR highpc;
14457
14458           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14459                                               range_beginning + baseaddr);
14460           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
14461                                                range_end + baseaddr);
14462           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
14463                              ranges_pst);
14464         }
14465
14466       /* FIXME: This is recording everything as a low-high
14467          segment of consecutive addresses.  We should have a
14468          data structure for discontiguous block ranges
14469          instead.  */
14470       if (! low_set)
14471         {
14472           low = range_beginning;
14473           high = range_end;
14474           low_set = 1;
14475         }
14476       else
14477         {
14478           if (range_beginning < low)
14479             low = range_beginning;
14480           if (range_end > high)
14481             high = range_end;
14482         }
14483     });
14484   if (!retval)
14485     return 0;
14486
14487   if (! low_set)
14488     /* If the first entry is an end-of-list marker, the range
14489        describes an empty scope, i.e. no instructions.  */
14490     return 0;
14491
14492   if (low_return)
14493     *low_return = low;
14494   if (high_return)
14495     *high_return = high;
14496   return 1;
14497 }
14498
14499 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
14500    definition for the return value.  *LOWPC and *HIGHPC are set iff
14501    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
14502
14503 static enum pc_bounds_kind
14504 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
14505                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
14506                       struct partial_symtab *pst)
14507 {
14508   struct dwarf2_per_objfile *dwarf2_per_objfile
14509     = cu->per_cu->dwarf2_per_objfile;
14510   struct attribute *attr;
14511   struct attribute *attr_high;
14512   CORE_ADDR low = 0;
14513   CORE_ADDR high = 0;
14514   enum pc_bounds_kind ret;
14515
14516   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14517   if (attr_high)
14518     {
14519       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14520       if (attr)
14521         {
14522           low = attr_value_as_address (attr);
14523           high = attr_value_as_address (attr_high);
14524           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14525             high += low;
14526         }
14527       else
14528         /* Found high w/o low attribute.  */
14529         return PC_BOUNDS_INVALID;
14530
14531       /* Found consecutive range of addresses.  */
14532       ret = PC_BOUNDS_HIGH_LOW;
14533     }
14534   else
14535     {
14536       attr = dwarf2_attr (die, DW_AT_ranges, cu);
14537       if (attr != NULL)
14538         {
14539           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14540              We take advantage of the fact that DW_AT_ranges does not appear
14541              in DW_TAG_compile_unit of DWO files.  */
14542           int need_ranges_base = die->tag != DW_TAG_compile_unit;
14543           unsigned int ranges_offset = (DW_UNSND (attr)
14544                                         + (need_ranges_base
14545                                            ? cu->ranges_base
14546                                            : 0));
14547
14548           /* Value of the DW_AT_ranges attribute is the offset in the
14549              .debug_ranges section.  */
14550           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
14551             return PC_BOUNDS_INVALID;
14552           /* Found discontinuous range of addresses.  */
14553           ret = PC_BOUNDS_RANGES;
14554         }
14555       else
14556         return PC_BOUNDS_NOT_PRESENT;
14557     }
14558
14559   /* partial_die_info::read has also the strict LOW < HIGH requirement.  */
14560   if (high <= low)
14561     return PC_BOUNDS_INVALID;
14562
14563   /* When using the GNU linker, .gnu.linkonce. sections are used to
14564      eliminate duplicate copies of functions and vtables and such.
14565      The linker will arbitrarily choose one and discard the others.
14566      The AT_*_pc values for such functions refer to local labels in
14567      these sections.  If the section from that file was discarded, the
14568      labels are not in the output, so the relocs get a value of 0.
14569      If this is a discarded function, mark the pc bounds as invalid,
14570      so that GDB will ignore it.  */
14571   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
14572     return PC_BOUNDS_INVALID;
14573
14574   *lowpc = low;
14575   if (highpc)
14576     *highpc = high;
14577   return ret;
14578 }
14579
14580 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
14581    its low and high PC addresses.  Do nothing if these addresses could not
14582    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
14583    and HIGHPC to the high address if greater than HIGHPC.  */
14584
14585 static void
14586 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
14587                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
14588                                  struct dwarf2_cu *cu)
14589 {
14590   CORE_ADDR low, high;
14591   struct die_info *child = die->child;
14592
14593   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
14594     {
14595       *lowpc = std::min (*lowpc, low);
14596       *highpc = std::max (*highpc, high);
14597     }
14598
14599   /* If the language does not allow nested subprograms (either inside
14600      subprograms or lexical blocks), we're done.  */
14601   if (cu->language != language_ada)
14602     return;
14603
14604   /* Check all the children of the given DIE.  If it contains nested
14605      subprograms, then check their pc bounds.  Likewise, we need to
14606      check lexical blocks as well, as they may also contain subprogram
14607      definitions.  */
14608   while (child && child->tag)
14609     {
14610       if (child->tag == DW_TAG_subprogram
14611           || child->tag == DW_TAG_lexical_block)
14612         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
14613       child = sibling_die (child);
14614     }
14615 }
14616
14617 /* Get the low and high pc's represented by the scope DIE, and store
14618    them in *LOWPC and *HIGHPC.  If the correct values can't be
14619    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
14620
14621 static void
14622 get_scope_pc_bounds (struct die_info *die,
14623                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
14624                      struct dwarf2_cu *cu)
14625 {
14626   CORE_ADDR best_low = (CORE_ADDR) -1;
14627   CORE_ADDR best_high = (CORE_ADDR) 0;
14628   CORE_ADDR current_low, current_high;
14629
14630   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
14631       >= PC_BOUNDS_RANGES)
14632     {
14633       best_low = current_low;
14634       best_high = current_high;
14635     }
14636   else
14637     {
14638       struct die_info *child = die->child;
14639
14640       while (child && child->tag)
14641         {
14642           switch (child->tag) {
14643           case DW_TAG_subprogram:
14644             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
14645             break;
14646           case DW_TAG_namespace:
14647           case DW_TAG_module:
14648             /* FIXME: carlton/2004-01-16: Should we do this for
14649                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
14650                that current GCC's always emit the DIEs corresponding
14651                to definitions of methods of classes as children of a
14652                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
14653                the DIEs giving the declarations, which could be
14654                anywhere).  But I don't see any reason why the
14655                standards says that they have to be there.  */
14656             get_scope_pc_bounds (child, &current_low, &current_high, cu);
14657
14658             if (current_low != ((CORE_ADDR) -1))
14659               {
14660                 best_low = std::min (best_low, current_low);
14661                 best_high = std::max (best_high, current_high);
14662               }
14663             break;
14664           default:
14665             /* Ignore.  */
14666             break;
14667           }
14668
14669           child = sibling_die (child);
14670         }
14671     }
14672
14673   *lowpc = best_low;
14674   *highpc = best_high;
14675 }
14676
14677 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
14678    in DIE.  */
14679
14680 static void
14681 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
14682                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
14683 {
14684   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14685   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14686   struct attribute *attr;
14687   struct attribute *attr_high;
14688
14689   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
14690   if (attr_high)
14691     {
14692       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
14693       if (attr)
14694         {
14695           CORE_ADDR low = attr_value_as_address (attr);
14696           CORE_ADDR high = attr_value_as_address (attr_high);
14697
14698           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
14699             high += low;
14700
14701           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
14702           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
14703           record_block_range (block, low, high - 1);
14704         }
14705     }
14706
14707   attr = dwarf2_attr (die, DW_AT_ranges, cu);
14708   if (attr)
14709     {
14710       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
14711          We take advantage of the fact that DW_AT_ranges does not appear
14712          in DW_TAG_compile_unit of DWO files.  */
14713       int need_ranges_base = die->tag != DW_TAG_compile_unit;
14714
14715       /* The value of the DW_AT_ranges attribute is the offset of the
14716          address range list in the .debug_ranges section.  */
14717       unsigned long offset = (DW_UNSND (attr)
14718                               + (need_ranges_base ? cu->ranges_base : 0));
14719
14720       dwarf2_ranges_process (offset, cu,
14721         [&] (CORE_ADDR start, CORE_ADDR end)
14722         {
14723           start += baseaddr;
14724           end += baseaddr;
14725           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
14726           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
14727           record_block_range (block, start, end - 1);
14728         });
14729     }
14730 }
14731
14732 /* Check whether the producer field indicates either of GCC < 4.6, or the
14733    Intel C/C++ compiler, and cache the result in CU.  */
14734
14735 static void
14736 check_producer (struct dwarf2_cu *cu)
14737 {
14738   int major, minor;
14739
14740   if (cu->producer == NULL)
14741     {
14742       /* For unknown compilers expect their behavior is DWARF version
14743          compliant.
14744
14745          GCC started to support .debug_types sections by -gdwarf-4 since
14746          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
14747          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
14748          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
14749          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
14750     }
14751   else if (producer_is_gcc (cu->producer, &major, &minor))
14752     {
14753       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
14754       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
14755     }
14756   else if (producer_is_icc (cu->producer, &major, &minor))
14757     cu->producer_is_icc_lt_14 = major < 14;
14758   else
14759     {
14760       /* For other non-GCC compilers, expect their behavior is DWARF version
14761          compliant.  */
14762     }
14763
14764   cu->checked_producer = 1;
14765 }
14766
14767 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
14768    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
14769    during 4.6.0 experimental.  */
14770
14771 static int
14772 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
14773 {
14774   if (!cu->checked_producer)
14775     check_producer (cu);
14776
14777   return cu->producer_is_gxx_lt_4_6;
14778 }
14779
14780 /* Return the default accessibility type if it is not overriden by
14781    DW_AT_accessibility.  */
14782
14783 static enum dwarf_access_attribute
14784 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
14785 {
14786   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
14787     {
14788       /* The default DWARF 2 accessibility for members is public, the default
14789          accessibility for inheritance is private.  */
14790
14791       if (die->tag != DW_TAG_inheritance)
14792         return DW_ACCESS_public;
14793       else
14794         return DW_ACCESS_private;
14795     }
14796   else
14797     {
14798       /* DWARF 3+ defines the default accessibility a different way.  The same
14799          rules apply now for DW_TAG_inheritance as for the members and it only
14800          depends on the container kind.  */
14801
14802       if (die->parent->tag == DW_TAG_class_type)
14803         return DW_ACCESS_private;
14804       else
14805         return DW_ACCESS_public;
14806     }
14807 }
14808
14809 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
14810    offset.  If the attribute was not found return 0, otherwise return
14811    1.  If it was found but could not properly be handled, set *OFFSET
14812    to 0.  */
14813
14814 static int
14815 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
14816                              LONGEST *offset)
14817 {
14818   struct attribute *attr;
14819
14820   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
14821   if (attr != NULL)
14822     {
14823       *offset = 0;
14824
14825       /* Note that we do not check for a section offset first here.
14826          This is because DW_AT_data_member_location is new in DWARF 4,
14827          so if we see it, we can assume that a constant form is really
14828          a constant and not a section offset.  */
14829       if (attr_form_is_constant (attr))
14830         *offset = dwarf2_get_attr_constant_value (attr, 0);
14831       else if (attr_form_is_section_offset (attr))
14832         dwarf2_complex_location_expr_complaint ();
14833       else if (attr_form_is_block (attr))
14834         *offset = decode_locdesc (DW_BLOCK (attr), cu);
14835       else
14836         dwarf2_complex_location_expr_complaint ();
14837
14838       return 1;
14839     }
14840
14841   return 0;
14842 }
14843
14844 /* Add an aggregate field to the field list.  */
14845
14846 static void
14847 dwarf2_add_field (struct field_info *fip, struct die_info *die,
14848                   struct dwarf2_cu *cu)
14849 {
14850   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
14851   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14852   struct nextfield *new_field;
14853   struct attribute *attr;
14854   struct field *fp;
14855   const char *fieldname = "";
14856
14857   if (die->tag == DW_TAG_inheritance)
14858     {
14859       fip->baseclasses.emplace_back ();
14860       new_field = &fip->baseclasses.back ();
14861     }
14862   else
14863     {
14864       fip->fields.emplace_back ();
14865       new_field = &fip->fields.back ();
14866     }
14867
14868   fip->nfields++;
14869
14870   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14871   if (attr)
14872     new_field->accessibility = DW_UNSND (attr);
14873   else
14874     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
14875   if (new_field->accessibility != DW_ACCESS_public)
14876     fip->non_public_fields = 1;
14877
14878   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14879   if (attr)
14880     new_field->virtuality = DW_UNSND (attr);
14881   else
14882     new_field->virtuality = DW_VIRTUALITY_none;
14883
14884   fp = &new_field->field;
14885
14886   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
14887     {
14888       LONGEST offset;
14889
14890       /* Data member other than a C++ static data member.  */
14891
14892       /* Get type of field.  */
14893       fp->type = die_type (die, cu);
14894
14895       SET_FIELD_BITPOS (*fp, 0);
14896
14897       /* Get bit size of field (zero if none).  */
14898       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
14899       if (attr)
14900         {
14901           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
14902         }
14903       else
14904         {
14905           FIELD_BITSIZE (*fp) = 0;
14906         }
14907
14908       /* Get bit offset of field.  */
14909       if (handle_data_member_location (die, cu, &offset))
14910         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14911       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
14912       if (attr)
14913         {
14914           if (gdbarch_bits_big_endian (gdbarch))
14915             {
14916               /* For big endian bits, the DW_AT_bit_offset gives the
14917                  additional bit offset from the MSB of the containing
14918                  anonymous object to the MSB of the field.  We don't
14919                  have to do anything special since we don't need to
14920                  know the size of the anonymous object.  */
14921               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
14922             }
14923           else
14924             {
14925               /* For little endian bits, compute the bit offset to the
14926                  MSB of the anonymous object, subtract off the number of
14927                  bits from the MSB of the field to the MSB of the
14928                  object, and then subtract off the number of bits of
14929                  the field itself.  The result is the bit offset of
14930                  the LSB of the field.  */
14931               int anonymous_size;
14932               int bit_offset = DW_UNSND (attr);
14933
14934               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14935               if (attr)
14936                 {
14937                   /* The size of the anonymous object containing
14938                      the bit field is explicit, so use the
14939                      indicated size (in bytes).  */
14940                   anonymous_size = DW_UNSND (attr);
14941                 }
14942               else
14943                 {
14944                   /* The size of the anonymous object containing
14945                      the bit field must be inferred from the type
14946                      attribute of the data member containing the
14947                      bit field.  */
14948                   anonymous_size = TYPE_LENGTH (fp->type);
14949                 }
14950               SET_FIELD_BITPOS (*fp,
14951                                 (FIELD_BITPOS (*fp)
14952                                  + anonymous_size * bits_per_byte
14953                                  - bit_offset - FIELD_BITSIZE (*fp)));
14954             }
14955         }
14956       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
14957       if (attr != NULL)
14958         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
14959                                 + dwarf2_get_attr_constant_value (attr, 0)));
14960
14961       /* Get name of field.  */
14962       fieldname = dwarf2_name (die, cu);
14963       if (fieldname == NULL)
14964         fieldname = "";
14965
14966       /* The name is already allocated along with this objfile, so we don't
14967          need to duplicate it for the type.  */
14968       fp->name = fieldname;
14969
14970       /* Change accessibility for artificial fields (e.g. virtual table
14971          pointer or virtual base class pointer) to private.  */
14972       if (dwarf2_attr (die, DW_AT_artificial, cu))
14973         {
14974           FIELD_ARTIFICIAL (*fp) = 1;
14975           new_field->accessibility = DW_ACCESS_private;
14976           fip->non_public_fields = 1;
14977         }
14978     }
14979   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
14980     {
14981       /* C++ static member.  */
14982
14983       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
14984          is a declaration, but all versions of G++ as of this writing
14985          (so through at least 3.2.1) incorrectly generate
14986          DW_TAG_variable tags.  */
14987
14988       const char *physname;
14989
14990       /* Get name of field.  */
14991       fieldname = dwarf2_name (die, cu);
14992       if (fieldname == NULL)
14993         return;
14994
14995       attr = dwarf2_attr (die, DW_AT_const_value, cu);
14996       if (attr
14997           /* Only create a symbol if this is an external value.
14998              new_symbol checks this and puts the value in the global symbol
14999              table, which we want.  If it is not external, new_symbol
15000              will try to put the value in cu->list_in_scope which is wrong.  */
15001           && dwarf2_flag_true_p (die, DW_AT_external, cu))
15002         {
15003           /* A static const member, not much different than an enum as far as
15004              we're concerned, except that we can support more types.  */
15005           new_symbol (die, NULL, cu);
15006         }
15007
15008       /* Get physical name.  */
15009       physname = dwarf2_physname (fieldname, die, cu);
15010
15011       /* The name is already allocated along with this objfile, so we don't
15012          need to duplicate it for the type.  */
15013       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
15014       FIELD_TYPE (*fp) = die_type (die, cu);
15015       FIELD_NAME (*fp) = fieldname;
15016     }
15017   else if (die->tag == DW_TAG_inheritance)
15018     {
15019       LONGEST offset;
15020
15021       /* C++ base class field.  */
15022       if (handle_data_member_location (die, cu, &offset))
15023         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
15024       FIELD_BITSIZE (*fp) = 0;
15025       FIELD_TYPE (*fp) = die_type (die, cu);
15026       FIELD_NAME (*fp) = TYPE_NAME (fp->type);
15027     }
15028   else if (die->tag == DW_TAG_variant_part)
15029     {
15030       /* process_structure_scope will treat this DIE as a union.  */
15031       process_structure_scope (die, cu);
15032
15033       /* The variant part is relative to the start of the enclosing
15034          structure.  */
15035       SET_FIELD_BITPOS (*fp, 0);
15036       fp->type = get_die_type (die, cu);
15037       fp->artificial = 1;
15038       fp->name = "<<variant>>";
15039     }
15040   else
15041     gdb_assert_not_reached ("missing case in dwarf2_add_field");
15042 }
15043
15044 /* Can the type given by DIE define another type?  */
15045
15046 static bool
15047 type_can_define_types (const struct die_info *die)
15048 {
15049   switch (die->tag)
15050     {
15051     case DW_TAG_typedef:
15052     case DW_TAG_class_type:
15053     case DW_TAG_structure_type:
15054     case DW_TAG_union_type:
15055     case DW_TAG_enumeration_type:
15056       return true;
15057
15058     default:
15059       return false;
15060     }
15061 }
15062
15063 /* Add a type definition defined in the scope of the FIP's class.  */
15064
15065 static void
15066 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
15067                       struct dwarf2_cu *cu)
15068 {
15069   struct decl_field fp;
15070   memset (&fp, 0, sizeof (fp));
15071
15072   gdb_assert (type_can_define_types (die));
15073
15074   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
15075   fp.name = dwarf2_name (die, cu);
15076   fp.type = read_type_die (die, cu);
15077
15078   /* Save accessibility.  */
15079   enum dwarf_access_attribute accessibility;
15080   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15081   if (attr != NULL)
15082     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15083   else
15084     accessibility = dwarf2_default_access_attribute (die, cu);
15085   switch (accessibility)
15086     {
15087     case DW_ACCESS_public:
15088       /* The assumed value if neither private nor protected.  */
15089       break;
15090     case DW_ACCESS_private:
15091       fp.is_private = 1;
15092       break;
15093     case DW_ACCESS_protected:
15094       fp.is_protected = 1;
15095       break;
15096     default:
15097       complaint (_("Unhandled DW_AT_accessibility value (%x)"), accessibility);
15098     }
15099
15100   if (die->tag == DW_TAG_typedef)
15101     fip->typedef_field_list.push_back (fp);
15102   else
15103     fip->nested_types_list.push_back (fp);
15104 }
15105
15106 /* Create the vector of fields, and attach it to the type.  */
15107
15108 static void
15109 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
15110                               struct dwarf2_cu *cu)
15111 {
15112   int nfields = fip->nfields;
15113
15114   /* Record the field count, allocate space for the array of fields,
15115      and create blank accessibility bitfields if necessary.  */
15116   TYPE_NFIELDS (type) = nfields;
15117   TYPE_FIELDS (type) = (struct field *)
15118     TYPE_ZALLOC (type, sizeof (struct field) * nfields);
15119
15120   if (fip->non_public_fields && cu->language != language_ada)
15121     {
15122       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15123
15124       TYPE_FIELD_PRIVATE_BITS (type) =
15125         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15126       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
15127
15128       TYPE_FIELD_PROTECTED_BITS (type) =
15129         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15130       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
15131
15132       TYPE_FIELD_IGNORE_BITS (type) =
15133         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
15134       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
15135     }
15136
15137   /* If the type has baseclasses, allocate and clear a bit vector for
15138      TYPE_FIELD_VIRTUAL_BITS.  */
15139   if (!fip->baseclasses.empty () && cu->language != language_ada)
15140     {
15141       int num_bytes = B_BYTES (fip->baseclasses.size ());
15142       unsigned char *pointer;
15143
15144       ALLOCATE_CPLUS_STRUCT_TYPE (type);
15145       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
15146       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
15147       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->baseclasses.size ());
15148       TYPE_N_BASECLASSES (type) = fip->baseclasses.size ();
15149     }
15150
15151   if (TYPE_FLAG_DISCRIMINATED_UNION (type))
15152     {
15153       struct discriminant_info *di = alloc_discriminant_info (type, -1, -1);
15154
15155       for (int index = 0; index < nfields; ++index)
15156         {
15157           struct nextfield &field = fip->fields[index];
15158
15159           if (field.variant.is_discriminant)
15160             di->discriminant_index = index;
15161           else if (field.variant.default_branch)
15162             di->default_index = index;
15163           else
15164             di->discriminants[index] = field.variant.discriminant_value;
15165         }
15166     }
15167
15168   /* Copy the saved-up fields into the field vector.  */
15169   for (int i = 0; i < nfields; ++i)
15170     {
15171       struct nextfield &field
15172         = ((i < fip->baseclasses.size ()) ? fip->baseclasses[i]
15173            : fip->fields[i - fip->baseclasses.size ()]);
15174
15175       TYPE_FIELD (type, i) = field.field;
15176       switch (field.accessibility)
15177         {
15178         case DW_ACCESS_private:
15179           if (cu->language != language_ada)
15180             SET_TYPE_FIELD_PRIVATE (type, i);
15181           break;
15182
15183         case DW_ACCESS_protected:
15184           if (cu->language != language_ada)
15185             SET_TYPE_FIELD_PROTECTED (type, i);
15186           break;
15187
15188         case DW_ACCESS_public:
15189           break;
15190
15191         default:
15192           /* Unknown accessibility.  Complain and treat it as public.  */
15193           {
15194             complaint (_("unsupported accessibility %d"),
15195                        field.accessibility);
15196           }
15197           break;
15198         }
15199       if (i < fip->baseclasses.size ())
15200         {
15201           switch (field.virtuality)
15202             {
15203             case DW_VIRTUALITY_virtual:
15204             case DW_VIRTUALITY_pure_virtual:
15205               if (cu->language == language_ada)
15206                 error (_("unexpected virtuality in component of Ada type"));
15207               SET_TYPE_FIELD_VIRTUAL (type, i);
15208               break;
15209             }
15210         }
15211     }
15212 }
15213
15214 /* Return true if this member function is a constructor, false
15215    otherwise.  */
15216
15217 static int
15218 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
15219 {
15220   const char *fieldname;
15221   const char *type_name;
15222   int len;
15223
15224   if (die->parent == NULL)
15225     return 0;
15226
15227   if (die->parent->tag != DW_TAG_structure_type
15228       && die->parent->tag != DW_TAG_union_type
15229       && die->parent->tag != DW_TAG_class_type)
15230     return 0;
15231
15232   fieldname = dwarf2_name (die, cu);
15233   type_name = dwarf2_name (die->parent, cu);
15234   if (fieldname == NULL || type_name == NULL)
15235     return 0;
15236
15237   len = strlen (fieldname);
15238   return (strncmp (fieldname, type_name, len) == 0
15239           && (type_name[len] == '\0' || type_name[len] == '<'));
15240 }
15241
15242 /* Add a member function to the proper fieldlist.  */
15243
15244 static void
15245 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
15246                       struct type *type, struct dwarf2_cu *cu)
15247 {
15248   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15249   struct attribute *attr;
15250   int i;
15251   struct fnfieldlist *flp = nullptr;
15252   struct fn_field *fnp;
15253   const char *fieldname;
15254   struct type *this_type;
15255   enum dwarf_access_attribute accessibility;
15256
15257   if (cu->language == language_ada)
15258     error (_("unexpected member function in Ada type"));
15259
15260   /* Get name of member function.  */
15261   fieldname = dwarf2_name (die, cu);
15262   if (fieldname == NULL)
15263     return;
15264
15265   /* Look up member function name in fieldlist.  */
15266   for (i = 0; i < fip->fnfieldlists.size (); i++)
15267     {
15268       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
15269         {
15270           flp = &fip->fnfieldlists[i];
15271           break;
15272         }
15273     }
15274
15275   /* Create a new fnfieldlist if necessary.  */
15276   if (flp == nullptr)
15277     {
15278       fip->fnfieldlists.emplace_back ();
15279       flp = &fip->fnfieldlists.back ();
15280       flp->name = fieldname;
15281       i = fip->fnfieldlists.size () - 1;
15282     }
15283
15284   /* Create a new member function field and add it to the vector of
15285      fnfieldlists.  */
15286   flp->fnfields.emplace_back ();
15287   fnp = &flp->fnfields.back ();
15288
15289   /* Delay processing of the physname until later.  */
15290   if (cu->language == language_cplus)
15291     add_to_method_list (type, i, flp->fnfields.size () - 1, fieldname,
15292                         die, cu);
15293   else
15294     {
15295       const char *physname = dwarf2_physname (fieldname, die, cu);
15296       fnp->physname = physname ? physname : "";
15297     }
15298
15299   fnp->type = alloc_type (objfile);
15300   this_type = read_type_die (die, cu);
15301   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
15302     {
15303       int nparams = TYPE_NFIELDS (this_type);
15304
15305       /* TYPE is the domain of this method, and THIS_TYPE is the type
15306            of the method itself (TYPE_CODE_METHOD).  */
15307       smash_to_method_type (fnp->type, type,
15308                             TYPE_TARGET_TYPE (this_type),
15309                             TYPE_FIELDS (this_type),
15310                             TYPE_NFIELDS (this_type),
15311                             TYPE_VARARGS (this_type));
15312
15313       /* Handle static member functions.
15314          Dwarf2 has no clean way to discern C++ static and non-static
15315          member functions.  G++ helps GDB by marking the first
15316          parameter for non-static member functions (which is the this
15317          pointer) as artificial.  We obtain this information from
15318          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
15319       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
15320         fnp->voffset = VOFFSET_STATIC;
15321     }
15322   else
15323     complaint (_("member function type missing for '%s'"),
15324                dwarf2_full_name (fieldname, die, cu));
15325
15326   /* Get fcontext from DW_AT_containing_type if present.  */
15327   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15328     fnp->fcontext = die_containing_type (die, cu);
15329
15330   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
15331      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
15332
15333   /* Get accessibility.  */
15334   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
15335   if (attr)
15336     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
15337   else
15338     accessibility = dwarf2_default_access_attribute (die, cu);
15339   switch (accessibility)
15340     {
15341     case DW_ACCESS_private:
15342       fnp->is_private = 1;
15343       break;
15344     case DW_ACCESS_protected:
15345       fnp->is_protected = 1;
15346       break;
15347     }
15348
15349   /* Check for artificial methods.  */
15350   attr = dwarf2_attr (die, DW_AT_artificial, cu);
15351   if (attr && DW_UNSND (attr) != 0)
15352     fnp->is_artificial = 1;
15353
15354   fnp->is_constructor = dwarf2_is_constructor (die, cu);
15355
15356   /* Get index in virtual function table if it is a virtual member
15357      function.  For older versions of GCC, this is an offset in the
15358      appropriate virtual table, as specified by DW_AT_containing_type.
15359      For everyone else, it is an expression to be evaluated relative
15360      to the object address.  */
15361
15362   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
15363   if (attr)
15364     {
15365       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
15366         {
15367           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
15368             {
15369               /* Old-style GCC.  */
15370               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
15371             }
15372           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
15373                    || (DW_BLOCK (attr)->size > 1
15374                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
15375                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
15376             {
15377               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
15378               if ((fnp->voffset % cu->header.addr_size) != 0)
15379                 dwarf2_complex_location_expr_complaint ();
15380               else
15381                 fnp->voffset /= cu->header.addr_size;
15382               fnp->voffset += 2;
15383             }
15384           else
15385             dwarf2_complex_location_expr_complaint ();
15386
15387           if (!fnp->fcontext)
15388             {
15389               /* If there is no `this' field and no DW_AT_containing_type,
15390                  we cannot actually find a base class context for the
15391                  vtable!  */
15392               if (TYPE_NFIELDS (this_type) == 0
15393                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
15394                 {
15395                   complaint (_("cannot determine context for virtual member "
15396                                "function \"%s\" (offset %s)"),
15397                              fieldname, sect_offset_str (die->sect_off));
15398                 }
15399               else
15400                 {
15401                   fnp->fcontext
15402                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
15403                 }
15404             }
15405         }
15406       else if (attr_form_is_section_offset (attr))
15407         {
15408           dwarf2_complex_location_expr_complaint ();
15409         }
15410       else
15411         {
15412           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
15413                                                  fieldname);
15414         }
15415     }
15416   else
15417     {
15418       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
15419       if (attr && DW_UNSND (attr))
15420         {
15421           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
15422           complaint (_("Member function \"%s\" (offset %s) is virtual "
15423                        "but the vtable offset is not specified"),
15424                      fieldname, sect_offset_str (die->sect_off));
15425           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15426           TYPE_CPLUS_DYNAMIC (type) = 1;
15427         }
15428     }
15429 }
15430
15431 /* Create the vector of member function fields, and attach it to the type.  */
15432
15433 static void
15434 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
15435                                  struct dwarf2_cu *cu)
15436 {
15437   if (cu->language == language_ada)
15438     error (_("unexpected member functions in Ada type"));
15439
15440   ALLOCATE_CPLUS_STRUCT_TYPE (type);
15441   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
15442     TYPE_ALLOC (type,
15443                 sizeof (struct fn_fieldlist) * fip->fnfieldlists.size ());
15444
15445   for (int i = 0; i < fip->fnfieldlists.size (); i++)
15446     {
15447       struct fnfieldlist &nf = fip->fnfieldlists[i];
15448       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
15449
15450       TYPE_FN_FIELDLIST_NAME (type, i) = nf.name;
15451       TYPE_FN_FIELDLIST_LENGTH (type, i) = nf.fnfields.size ();
15452       fn_flp->fn_fields = (struct fn_field *)
15453         TYPE_ALLOC (type, sizeof (struct fn_field) * nf.fnfields.size ());
15454
15455       for (int k = 0; k < nf.fnfields.size (); ++k)
15456         fn_flp->fn_fields[k] = nf.fnfields[k];
15457     }
15458
15459   TYPE_NFN_FIELDS (type) = fip->fnfieldlists.size ();
15460 }
15461
15462 /* Returns non-zero if NAME is the name of a vtable member in CU's
15463    language, zero otherwise.  */
15464 static int
15465 is_vtable_name (const char *name, struct dwarf2_cu *cu)
15466 {
15467   static const char vptr[] = "_vptr";
15468
15469   /* Look for the C++ form of the vtable.  */
15470   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
15471     return 1;
15472
15473   return 0;
15474 }
15475
15476 /* GCC outputs unnamed structures that are really pointers to member
15477    functions, with the ABI-specified layout.  If TYPE describes
15478    such a structure, smash it into a member function type.
15479
15480    GCC shouldn't do this; it should just output pointer to member DIEs.
15481    This is GCC PR debug/28767.  */
15482
15483 static void
15484 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
15485 {
15486   struct type *pfn_type, *self_type, *new_type;
15487
15488   /* Check for a structure with no name and two children.  */
15489   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
15490     return;
15491
15492   /* Check for __pfn and __delta members.  */
15493   if (TYPE_FIELD_NAME (type, 0) == NULL
15494       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
15495       || TYPE_FIELD_NAME (type, 1) == NULL
15496       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
15497     return;
15498
15499   /* Find the type of the method.  */
15500   pfn_type = TYPE_FIELD_TYPE (type, 0);
15501   if (pfn_type == NULL
15502       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
15503       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
15504     return;
15505
15506   /* Look for the "this" argument.  */
15507   pfn_type = TYPE_TARGET_TYPE (pfn_type);
15508   if (TYPE_NFIELDS (pfn_type) == 0
15509       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
15510       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
15511     return;
15512
15513   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
15514   new_type = alloc_type (objfile);
15515   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
15516                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
15517                         TYPE_VARARGS (pfn_type));
15518   smash_to_methodptr_type (type, new_type);
15519 }
15520
15521 /* If the DIE has a DW_AT_alignment attribute, return its value, doing
15522    appropriate error checking and issuing complaints if there is a
15523    problem.  */
15524
15525 static ULONGEST
15526 get_alignment (struct dwarf2_cu *cu, struct die_info *die)
15527 {
15528   struct attribute *attr = dwarf2_attr (die, DW_AT_alignment, cu);
15529
15530   if (attr == nullptr)
15531     return 0;
15532
15533   if (!attr_form_is_constant (attr))
15534     {
15535       complaint (_("DW_AT_alignment must have constant form"
15536                    " - DIE at %s [in module %s]"),
15537                  sect_offset_str (die->sect_off),
15538                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15539       return 0;
15540     }
15541
15542   ULONGEST align;
15543   if (attr->form == DW_FORM_sdata)
15544     {
15545       LONGEST val = DW_SND (attr);
15546       if (val < 0)
15547         {
15548           complaint (_("DW_AT_alignment value must not be negative"
15549                        " - DIE at %s [in module %s]"),
15550                      sect_offset_str (die->sect_off),
15551                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15552           return 0;
15553         }
15554       align = val;
15555     }
15556   else
15557     align = DW_UNSND (attr);
15558
15559   if (align == 0)
15560     {
15561       complaint (_("DW_AT_alignment value must not be zero"
15562                    " - DIE at %s [in module %s]"),
15563                  sect_offset_str (die->sect_off),
15564                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15565       return 0;
15566     }
15567   if ((align & (align - 1)) != 0)
15568     {
15569       complaint (_("DW_AT_alignment value must be a power of 2"
15570                    " - DIE at %s [in module %s]"),
15571                  sect_offset_str (die->sect_off),
15572                  objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15573       return 0;
15574     }
15575
15576   return align;
15577 }
15578
15579 /* If the DIE has a DW_AT_alignment attribute, use its value to set
15580    the alignment for TYPE.  */
15581
15582 static void
15583 maybe_set_alignment (struct dwarf2_cu *cu, struct die_info *die,
15584                      struct type *type)
15585 {
15586   if (!set_type_align (type, get_alignment (cu, die)))
15587     complaint (_("DW_AT_alignment value too large"
15588                  " - DIE at %s [in module %s]"),
15589                sect_offset_str (die->sect_off),
15590                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15591 }
15592
15593 /* Called when we find the DIE that starts a structure or union scope
15594    (definition) to create a type for the structure or union.  Fill in
15595    the type's name and general properties; the members will not be
15596    processed until process_structure_scope.  A symbol table entry for
15597    the type will also not be done until process_structure_scope (assuming
15598    the type has a name).
15599
15600    NOTE: we need to call these functions regardless of whether or not the
15601    DIE has a DW_AT_name attribute, since it might be an anonymous
15602    structure or union.  This gets the type entered into our set of
15603    user defined types.  */
15604
15605 static struct type *
15606 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
15607 {
15608   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15609   struct type *type;
15610   struct attribute *attr;
15611   const char *name;
15612
15613   /* If the definition of this type lives in .debug_types, read that type.
15614      Don't follow DW_AT_specification though, that will take us back up
15615      the chain and we want to go down.  */
15616   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15617   if (attr)
15618     {
15619       type = get_DW_AT_signature_type (die, attr, cu);
15620
15621       /* The type's CU may not be the same as CU.
15622          Ensure TYPE is recorded with CU in die_type_hash.  */
15623       return set_die_type (die, type, cu);
15624     }
15625
15626   type = alloc_type (objfile);
15627   INIT_CPLUS_SPECIFIC (type);
15628
15629   name = dwarf2_name (die, cu);
15630   if (name != NULL)
15631     {
15632       if (cu->language == language_cplus
15633           || cu->language == language_d
15634           || cu->language == language_rust)
15635         {
15636           const char *full_name = dwarf2_full_name (name, die, cu);
15637
15638           /* dwarf2_full_name might have already finished building the DIE's
15639              type.  If so, there is no need to continue.  */
15640           if (get_die_type (die, cu) != NULL)
15641             return get_die_type (die, cu);
15642
15643           TYPE_NAME (type) = full_name;
15644         }
15645       else
15646         {
15647           /* The name is already allocated along with this objfile, so
15648              we don't need to duplicate it for the type.  */
15649           TYPE_NAME (type) = name;
15650         }
15651     }
15652
15653   if (die->tag == DW_TAG_structure_type)
15654     {
15655       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15656     }
15657   else if (die->tag == DW_TAG_union_type)
15658     {
15659       TYPE_CODE (type) = TYPE_CODE_UNION;
15660     }
15661   else if (die->tag == DW_TAG_variant_part)
15662     {
15663       TYPE_CODE (type) = TYPE_CODE_UNION;
15664       TYPE_FLAG_DISCRIMINATED_UNION (type) = 1;
15665     }
15666   else
15667     {
15668       TYPE_CODE (type) = TYPE_CODE_STRUCT;
15669     }
15670
15671   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
15672     TYPE_DECLARED_CLASS (type) = 1;
15673
15674   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15675   if (attr)
15676     {
15677       if (attr_form_is_constant (attr))
15678         TYPE_LENGTH (type) = DW_UNSND (attr);
15679       else
15680         {
15681           /* For the moment, dynamic type sizes are not supported
15682              by GDB's struct type.  The actual size is determined
15683              on-demand when resolving the type of a given object,
15684              so set the type's length to zero for now.  Otherwise,
15685              we record an expression as the length, and that expression
15686              could lead to a very large value, which could eventually
15687              lead to us trying to allocate that much memory when creating
15688              a value of that type.  */
15689           TYPE_LENGTH (type) = 0;
15690         }
15691     }
15692   else
15693     {
15694       TYPE_LENGTH (type) = 0;
15695     }
15696
15697   maybe_set_alignment (cu, die, type);
15698
15699   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
15700     {
15701       /* ICC<14 does not output the required DW_AT_declaration on
15702          incomplete types, but gives them a size of zero.  */
15703       TYPE_STUB (type) = 1;
15704     }
15705   else
15706     TYPE_STUB_SUPPORTED (type) = 1;
15707
15708   if (die_is_declaration (die, cu))
15709     TYPE_STUB (type) = 1;
15710   else if (attr == NULL && die->child == NULL
15711            && producer_is_realview (cu->producer))
15712     /* RealView does not output the required DW_AT_declaration
15713        on incomplete types.  */
15714     TYPE_STUB (type) = 1;
15715
15716   /* We need to add the type field to the die immediately so we don't
15717      infinitely recurse when dealing with pointers to the structure
15718      type within the structure itself.  */
15719   set_die_type (die, type, cu);
15720
15721   /* set_die_type should be already done.  */
15722   set_descriptive_type (type, die, cu);
15723
15724   return type;
15725 }
15726
15727 /* A helper for process_structure_scope that handles a single member
15728    DIE.  */
15729
15730 static void
15731 handle_struct_member_die (struct die_info *child_die, struct type *type,
15732                           struct field_info *fi,
15733                           std::vector<struct symbol *> *template_args,
15734                           struct dwarf2_cu *cu)
15735 {
15736   if (child_die->tag == DW_TAG_member
15737       || child_die->tag == DW_TAG_variable
15738       || child_die->tag == DW_TAG_variant_part)
15739     {
15740       /* NOTE: carlton/2002-11-05: A C++ static data member
15741          should be a DW_TAG_member that is a declaration, but
15742          all versions of G++ as of this writing (so through at
15743          least 3.2.1) incorrectly generate DW_TAG_variable
15744          tags for them instead.  */
15745       dwarf2_add_field (fi, child_die, cu);
15746     }
15747   else if (child_die->tag == DW_TAG_subprogram)
15748     {
15749       /* Rust doesn't have member functions in the C++ sense.
15750          However, it does emit ordinary functions as children
15751          of a struct DIE.  */
15752       if (cu->language == language_rust)
15753         read_func_scope (child_die, cu);
15754       else
15755         {
15756           /* C++ member function.  */
15757           dwarf2_add_member_fn (fi, child_die, type, cu);
15758         }
15759     }
15760   else if (child_die->tag == DW_TAG_inheritance)
15761     {
15762       /* C++ base class field.  */
15763       dwarf2_add_field (fi, child_die, cu);
15764     }
15765   else if (type_can_define_types (child_die))
15766     dwarf2_add_type_defn (fi, child_die, cu);
15767   else if (child_die->tag == DW_TAG_template_type_param
15768            || child_die->tag == DW_TAG_template_value_param)
15769     {
15770       struct symbol *arg = new_symbol (child_die, NULL, cu);
15771
15772       if (arg != NULL)
15773         template_args->push_back (arg);
15774     }
15775   else if (child_die->tag == DW_TAG_variant)
15776     {
15777       /* In a variant we want to get the discriminant and also add a
15778          field for our sole member child.  */
15779       struct attribute *discr = dwarf2_attr (child_die, DW_AT_discr_value, cu);
15780
15781       for (struct die_info *variant_child = child_die->child;
15782            variant_child != NULL;
15783            variant_child = sibling_die (variant_child))
15784         {
15785           if (variant_child->tag == DW_TAG_member)
15786             {
15787               handle_struct_member_die (variant_child, type, fi,
15788                                         template_args, cu);
15789               /* Only handle the one.  */
15790               break;
15791             }
15792         }
15793
15794       /* We don't handle this but we might as well report it if we see
15795          it.  */
15796       if (dwarf2_attr (child_die, DW_AT_discr_list, cu) != nullptr)
15797           complaint (_("DW_AT_discr_list is not supported yet"
15798                        " - DIE at %s [in module %s]"),
15799                      sect_offset_str (child_die->sect_off),
15800                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15801
15802       /* The first field was just added, so we can stash the
15803          discriminant there.  */
15804       gdb_assert (!fi->fields.empty ());
15805       if (discr == NULL)
15806         fi->fields.back ().variant.default_branch = true;
15807       else
15808         fi->fields.back ().variant.discriminant_value = DW_UNSND (discr);
15809     }
15810 }
15811
15812 /* Finish creating a structure or union type, including filling in
15813    its members and creating a symbol for it.  */
15814
15815 static void
15816 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
15817 {
15818   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
15819   struct die_info *child_die;
15820   struct type *type;
15821
15822   type = get_die_type (die, cu);
15823   if (type == NULL)
15824     type = read_structure_type (die, cu);
15825
15826   /* When reading a DW_TAG_variant_part, we need to notice when we
15827      read the discriminant member, so we can record it later in the
15828      discriminant_info.  */
15829   bool is_variant_part = TYPE_FLAG_DISCRIMINATED_UNION (type);
15830   sect_offset discr_offset;
15831
15832   if (is_variant_part)
15833     {
15834       struct attribute *discr = dwarf2_attr (die, DW_AT_discr, cu);
15835       if (discr == NULL)
15836         {
15837           /* Maybe it's a univariant form, an extension we support.
15838              In this case arrange not to check the offset.  */
15839           is_variant_part = false;
15840         }
15841       else if (attr_form_is_ref (discr))
15842         {
15843           struct dwarf2_cu *target_cu = cu;
15844           struct die_info *target_die = follow_die_ref (die, discr, &target_cu);
15845
15846           discr_offset = target_die->sect_off;
15847         }
15848       else
15849         {
15850           complaint (_("DW_AT_discr does not have DIE reference form"
15851                        " - DIE at %s [in module %s]"),
15852                      sect_offset_str (die->sect_off),
15853                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
15854           is_variant_part = false;
15855         }
15856     }
15857
15858   if (die->child != NULL && ! die_is_declaration (die, cu))
15859     {
15860       struct field_info fi;
15861       std::vector<struct symbol *> template_args;
15862
15863       child_die = die->child;
15864
15865       while (child_die && child_die->tag)
15866         {
15867           handle_struct_member_die (child_die, type, &fi, &template_args, cu);
15868
15869           if (is_variant_part && discr_offset == child_die->sect_off)
15870             fi.fields.back ().variant.is_discriminant = true;
15871
15872           child_die = sibling_die (child_die);
15873         }
15874
15875       /* Attach template arguments to type.  */
15876       if (!template_args.empty ())
15877         {
15878           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15879           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
15880           TYPE_TEMPLATE_ARGUMENTS (type)
15881             = XOBNEWVEC (&objfile->objfile_obstack,
15882                          struct symbol *,
15883                          TYPE_N_TEMPLATE_ARGUMENTS (type));
15884           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
15885                   template_args.data (),
15886                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
15887                    * sizeof (struct symbol *)));
15888         }
15889
15890       /* Attach fields and member functions to the type.  */
15891       if (fi.nfields)
15892         dwarf2_attach_fields_to_type (&fi, type, cu);
15893       if (!fi.fnfieldlists.empty ())
15894         {
15895           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
15896
15897           /* Get the type which refers to the base class (possibly this
15898              class itself) which contains the vtable pointer for the current
15899              class from the DW_AT_containing_type attribute.  This use of
15900              DW_AT_containing_type is a GNU extension.  */
15901
15902           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
15903             {
15904               struct type *t = die_containing_type (die, cu);
15905
15906               set_type_vptr_basetype (type, t);
15907               if (type == t)
15908                 {
15909                   int i;
15910
15911                   /* Our own class provides vtbl ptr.  */
15912                   for (i = TYPE_NFIELDS (t) - 1;
15913                        i >= TYPE_N_BASECLASSES (t);
15914                        --i)
15915                     {
15916                       const char *fieldname = TYPE_FIELD_NAME (t, i);
15917
15918                       if (is_vtable_name (fieldname, cu))
15919                         {
15920                           set_type_vptr_fieldno (type, i);
15921                           break;
15922                         }
15923                     }
15924
15925                   /* Complain if virtual function table field not found.  */
15926                   if (i < TYPE_N_BASECLASSES (t))
15927                     complaint (_("virtual function table pointer "
15928                                  "not found when defining class '%s'"),
15929                                TYPE_NAME (type) ? TYPE_NAME (type) : "");
15930                 }
15931               else
15932                 {
15933                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
15934                 }
15935             }
15936           else if (cu->producer
15937                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
15938             {
15939               /* The IBM XLC compiler does not provide direct indication
15940                  of the containing type, but the vtable pointer is
15941                  always named __vfp.  */
15942
15943               int i;
15944
15945               for (i = TYPE_NFIELDS (type) - 1;
15946                    i >= TYPE_N_BASECLASSES (type);
15947                    --i)
15948                 {
15949                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
15950                     {
15951                       set_type_vptr_fieldno (type, i);
15952                       set_type_vptr_basetype (type, type);
15953                       break;
15954                     }
15955                 }
15956             }
15957         }
15958
15959       /* Copy fi.typedef_field_list linked list elements content into the
15960          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
15961       if (!fi.typedef_field_list.empty ())
15962         {
15963           int count = fi.typedef_field_list.size ();
15964
15965           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15966           TYPE_TYPEDEF_FIELD_ARRAY (type)
15967             = ((struct decl_field *)
15968                TYPE_ALLOC (type,
15969                            sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * count));
15970           TYPE_TYPEDEF_FIELD_COUNT (type) = count;
15971
15972           for (int i = 0; i < fi.typedef_field_list.size (); ++i)
15973             TYPE_TYPEDEF_FIELD (type, i) = fi.typedef_field_list[i];
15974         }
15975
15976       /* Copy fi.nested_types_list linked list elements content into the
15977          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
15978       if (!fi.nested_types_list.empty () && cu->language != language_ada)
15979         {
15980           int count = fi.nested_types_list.size ();
15981
15982           ALLOCATE_CPLUS_STRUCT_TYPE (type);
15983           TYPE_NESTED_TYPES_ARRAY (type)
15984             = ((struct decl_field *)
15985                TYPE_ALLOC (type, sizeof (struct decl_field) * count));
15986           TYPE_NESTED_TYPES_COUNT (type) = count;
15987
15988           for (int i = 0; i < fi.nested_types_list.size (); ++i)
15989             TYPE_NESTED_TYPES_FIELD (type, i) = fi.nested_types_list[i];
15990         }
15991     }
15992
15993   quirk_gcc_member_function_pointer (type, objfile);
15994   if (cu->language == language_rust && die->tag == DW_TAG_union_type)
15995     cu->rust_unions.push_back (type);
15996
15997   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
15998      snapshots) has been known to create a die giving a declaration
15999      for a class that has, as a child, a die giving a definition for a
16000      nested class.  So we have to process our children even if the
16001      current die is a declaration.  Normally, of course, a declaration
16002      won't have any children at all.  */
16003
16004   child_die = die->child;
16005
16006   while (child_die != NULL && child_die->tag)
16007     {
16008       if (child_die->tag == DW_TAG_member
16009           || child_die->tag == DW_TAG_variable
16010           || child_die->tag == DW_TAG_inheritance
16011           || child_die->tag == DW_TAG_template_value_param
16012           || child_die->tag == DW_TAG_template_type_param)
16013         {
16014           /* Do nothing.  */
16015         }
16016       else
16017         process_die (child_die, cu);
16018
16019       child_die = sibling_die (child_die);
16020     }
16021
16022   /* Do not consider external references.  According to the DWARF standard,
16023      these DIEs are identified by the fact that they have no byte_size
16024      attribute, and a declaration attribute.  */
16025   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
16026       || !die_is_declaration (die, cu))
16027     new_symbol (die, type, cu);
16028 }
16029
16030 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
16031    update TYPE using some information only available in DIE's children.  */
16032
16033 static void
16034 update_enumeration_type_from_children (struct die_info *die,
16035                                        struct type *type,
16036                                        struct dwarf2_cu *cu)
16037 {
16038   struct die_info *child_die;
16039   int unsigned_enum = 1;
16040   int flag_enum = 1;
16041   ULONGEST mask = 0;
16042
16043   auto_obstack obstack;
16044
16045   for (child_die = die->child;
16046        child_die != NULL && child_die->tag;
16047        child_die = sibling_die (child_die))
16048     {
16049       struct attribute *attr;
16050       LONGEST value;
16051       const gdb_byte *bytes;
16052       struct dwarf2_locexpr_baton *baton;
16053       const char *name;
16054
16055       if (child_die->tag != DW_TAG_enumerator)
16056         continue;
16057
16058       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
16059       if (attr == NULL)
16060         continue;
16061
16062       name = dwarf2_name (child_die, cu);
16063       if (name == NULL)
16064         name = "<anonymous enumerator>";
16065
16066       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
16067                                &value, &bytes, &baton);
16068       if (value < 0)
16069         {
16070           unsigned_enum = 0;
16071           flag_enum = 0;
16072         }
16073       else if ((mask & value) != 0)
16074         flag_enum = 0;
16075       else
16076         mask |= value;
16077
16078       /* If we already know that the enum type is neither unsigned, nor
16079          a flag type, no need to look at the rest of the enumerates.  */
16080       if (!unsigned_enum && !flag_enum)
16081         break;
16082     }
16083
16084   if (unsigned_enum)
16085     TYPE_UNSIGNED (type) = 1;
16086   if (flag_enum)
16087     TYPE_FLAG_ENUM (type) = 1;
16088 }
16089
16090 /* Given a DW_AT_enumeration_type die, set its type.  We do not
16091    complete the type's fields yet, or create any symbols.  */
16092
16093 static struct type *
16094 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
16095 {
16096   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16097   struct type *type;
16098   struct attribute *attr;
16099   const char *name;
16100
16101   /* If the definition of this type lives in .debug_types, read that type.
16102      Don't follow DW_AT_specification though, that will take us back up
16103      the chain and we want to go down.  */
16104   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
16105   if (attr)
16106     {
16107       type = get_DW_AT_signature_type (die, attr, cu);
16108
16109       /* The type's CU may not be the same as CU.
16110          Ensure TYPE is recorded with CU in die_type_hash.  */
16111       return set_die_type (die, type, cu);
16112     }
16113
16114   type = alloc_type (objfile);
16115
16116   TYPE_CODE (type) = TYPE_CODE_ENUM;
16117   name = dwarf2_full_name (NULL, die, cu);
16118   if (name != NULL)
16119     TYPE_NAME (type) = name;
16120
16121   attr = dwarf2_attr (die, DW_AT_type, cu);
16122   if (attr != NULL)
16123     {
16124       struct type *underlying_type = die_type (die, cu);
16125
16126       TYPE_TARGET_TYPE (type) = underlying_type;
16127     }
16128
16129   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16130   if (attr)
16131     {
16132       TYPE_LENGTH (type) = DW_UNSND (attr);
16133     }
16134   else
16135     {
16136       TYPE_LENGTH (type) = 0;
16137     }
16138
16139   maybe_set_alignment (cu, die, type);
16140
16141   /* The enumeration DIE can be incomplete.  In Ada, any type can be
16142      declared as private in the package spec, and then defined only
16143      inside the package body.  Such types are known as Taft Amendment
16144      Types.  When another package uses such a type, an incomplete DIE
16145      may be generated by the compiler.  */
16146   if (die_is_declaration (die, cu))
16147     TYPE_STUB (type) = 1;
16148
16149   /* Finish the creation of this type by using the enum's children.
16150      We must call this even when the underlying type has been provided
16151      so that we can determine if we're looking at a "flag" enum.  */
16152   update_enumeration_type_from_children (die, type, cu);
16153
16154   /* If this type has an underlying type that is not a stub, then we
16155      may use its attributes.  We always use the "unsigned" attribute
16156      in this situation, because ordinarily we guess whether the type
16157      is unsigned -- but the guess can be wrong and the underlying type
16158      can tell us the reality.  However, we defer to a local size
16159      attribute if one exists, because this lets the compiler override
16160      the underlying type if needed.  */
16161   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
16162     {
16163       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
16164       if (TYPE_LENGTH (type) == 0)
16165         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
16166       if (TYPE_RAW_ALIGN (type) == 0
16167           && TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)) != 0)
16168         set_type_align (type, TYPE_RAW_ALIGN (TYPE_TARGET_TYPE (type)));
16169     }
16170
16171   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
16172
16173   return set_die_type (die, type, cu);
16174 }
16175
16176 /* Given a pointer to a die which begins an enumeration, process all
16177    the dies that define the members of the enumeration, and create the
16178    symbol for the enumeration type.
16179
16180    NOTE: We reverse the order of the element list.  */
16181
16182 static void
16183 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
16184 {
16185   struct type *this_type;
16186
16187   this_type = get_die_type (die, cu);
16188   if (this_type == NULL)
16189     this_type = read_enumeration_type (die, cu);
16190
16191   if (die->child != NULL)
16192     {
16193       struct die_info *child_die;
16194       struct symbol *sym;
16195       struct field *fields = NULL;
16196       int num_fields = 0;
16197       const char *name;
16198
16199       child_die = die->child;
16200       while (child_die && child_die->tag)
16201         {
16202           if (child_die->tag != DW_TAG_enumerator)
16203             {
16204               process_die (child_die, cu);
16205             }
16206           else
16207             {
16208               name = dwarf2_name (child_die, cu);
16209               if (name)
16210                 {
16211                   sym = new_symbol (child_die, this_type, cu);
16212
16213                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
16214                     {
16215                       fields = (struct field *)
16216                         xrealloc (fields,
16217                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
16218                                   * sizeof (struct field));
16219                     }
16220
16221                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
16222                   FIELD_TYPE (fields[num_fields]) = NULL;
16223                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
16224                   FIELD_BITSIZE (fields[num_fields]) = 0;
16225
16226                   num_fields++;
16227                 }
16228             }
16229
16230           child_die = sibling_die (child_die);
16231         }
16232
16233       if (num_fields)
16234         {
16235           TYPE_NFIELDS (this_type) = num_fields;
16236           TYPE_FIELDS (this_type) = (struct field *)
16237             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
16238           memcpy (TYPE_FIELDS (this_type), fields,
16239                   sizeof (struct field) * num_fields);
16240           xfree (fields);
16241         }
16242     }
16243
16244   /* If we are reading an enum from a .debug_types unit, and the enum
16245      is a declaration, and the enum is not the signatured type in the
16246      unit, then we do not want to add a symbol for it.  Adding a
16247      symbol would in some cases obscure the true definition of the
16248      enum, giving users an incomplete type when the definition is
16249      actually available.  Note that we do not want to do this for all
16250      enums which are just declarations, because C++0x allows forward
16251      enum declarations.  */
16252   if (cu->per_cu->is_debug_types
16253       && die_is_declaration (die, cu))
16254     {
16255       struct signatured_type *sig_type;
16256
16257       sig_type = (struct signatured_type *) cu->per_cu;
16258       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
16259       if (sig_type->type_offset_in_section != die->sect_off)
16260         return;
16261     }
16262
16263   new_symbol (die, this_type, cu);
16264 }
16265
16266 /* Extract all information from a DW_TAG_array_type DIE and put it in
16267    the DIE's type field.  For now, this only handles one dimensional
16268    arrays.  */
16269
16270 static struct type *
16271 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
16272 {
16273   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16274   struct die_info *child_die;
16275   struct type *type;
16276   struct type *element_type, *range_type, *index_type;
16277   struct attribute *attr;
16278   const char *name;
16279   struct dynamic_prop *byte_stride_prop = NULL;
16280   unsigned int bit_stride = 0;
16281
16282   element_type = die_type (die, cu);
16283
16284   /* The die_type call above may have already set the type for this DIE.  */
16285   type = get_die_type (die, cu);
16286   if (type)
16287     return type;
16288
16289   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
16290   if (attr != NULL)
16291     {
16292       int stride_ok;
16293
16294       byte_stride_prop
16295         = (struct dynamic_prop *) alloca (sizeof (struct dynamic_prop));
16296       stride_ok = attr_to_dynamic_prop (attr, die, cu, byte_stride_prop);
16297       if (!stride_ok)
16298         {
16299           complaint (_("unable to read array DW_AT_byte_stride "
16300                        " - DIE at %s [in module %s]"),
16301                      sect_offset_str (die->sect_off),
16302                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16303           /* Ignore this attribute.  We will likely not be able to print
16304              arrays of this type correctly, but there is little we can do
16305              to help if we cannot read the attribute's value.  */
16306           byte_stride_prop = NULL;
16307         }
16308     }
16309
16310   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
16311   if (attr != NULL)
16312     bit_stride = DW_UNSND (attr);
16313
16314   /* Irix 6.2 native cc creates array types without children for
16315      arrays with unspecified length.  */
16316   if (die->child == NULL)
16317     {
16318       index_type = objfile_type (objfile)->builtin_int;
16319       range_type = create_static_range_type (NULL, index_type, 0, -1);
16320       type = create_array_type_with_stride (NULL, element_type, range_type,
16321                                             byte_stride_prop, bit_stride);
16322       return set_die_type (die, type, cu);
16323     }
16324
16325   std::vector<struct type *> range_types;
16326   child_die = die->child;
16327   while (child_die && child_die->tag)
16328     {
16329       if (child_die->tag == DW_TAG_subrange_type)
16330         {
16331           struct type *child_type = read_type_die (child_die, cu);
16332
16333           if (child_type != NULL)
16334             {
16335               /* The range type was succesfully read.  Save it for the
16336                  array type creation.  */
16337               range_types.push_back (child_type);
16338             }
16339         }
16340       child_die = sibling_die (child_die);
16341     }
16342
16343   /* Dwarf2 dimensions are output from left to right, create the
16344      necessary array types in backwards order.  */
16345
16346   type = element_type;
16347
16348   if (read_array_order (die, cu) == DW_ORD_col_major)
16349     {
16350       int i = 0;
16351
16352       while (i < range_types.size ())
16353         type = create_array_type_with_stride (NULL, type, range_types[i++],
16354                                               byte_stride_prop, bit_stride);
16355     }
16356   else
16357     {
16358       size_t ndim = range_types.size ();
16359       while (ndim-- > 0)
16360         type = create_array_type_with_stride (NULL, type, range_types[ndim],
16361                                               byte_stride_prop, bit_stride);
16362     }
16363
16364   /* Understand Dwarf2 support for vector types (like they occur on
16365      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
16366      array type.  This is not part of the Dwarf2/3 standard yet, but a
16367      custom vendor extension.  The main difference between a regular
16368      array and the vector variant is that vectors are passed by value
16369      to functions.  */
16370   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
16371   if (attr)
16372     make_vector_type (type);
16373
16374   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
16375      implementation may choose to implement triple vectors using this
16376      attribute.  */
16377   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16378   if (attr)
16379     {
16380       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
16381         TYPE_LENGTH (type) = DW_UNSND (attr);
16382       else
16383         complaint (_("DW_AT_byte_size for array type smaller "
16384                      "than the total size of elements"));
16385     }
16386
16387   name = dwarf2_name (die, cu);
16388   if (name)
16389     TYPE_NAME (type) = name;
16390
16391   maybe_set_alignment (cu, die, type);
16392
16393   /* Install the type in the die.  */
16394   set_die_type (die, type, cu);
16395
16396   /* set_die_type should be already done.  */
16397   set_descriptive_type (type, die, cu);
16398
16399   return type;
16400 }
16401
16402 static enum dwarf_array_dim_ordering
16403 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
16404 {
16405   struct attribute *attr;
16406
16407   attr = dwarf2_attr (die, DW_AT_ordering, cu);
16408
16409   if (attr)
16410     return (enum dwarf_array_dim_ordering) DW_SND (attr);
16411
16412   /* GNU F77 is a special case, as at 08/2004 array type info is the
16413      opposite order to the dwarf2 specification, but data is still
16414      laid out as per normal fortran.
16415
16416      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
16417      version checking.  */
16418
16419   if (cu->language == language_fortran
16420       && cu->producer && strstr (cu->producer, "GNU F77"))
16421     {
16422       return DW_ORD_row_major;
16423     }
16424
16425   switch (cu->language_defn->la_array_ordering)
16426     {
16427     case array_column_major:
16428       return DW_ORD_col_major;
16429     case array_row_major:
16430     default:
16431       return DW_ORD_row_major;
16432     };
16433 }
16434
16435 /* Extract all information from a DW_TAG_set_type DIE and put it in
16436    the DIE's type field.  */
16437
16438 static struct type *
16439 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
16440 {
16441   struct type *domain_type, *set_type;
16442   struct attribute *attr;
16443
16444   domain_type = die_type (die, cu);
16445
16446   /* The die_type call above may have already set the type for this DIE.  */
16447   set_type = get_die_type (die, cu);
16448   if (set_type)
16449     return set_type;
16450
16451   set_type = create_set_type (NULL, domain_type);
16452
16453   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16454   if (attr)
16455     TYPE_LENGTH (set_type) = DW_UNSND (attr);
16456
16457   maybe_set_alignment (cu, die, set_type);
16458
16459   return set_die_type (die, set_type, cu);
16460 }
16461
16462 /* A helper for read_common_block that creates a locexpr baton.
16463    SYM is the symbol which we are marking as computed.
16464    COMMON_DIE is the DIE for the common block.
16465    COMMON_LOC is the location expression attribute for the common
16466    block itself.
16467    MEMBER_LOC is the location expression attribute for the particular
16468    member of the common block that we are processing.
16469    CU is the CU from which the above come.  */
16470
16471 static void
16472 mark_common_block_symbol_computed (struct symbol *sym,
16473                                    struct die_info *common_die,
16474                                    struct attribute *common_loc,
16475                                    struct attribute *member_loc,
16476                                    struct dwarf2_cu *cu)
16477 {
16478   struct dwarf2_per_objfile *dwarf2_per_objfile
16479     = cu->per_cu->dwarf2_per_objfile;
16480   struct objfile *objfile = dwarf2_per_objfile->objfile;
16481   struct dwarf2_locexpr_baton *baton;
16482   gdb_byte *ptr;
16483   unsigned int cu_off;
16484   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
16485   LONGEST offset = 0;
16486
16487   gdb_assert (common_loc && member_loc);
16488   gdb_assert (attr_form_is_block (common_loc));
16489   gdb_assert (attr_form_is_block (member_loc)
16490               || attr_form_is_constant (member_loc));
16491
16492   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
16493   baton->per_cu = cu->per_cu;
16494   gdb_assert (baton->per_cu);
16495
16496   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
16497
16498   if (attr_form_is_constant (member_loc))
16499     {
16500       offset = dwarf2_get_attr_constant_value (member_loc, 0);
16501       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
16502     }
16503   else
16504     baton->size += DW_BLOCK (member_loc)->size;
16505
16506   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
16507   baton->data = ptr;
16508
16509   *ptr++ = DW_OP_call4;
16510   cu_off = common_die->sect_off - cu->per_cu->sect_off;
16511   store_unsigned_integer (ptr, 4, byte_order, cu_off);
16512   ptr += 4;
16513
16514   if (attr_form_is_constant (member_loc))
16515     {
16516       *ptr++ = DW_OP_addr;
16517       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
16518       ptr += cu->header.addr_size;
16519     }
16520   else
16521     {
16522       /* We have to copy the data here, because DW_OP_call4 will only
16523          use a DW_AT_location attribute.  */
16524       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
16525       ptr += DW_BLOCK (member_loc)->size;
16526     }
16527
16528   *ptr++ = DW_OP_plus;
16529   gdb_assert (ptr - baton->data == baton->size);
16530
16531   SYMBOL_LOCATION_BATON (sym) = baton;
16532   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
16533 }
16534
16535 /* Create appropriate locally-scoped variables for all the
16536    DW_TAG_common_block entries.  Also create a struct common_block
16537    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
16538    is used to sepate the common blocks name namespace from regular
16539    variable names.  */
16540
16541 static void
16542 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
16543 {
16544   struct attribute *attr;
16545
16546   attr = dwarf2_attr (die, DW_AT_location, cu);
16547   if (attr)
16548     {
16549       /* Support the .debug_loc offsets.  */
16550       if (attr_form_is_block (attr))
16551         {
16552           /* Ok.  */
16553         }
16554       else if (attr_form_is_section_offset (attr))
16555         {
16556           dwarf2_complex_location_expr_complaint ();
16557           attr = NULL;
16558         }
16559       else
16560         {
16561           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16562                                                  "common block member");
16563           attr = NULL;
16564         }
16565     }
16566
16567   if (die->child != NULL)
16568     {
16569       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16570       struct die_info *child_die;
16571       size_t n_entries = 0, size;
16572       struct common_block *common_block;
16573       struct symbol *sym;
16574
16575       for (child_die = die->child;
16576            child_die && child_die->tag;
16577            child_die = sibling_die (child_die))
16578         ++n_entries;
16579
16580       size = (sizeof (struct common_block)
16581               + (n_entries - 1) * sizeof (struct symbol *));
16582       common_block
16583         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
16584                                                  size);
16585       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
16586       common_block->n_entries = 0;
16587
16588       for (child_die = die->child;
16589            child_die && child_die->tag;
16590            child_die = sibling_die (child_die))
16591         {
16592           /* Create the symbol in the DW_TAG_common_block block in the current
16593              symbol scope.  */
16594           sym = new_symbol (child_die, NULL, cu);
16595           if (sym != NULL)
16596             {
16597               struct attribute *member_loc;
16598
16599               common_block->contents[common_block->n_entries++] = sym;
16600
16601               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
16602                                         cu);
16603               if (member_loc)
16604                 {
16605                   /* GDB has handled this for a long time, but it is
16606                      not specified by DWARF.  It seems to have been
16607                      emitted by gfortran at least as recently as:
16608                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
16609                   complaint (_("Variable in common block has "
16610                                "DW_AT_data_member_location "
16611                                "- DIE at %s [in module %s]"),
16612                                sect_offset_str (child_die->sect_off),
16613                              objfile_name (objfile));
16614
16615                   if (attr_form_is_section_offset (member_loc))
16616                     dwarf2_complex_location_expr_complaint ();
16617                   else if (attr_form_is_constant (member_loc)
16618                            || attr_form_is_block (member_loc))
16619                     {
16620                       if (attr)
16621                         mark_common_block_symbol_computed (sym, die, attr,
16622                                                            member_loc, cu);
16623                     }
16624                   else
16625                     dwarf2_complex_location_expr_complaint ();
16626                 }
16627             }
16628         }
16629
16630       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
16631       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
16632     }
16633 }
16634
16635 /* Create a type for a C++ namespace.  */
16636
16637 static struct type *
16638 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
16639 {
16640   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16641   const char *previous_prefix, *name;
16642   int is_anonymous;
16643   struct type *type;
16644
16645   /* For extensions, reuse the type of the original namespace.  */
16646   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
16647     {
16648       struct die_info *ext_die;
16649       struct dwarf2_cu *ext_cu = cu;
16650
16651       ext_die = dwarf2_extension (die, &ext_cu);
16652       type = read_type_die (ext_die, ext_cu);
16653
16654       /* EXT_CU may not be the same as CU.
16655          Ensure TYPE is recorded with CU in die_type_hash.  */
16656       return set_die_type (die, type, cu);
16657     }
16658
16659   name = namespace_name (die, &is_anonymous, cu);
16660
16661   /* Now build the name of the current namespace.  */
16662
16663   previous_prefix = determine_prefix (die, cu);
16664   if (previous_prefix[0] != '\0')
16665     name = typename_concat (&objfile->objfile_obstack,
16666                             previous_prefix, name, 0, cu);
16667
16668   /* Create the type.  */
16669   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
16670
16671   return set_die_type (die, type, cu);
16672 }
16673
16674 /* Read a namespace scope.  */
16675
16676 static void
16677 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
16678 {
16679   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16680   int is_anonymous;
16681
16682   /* Add a symbol associated to this if we haven't seen the namespace
16683      before.  Also, add a using directive if it's an anonymous
16684      namespace.  */
16685
16686   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
16687     {
16688       struct type *type;
16689
16690       type = read_type_die (die, cu);
16691       new_symbol (die, type, cu);
16692
16693       namespace_name (die, &is_anonymous, cu);
16694       if (is_anonymous)
16695         {
16696           const char *previous_prefix = determine_prefix (die, cu);
16697
16698           std::vector<const char *> excludes;
16699           add_using_directive (using_directives (cu->language),
16700                                previous_prefix, TYPE_NAME (type), NULL,
16701                                NULL, excludes, 0, &objfile->objfile_obstack);
16702         }
16703     }
16704
16705   if (die->child != NULL)
16706     {
16707       struct die_info *child_die = die->child;
16708
16709       while (child_die && child_die->tag)
16710         {
16711           process_die (child_die, cu);
16712           child_die = sibling_die (child_die);
16713         }
16714     }
16715 }
16716
16717 /* Read a Fortran module as type.  This DIE can be only a declaration used for
16718    imported module.  Still we need that type as local Fortran "use ... only"
16719    declaration imports depend on the created type in determine_prefix.  */
16720
16721 static struct type *
16722 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
16723 {
16724   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
16725   const char *module_name;
16726   struct type *type;
16727
16728   module_name = dwarf2_name (die, cu);
16729   if (!module_name)
16730     complaint (_("DW_TAG_module has no name, offset %s"),
16731                sect_offset_str (die->sect_off));
16732   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
16733
16734   return set_die_type (die, type, cu);
16735 }
16736
16737 /* Read a Fortran module.  */
16738
16739 static void
16740 read_module (struct die_info *die, struct dwarf2_cu *cu)
16741 {
16742   struct die_info *child_die = die->child;
16743   struct type *type;
16744
16745   type = read_type_die (die, cu);
16746   new_symbol (die, type, cu);
16747
16748   while (child_die && child_die->tag)
16749     {
16750       process_die (child_die, cu);
16751       child_die = sibling_die (child_die);
16752     }
16753 }
16754
16755 /* Return the name of the namespace represented by DIE.  Set
16756    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
16757    namespace.  */
16758
16759 static const char *
16760 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
16761 {
16762   struct die_info *current_die;
16763   const char *name = NULL;
16764
16765   /* Loop through the extensions until we find a name.  */
16766
16767   for (current_die = die;
16768        current_die != NULL;
16769        current_die = dwarf2_extension (die, &cu))
16770     {
16771       /* We don't use dwarf2_name here so that we can detect the absence
16772          of a name -> anonymous namespace.  */
16773       name = dwarf2_string_attr (die, DW_AT_name, cu);
16774
16775       if (name != NULL)
16776         break;
16777     }
16778
16779   /* Is it an anonymous namespace?  */
16780
16781   *is_anonymous = (name == NULL);
16782   if (*is_anonymous)
16783     name = CP_ANONYMOUS_NAMESPACE_STR;
16784
16785   return name;
16786 }
16787
16788 /* Extract all information from a DW_TAG_pointer_type DIE and add to
16789    the user defined type vector.  */
16790
16791 static struct type *
16792 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
16793 {
16794   struct gdbarch *gdbarch
16795     = get_objfile_arch (cu->per_cu->dwarf2_per_objfile->objfile);
16796   struct comp_unit_head *cu_header = &cu->header;
16797   struct type *type;
16798   struct attribute *attr_byte_size;
16799   struct attribute *attr_address_class;
16800   int byte_size, addr_class;
16801   struct type *target_type;
16802
16803   target_type = die_type (die, cu);
16804
16805   /* The die_type call above may have already set the type for this DIE.  */
16806   type = get_die_type (die, cu);
16807   if (type)
16808     return type;
16809
16810   type = lookup_pointer_type (target_type);
16811
16812   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
16813   if (attr_byte_size)
16814     byte_size = DW_UNSND (attr_byte_size);
16815   else
16816     byte_size = cu_header->addr_size;
16817
16818   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
16819   if (attr_address_class)
16820     addr_class = DW_UNSND (attr_address_class);
16821   else
16822     addr_class = DW_ADDR_none;
16823
16824   ULONGEST alignment = get_alignment (cu, die);
16825
16826   /* If the pointer size, alignment, or address class is different
16827      than the default, create a type variant marked as such and set
16828      the length accordingly.  */
16829   if (TYPE_LENGTH (type) != byte_size
16830       || (alignment != 0 && TYPE_RAW_ALIGN (type) != 0
16831           && alignment != TYPE_RAW_ALIGN (type))
16832       || addr_class != DW_ADDR_none)
16833     {
16834       if (gdbarch_address_class_type_flags_p (gdbarch))
16835         {
16836           int type_flags;
16837
16838           type_flags = gdbarch_address_class_type_flags
16839                          (gdbarch, byte_size, addr_class);
16840           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
16841                       == 0);
16842           type = make_type_with_address_space (type, type_flags);
16843         }
16844       else if (TYPE_LENGTH (type) != byte_size)
16845         {
16846           complaint (_("invalid pointer size %d"), byte_size);
16847         }
16848       else if (TYPE_RAW_ALIGN (type) != alignment)
16849         {
16850           complaint (_("Invalid DW_AT_alignment"
16851                        " - DIE at %s [in module %s]"),
16852                      sect_offset_str (die->sect_off),
16853                      objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
16854         }
16855       else
16856         {
16857           /* Should we also complain about unhandled address classes?  */
16858         }
16859     }
16860
16861   TYPE_LENGTH (type) = byte_size;
16862   set_type_align (type, alignment);
16863   return set_die_type (die, type, cu);
16864 }
16865
16866 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
16867    the user defined type vector.  */
16868
16869 static struct type *
16870 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
16871 {
16872   struct type *type;
16873   struct type *to_type;
16874   struct type *domain;
16875
16876   to_type = die_type (die, cu);
16877   domain = die_containing_type (die, cu);
16878
16879   /* The calls above may have already set the type for this DIE.  */
16880   type = get_die_type (die, cu);
16881   if (type)
16882     return type;
16883
16884   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
16885     type = lookup_methodptr_type (to_type);
16886   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
16887     {
16888       struct type *new_type
16889         = alloc_type (cu->per_cu->dwarf2_per_objfile->objfile);
16890
16891       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
16892                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
16893                             TYPE_VARARGS (to_type));
16894       type = lookup_methodptr_type (new_type);
16895     }
16896   else
16897     type = lookup_memberptr_type (to_type, domain);
16898
16899   return set_die_type (die, type, cu);
16900 }
16901
16902 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
16903    the user defined type vector.  */
16904
16905 static struct type *
16906 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
16907                           enum type_code refcode)
16908 {
16909   struct comp_unit_head *cu_header = &cu->header;
16910   struct type *type, *target_type;
16911   struct attribute *attr;
16912
16913   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
16914
16915   target_type = die_type (die, cu);
16916
16917   /* The die_type call above may have already set the type for this DIE.  */
16918   type = get_die_type (die, cu);
16919   if (type)
16920     return type;
16921
16922   type = lookup_reference_type (target_type, refcode);
16923   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16924   if (attr)
16925     {
16926       TYPE_LENGTH (type) = DW_UNSND (attr);
16927     }
16928   else
16929     {
16930       TYPE_LENGTH (type) = cu_header->addr_size;
16931     }
16932   maybe_set_alignment (cu, die, type);
16933   return set_die_type (die, type, cu);
16934 }
16935
16936 /* Add the given cv-qualifiers to the element type of the array.  GCC
16937    outputs DWARF type qualifiers that apply to an array, not the
16938    element type.  But GDB relies on the array element type to carry
16939    the cv-qualifiers.  This mimics section 6.7.3 of the C99
16940    specification.  */
16941
16942 static struct type *
16943 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
16944                    struct type *base_type, int cnst, int voltl)
16945 {
16946   struct type *el_type, *inner_array;
16947
16948   base_type = copy_type (base_type);
16949   inner_array = base_type;
16950
16951   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
16952     {
16953       TYPE_TARGET_TYPE (inner_array) =
16954         copy_type (TYPE_TARGET_TYPE (inner_array));
16955       inner_array = TYPE_TARGET_TYPE (inner_array);
16956     }
16957
16958   el_type = TYPE_TARGET_TYPE (inner_array);
16959   cnst |= TYPE_CONST (el_type);
16960   voltl |= TYPE_VOLATILE (el_type);
16961   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
16962
16963   return set_die_type (die, base_type, cu);
16964 }
16965
16966 static struct type *
16967 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
16968 {
16969   struct type *base_type, *cv_type;
16970
16971   base_type = die_type (die, cu);
16972
16973   /* The die_type call above may have already set the type for this DIE.  */
16974   cv_type = get_die_type (die, cu);
16975   if (cv_type)
16976     return cv_type;
16977
16978   /* In case the const qualifier is applied to an array type, the element type
16979      is so qualified, not the array type (section 6.7.3 of C99).  */
16980   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
16981     return add_array_cv_type (die, cu, base_type, 1, 0);
16982
16983   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
16984   return set_die_type (die, cv_type, cu);
16985 }
16986
16987 static struct type *
16988 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
16989 {
16990   struct type *base_type, *cv_type;
16991
16992   base_type = die_type (die, cu);
16993
16994   /* The die_type call above may have already set the type for this DIE.  */
16995   cv_type = get_die_type (die, cu);
16996   if (cv_type)
16997     return cv_type;
16998
16999   /* In case the volatile qualifier is applied to an array type, the
17000      element type is so qualified, not the array type (section 6.7.3
17001      of C99).  */
17002   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
17003     return add_array_cv_type (die, cu, base_type, 0, 1);
17004
17005   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
17006   return set_die_type (die, cv_type, cu);
17007 }
17008
17009 /* Handle DW_TAG_restrict_type.  */
17010
17011 static struct type *
17012 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
17013 {
17014   struct type *base_type, *cv_type;
17015
17016   base_type = die_type (die, cu);
17017
17018   /* The die_type call above may have already set the type for this DIE.  */
17019   cv_type = get_die_type (die, cu);
17020   if (cv_type)
17021     return cv_type;
17022
17023   cv_type = make_restrict_type (base_type);
17024   return set_die_type (die, cv_type, cu);
17025 }
17026
17027 /* Handle DW_TAG_atomic_type.  */
17028
17029 static struct type *
17030 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
17031 {
17032   struct type *base_type, *cv_type;
17033
17034   base_type = die_type (die, cu);
17035
17036   /* The die_type call above may have already set the type for this DIE.  */
17037   cv_type = get_die_type (die, cu);
17038   if (cv_type)
17039     return cv_type;
17040
17041   cv_type = make_atomic_type (base_type);
17042   return set_die_type (die, cv_type, cu);
17043 }
17044
17045 /* Extract all information from a DW_TAG_string_type DIE and add to
17046    the user defined type vector.  It isn't really a user defined type,
17047    but it behaves like one, with other DIE's using an AT_user_def_type
17048    attribute to reference it.  */
17049
17050 static struct type *
17051 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
17052 {
17053   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17054   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17055   struct type *type, *range_type, *index_type, *char_type;
17056   struct attribute *attr;
17057   unsigned int length;
17058
17059   attr = dwarf2_attr (die, DW_AT_string_length, cu);
17060   if (attr)
17061     {
17062       length = DW_UNSND (attr);
17063     }
17064   else
17065     {
17066       /* Check for the DW_AT_byte_size attribute.  */
17067       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17068       if (attr)
17069         {
17070           length = DW_UNSND (attr);
17071         }
17072       else
17073         {
17074           length = 1;
17075         }
17076     }
17077
17078   index_type = objfile_type (objfile)->builtin_int;
17079   range_type = create_static_range_type (NULL, index_type, 1, length);
17080   char_type = language_string_char_type (cu->language_defn, gdbarch);
17081   type = create_string_type (NULL, char_type, range_type);
17082
17083   return set_die_type (die, type, cu);
17084 }
17085
17086 /* Assuming that DIE corresponds to a function, returns nonzero
17087    if the function is prototyped.  */
17088
17089 static int
17090 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
17091 {
17092   struct attribute *attr;
17093
17094   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
17095   if (attr && (DW_UNSND (attr) != 0))
17096     return 1;
17097
17098   /* The DWARF standard implies that the DW_AT_prototyped attribute
17099      is only meaninful for C, but the concept also extends to other
17100      languages that allow unprototyped functions (Eg: Objective C).
17101      For all other languages, assume that functions are always
17102      prototyped.  */
17103   if (cu->language != language_c
17104       && cu->language != language_objc
17105       && cu->language != language_opencl)
17106     return 1;
17107
17108   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
17109      prototyped and unprototyped functions; default to prototyped,
17110      since that is more common in modern code (and RealView warns
17111      about unprototyped functions).  */
17112   if (producer_is_realview (cu->producer))
17113     return 1;
17114
17115   return 0;
17116 }
17117
17118 /* Handle DIES due to C code like:
17119
17120    struct foo
17121    {
17122    int (*funcp)(int a, long l);
17123    int b;
17124    };
17125
17126    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
17127
17128 static struct type *
17129 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
17130 {
17131   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17132   struct type *type;            /* Type that this function returns.  */
17133   struct type *ftype;           /* Function that returns above type.  */
17134   struct attribute *attr;
17135
17136   type = die_type (die, cu);
17137
17138   /* The die_type call above may have already set the type for this DIE.  */
17139   ftype = get_die_type (die, cu);
17140   if (ftype)
17141     return ftype;
17142
17143   ftype = lookup_function_type (type);
17144
17145   if (prototyped_function_p (die, cu))
17146     TYPE_PROTOTYPED (ftype) = 1;
17147
17148   /* Store the calling convention in the type if it's available in
17149      the subroutine die.  Otherwise set the calling convention to
17150      the default value DW_CC_normal.  */
17151   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
17152   if (attr)
17153     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
17154   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
17155     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
17156   else
17157     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
17158
17159   /* Record whether the function returns normally to its caller or not
17160      if the DWARF producer set that information.  */
17161   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
17162   if (attr && (DW_UNSND (attr) != 0))
17163     TYPE_NO_RETURN (ftype) = 1;
17164
17165   /* We need to add the subroutine type to the die immediately so
17166      we don't infinitely recurse when dealing with parameters
17167      declared as the same subroutine type.  */
17168   set_die_type (die, ftype, cu);
17169
17170   if (die->child != NULL)
17171     {
17172       struct type *void_type = objfile_type (objfile)->builtin_void;
17173       struct die_info *child_die;
17174       int nparams, iparams;
17175
17176       /* Count the number of parameters.
17177          FIXME: GDB currently ignores vararg functions, but knows about
17178          vararg member functions.  */
17179       nparams = 0;
17180       child_die = die->child;
17181       while (child_die && child_die->tag)
17182         {
17183           if (child_die->tag == DW_TAG_formal_parameter)
17184             nparams++;
17185           else if (child_die->tag == DW_TAG_unspecified_parameters)
17186             TYPE_VARARGS (ftype) = 1;
17187           child_die = sibling_die (child_die);
17188         }
17189
17190       /* Allocate storage for parameters and fill them in.  */
17191       TYPE_NFIELDS (ftype) = nparams;
17192       TYPE_FIELDS (ftype) = (struct field *)
17193         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
17194
17195       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
17196          even if we error out during the parameters reading below.  */
17197       for (iparams = 0; iparams < nparams; iparams++)
17198         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
17199
17200       iparams = 0;
17201       child_die = die->child;
17202       while (child_die && child_die->tag)
17203         {
17204           if (child_die->tag == DW_TAG_formal_parameter)
17205             {
17206               struct type *arg_type;
17207
17208               /* DWARF version 2 has no clean way to discern C++
17209                  static and non-static member functions.  G++ helps
17210                  GDB by marking the first parameter for non-static
17211                  member functions (which is the this pointer) as
17212                  artificial.  We pass this information to
17213                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
17214
17215                  DWARF version 3 added DW_AT_object_pointer, which GCC
17216                  4.5 does not yet generate.  */
17217               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
17218               if (attr)
17219                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
17220               else
17221                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
17222               arg_type = die_type (child_die, cu);
17223
17224               /* RealView does not mark THIS as const, which the testsuite
17225                  expects.  GCC marks THIS as const in method definitions,
17226                  but not in the class specifications (GCC PR 43053).  */
17227               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
17228                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
17229                 {
17230                   int is_this = 0;
17231                   struct dwarf2_cu *arg_cu = cu;
17232                   const char *name = dwarf2_name (child_die, cu);
17233
17234                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
17235                   if (attr)
17236                     {
17237                       /* If the compiler emits this, use it.  */
17238                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
17239                         is_this = 1;
17240                     }
17241                   else if (name && strcmp (name, "this") == 0)
17242                     /* Function definitions will have the argument names.  */
17243                     is_this = 1;
17244                   else if (name == NULL && iparams == 0)
17245                     /* Declarations may not have the names, so like
17246                        elsewhere in GDB, assume an artificial first
17247                        argument is "this".  */
17248                     is_this = 1;
17249
17250                   if (is_this)
17251                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
17252                                              arg_type, 0);
17253                 }
17254
17255               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
17256               iparams++;
17257             }
17258           child_die = sibling_die (child_die);
17259         }
17260     }
17261
17262   return ftype;
17263 }
17264
17265 static struct type *
17266 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
17267 {
17268   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17269   const char *name = NULL;
17270   struct type *this_type, *target_type;
17271
17272   name = dwarf2_full_name (NULL, die, cu);
17273   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
17274   TYPE_TARGET_STUB (this_type) = 1;
17275   set_die_type (die, this_type, cu);
17276   target_type = die_type (die, cu);
17277   if (target_type != this_type)
17278     TYPE_TARGET_TYPE (this_type) = target_type;
17279   else
17280     {
17281       /* Self-referential typedefs are, it seems, not allowed by the DWARF
17282          spec and cause infinite loops in GDB.  */
17283       complaint (_("Self-referential DW_TAG_typedef "
17284                    "- DIE at %s [in module %s]"),
17285                  sect_offset_str (die->sect_off), objfile_name (objfile));
17286       TYPE_TARGET_TYPE (this_type) = NULL;
17287     }
17288   return this_type;
17289 }
17290
17291 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
17292    (which may be different from NAME) to the architecture back-end to allow
17293    it to guess the correct format if necessary.  */
17294
17295 static struct type *
17296 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
17297                         const char *name_hint)
17298 {
17299   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17300   const struct floatformat **format;
17301   struct type *type;
17302
17303   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
17304   if (format)
17305     type = init_float_type (objfile, bits, name, format);
17306   else
17307     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17308
17309   return type;
17310 }
17311
17312 /* Find a representation of a given base type and install
17313    it in the TYPE field of the die.  */
17314
17315 static struct type *
17316 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
17317 {
17318   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17319   struct type *type;
17320   struct attribute *attr;
17321   int encoding = 0, bits = 0;
17322   const char *name;
17323
17324   attr = dwarf2_attr (die, DW_AT_encoding, cu);
17325   if (attr)
17326     {
17327       encoding = DW_UNSND (attr);
17328     }
17329   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17330   if (attr)
17331     {
17332       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
17333     }
17334   name = dwarf2_name (die, cu);
17335   if (!name)
17336     {
17337       complaint (_("DW_AT_name missing from DW_TAG_base_type"));
17338     }
17339
17340   switch (encoding)
17341     {
17342       case DW_ATE_address:
17343         /* Turn DW_ATE_address into a void * pointer.  */
17344         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
17345         type = init_pointer_type (objfile, bits, name, type);
17346         break;
17347       case DW_ATE_boolean:
17348         type = init_boolean_type (objfile, bits, 1, name);
17349         break;
17350       case DW_ATE_complex_float:
17351         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
17352         type = init_complex_type (objfile, name, type);
17353         break;
17354       case DW_ATE_decimal_float:
17355         type = init_decfloat_type (objfile, bits, name);
17356         break;
17357       case DW_ATE_float:
17358         type = dwarf2_init_float_type (objfile, bits, name, name);
17359         break;
17360       case DW_ATE_signed:
17361         type = init_integer_type (objfile, bits, 0, name);
17362         break;
17363       case DW_ATE_unsigned:
17364         if (cu->language == language_fortran
17365             && name
17366             && startswith (name, "character("))
17367           type = init_character_type (objfile, bits, 1, name);
17368         else
17369           type = init_integer_type (objfile, bits, 1, name);
17370         break;
17371       case DW_ATE_signed_char:
17372         if (cu->language == language_ada || cu->language == language_m2
17373             || cu->language == language_pascal
17374             || cu->language == language_fortran)
17375           type = init_character_type (objfile, bits, 0, name);
17376         else
17377           type = init_integer_type (objfile, bits, 0, name);
17378         break;
17379       case DW_ATE_unsigned_char:
17380         if (cu->language == language_ada || cu->language == language_m2
17381             || cu->language == language_pascal
17382             || cu->language == language_fortran
17383             || cu->language == language_rust)
17384           type = init_character_type (objfile, bits, 1, name);
17385         else
17386           type = init_integer_type (objfile, bits, 1, name);
17387         break;
17388       case DW_ATE_UTF:
17389         {
17390           gdbarch *arch = get_objfile_arch (objfile);
17391
17392           if (bits == 16)
17393             type = builtin_type (arch)->builtin_char16;
17394           else if (bits == 32)
17395             type = builtin_type (arch)->builtin_char32;
17396           else
17397             {
17398               complaint (_("unsupported DW_ATE_UTF bit size: '%d'"),
17399                          bits);
17400               type = init_integer_type (objfile, bits, 1, name);
17401             }
17402           return set_die_type (die, type, cu);
17403         }
17404         break;
17405
17406       default:
17407         complaint (_("unsupported DW_AT_encoding: '%s'"),
17408                    dwarf_type_encoding_name (encoding));
17409         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
17410         break;
17411     }
17412
17413   if (name && strcmp (name, "char") == 0)
17414     TYPE_NOSIGN (type) = 1;
17415
17416   maybe_set_alignment (cu, die, type);
17417
17418   return set_die_type (die, type, cu);
17419 }
17420
17421 /* Parse dwarf attribute if it's a block, reference or constant and put the
17422    resulting value of the attribute into struct bound_prop.
17423    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
17424
17425 static int
17426 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
17427                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
17428 {
17429   struct dwarf2_property_baton *baton;
17430   struct obstack *obstack
17431     = &cu->per_cu->dwarf2_per_objfile->objfile->objfile_obstack;
17432
17433   if (attr == NULL || prop == NULL)
17434     return 0;
17435
17436   if (attr_form_is_block (attr))
17437     {
17438       baton = XOBNEW (obstack, struct dwarf2_property_baton);
17439       baton->referenced_type = NULL;
17440       baton->locexpr.per_cu = cu->per_cu;
17441       baton->locexpr.size = DW_BLOCK (attr)->size;
17442       baton->locexpr.data = DW_BLOCK (attr)->data;
17443       prop->data.baton = baton;
17444       prop->kind = PROP_LOCEXPR;
17445       gdb_assert (prop->data.baton != NULL);
17446     }
17447   else if (attr_form_is_ref (attr))
17448     {
17449       struct dwarf2_cu *target_cu = cu;
17450       struct die_info *target_die;
17451       struct attribute *target_attr;
17452
17453       target_die = follow_die_ref (die, attr, &target_cu);
17454       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
17455       if (target_attr == NULL)
17456         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
17457                                    target_cu);
17458       if (target_attr == NULL)
17459         return 0;
17460
17461       switch (target_attr->name)
17462         {
17463           case DW_AT_location:
17464             if (attr_form_is_section_offset (target_attr))
17465               {
17466                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17467                 baton->referenced_type = die_type (target_die, target_cu);
17468                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
17469                 prop->data.baton = baton;
17470                 prop->kind = PROP_LOCLIST;
17471                 gdb_assert (prop->data.baton != NULL);
17472               }
17473             else if (attr_form_is_block (target_attr))
17474               {
17475                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
17476                 baton->referenced_type = die_type (target_die, target_cu);
17477                 baton->locexpr.per_cu = cu->per_cu;
17478                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
17479                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
17480                 prop->data.baton = baton;
17481                 prop->kind = PROP_LOCEXPR;
17482                 gdb_assert (prop->data.baton != NULL);
17483               }
17484             else
17485               {
17486                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17487                                                        "dynamic property");
17488                 return 0;
17489               }
17490             break;
17491           case DW_AT_data_member_location:
17492             {
17493               LONGEST offset;
17494
17495               if (!handle_data_member_location (target_die, target_cu,
17496                                                 &offset))
17497                 return 0;
17498
17499               baton = XOBNEW (obstack, struct dwarf2_property_baton);
17500               baton->referenced_type = read_type_die (target_die->parent,
17501                                                       target_cu);
17502               baton->offset_info.offset = offset;
17503               baton->offset_info.type = die_type (target_die, target_cu);
17504               prop->data.baton = baton;
17505               prop->kind = PROP_ADDR_OFFSET;
17506               break;
17507             }
17508         }
17509     }
17510   else if (attr_form_is_constant (attr))
17511     {
17512       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
17513       prop->kind = PROP_CONST;
17514     }
17515   else
17516     {
17517       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
17518                                              dwarf2_name (die, cu));
17519       return 0;
17520     }
17521
17522   return 1;
17523 }
17524
17525 /* Read the given DW_AT_subrange DIE.  */
17526
17527 static struct type *
17528 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
17529 {
17530   struct type *base_type, *orig_base_type;
17531   struct type *range_type;
17532   struct attribute *attr;
17533   struct dynamic_prop low, high;
17534   int low_default_is_valid;
17535   int high_bound_is_count = 0;
17536   const char *name;
17537   LONGEST negative_mask;
17538
17539   orig_base_type = die_type (die, cu);
17540   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
17541      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
17542      creating the range type, but we use the result of check_typedef
17543      when examining properties of the type.  */
17544   base_type = check_typedef (orig_base_type);
17545
17546   /* The die_type call above may have already set the type for this DIE.  */
17547   range_type = get_die_type (die, cu);
17548   if (range_type)
17549     return range_type;
17550
17551   low.kind = PROP_CONST;
17552   high.kind = PROP_CONST;
17553   high.data.const_val = 0;
17554
17555   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
17556      omitting DW_AT_lower_bound.  */
17557   switch (cu->language)
17558     {
17559     case language_c:
17560     case language_cplus:
17561       low.data.const_val = 0;
17562       low_default_is_valid = 1;
17563       break;
17564     case language_fortran:
17565       low.data.const_val = 1;
17566       low_default_is_valid = 1;
17567       break;
17568     case language_d:
17569     case language_objc:
17570     case language_rust:
17571       low.data.const_val = 0;
17572       low_default_is_valid = (cu->header.version >= 4);
17573       break;
17574     case language_ada:
17575     case language_m2:
17576     case language_pascal:
17577       low.data.const_val = 1;
17578       low_default_is_valid = (cu->header.version >= 4);
17579       break;
17580     default:
17581       low.data.const_val = 0;
17582       low_default_is_valid = 0;
17583       break;
17584     }
17585
17586   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
17587   if (attr)
17588     attr_to_dynamic_prop (attr, die, cu, &low);
17589   else if (!low_default_is_valid)
17590     complaint (_("Missing DW_AT_lower_bound "
17591                                       "- DIE at %s [in module %s]"),
17592                sect_offset_str (die->sect_off),
17593                objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
17594
17595   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
17596   if (!attr_to_dynamic_prop (attr, die, cu, &high))
17597     {
17598       attr = dwarf2_attr (die, DW_AT_count, cu);
17599       if (attr_to_dynamic_prop (attr, die, cu, &high))
17600         {
17601           /* If bounds are constant do the final calculation here.  */
17602           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
17603             high.data.const_val = low.data.const_val + high.data.const_val - 1;
17604           else
17605             high_bound_is_count = 1;
17606         }
17607     }
17608
17609   /* Dwarf-2 specifications explicitly allows to create subrange types
17610      without specifying a base type.
17611      In that case, the base type must be set to the type of
17612      the lower bound, upper bound or count, in that order, if any of these
17613      three attributes references an object that has a type.
17614      If no base type is found, the Dwarf-2 specifications say that
17615      a signed integer type of size equal to the size of an address should
17616      be used.
17617      For the following C code: `extern char gdb_int [];'
17618      GCC produces an empty range DIE.
17619      FIXME: muller/2010-05-28: Possible references to object for low bound,
17620      high bound or count are not yet handled by this code.  */
17621   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
17622     {
17623       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
17624       struct gdbarch *gdbarch = get_objfile_arch (objfile);
17625       int addr_size = gdbarch_addr_bit (gdbarch) /8;
17626       struct type *int_type = objfile_type (objfile)->builtin_int;
17627
17628       /* Test "int", "long int", and "long long int" objfile types,
17629          and select the first one having a size above or equal to the
17630          architecture address size.  */
17631       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17632         base_type = int_type;
17633       else
17634         {
17635           int_type = objfile_type (objfile)->builtin_long;
17636           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17637             base_type = int_type;
17638           else
17639             {
17640               int_type = objfile_type (objfile)->builtin_long_long;
17641               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
17642                 base_type = int_type;
17643             }
17644         }
17645     }
17646
17647   /* Normally, the DWARF producers are expected to use a signed
17648      constant form (Eg. DW_FORM_sdata) to express negative bounds.
17649      But this is unfortunately not always the case, as witnessed
17650      with GCC, for instance, where the ambiguous DW_FORM_dataN form
17651      is used instead.  To work around that ambiguity, we treat
17652      the bounds as signed, and thus sign-extend their values, when
17653      the base type is signed.  */
17654   negative_mask =
17655     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
17656   if (low.kind == PROP_CONST
17657       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
17658     low.data.const_val |= negative_mask;
17659   if (high.kind == PROP_CONST
17660       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
17661     high.data.const_val |= negative_mask;
17662
17663   range_type = create_range_type (NULL, orig_base_type, &low, &high);
17664
17665   if (high_bound_is_count)
17666     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
17667
17668   /* Ada expects an empty array on no boundary attributes.  */
17669   if (attr == NULL && cu->language != language_ada)
17670     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
17671
17672   name = dwarf2_name (die, cu);
17673   if (name)
17674     TYPE_NAME (range_type) = name;
17675
17676   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
17677   if (attr)
17678     TYPE_LENGTH (range_type) = DW_UNSND (attr);
17679
17680   maybe_set_alignment (cu, die, range_type);
17681
17682   set_die_type (die, range_type, cu);
17683
17684   /* set_die_type should be already done.  */
17685   set_descriptive_type (range_type, die, cu);
17686
17687   return range_type;
17688 }
17689
17690 static struct type *
17691 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
17692 {
17693   struct type *type;
17694
17695   type = init_type (cu->per_cu->dwarf2_per_objfile->objfile, TYPE_CODE_VOID,0,
17696                     NULL);
17697   TYPE_NAME (type) = dwarf2_name (die, cu);
17698
17699   /* In Ada, an unspecified type is typically used when the description
17700      of the type is defered to a different unit.  When encountering
17701      such a type, we treat it as a stub, and try to resolve it later on,
17702      when needed.  */
17703   if (cu->language == language_ada)
17704     TYPE_STUB (type) = 1;
17705
17706   return set_die_type (die, type, cu);
17707 }
17708
17709 /* Read a single die and all its descendents.  Set the die's sibling
17710    field to NULL; set other fields in the die correctly, and set all
17711    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
17712    location of the info_ptr after reading all of those dies.  PARENT
17713    is the parent of the die in question.  */
17714
17715 static struct die_info *
17716 read_die_and_children (const struct die_reader_specs *reader,
17717                        const gdb_byte *info_ptr,
17718                        const gdb_byte **new_info_ptr,
17719                        struct die_info *parent)
17720 {
17721   struct die_info *die;
17722   const gdb_byte *cur_ptr;
17723   int has_children;
17724
17725   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
17726   if (die == NULL)
17727     {
17728       *new_info_ptr = cur_ptr;
17729       return NULL;
17730     }
17731   store_in_ref_table (die, reader->cu);
17732
17733   if (has_children)
17734     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
17735   else
17736     {
17737       die->child = NULL;
17738       *new_info_ptr = cur_ptr;
17739     }
17740
17741   die->sibling = NULL;
17742   die->parent = parent;
17743   return die;
17744 }
17745
17746 /* Read a die, all of its descendents, and all of its siblings; set
17747    all of the fields of all of the dies correctly.  Arguments are as
17748    in read_die_and_children.  */
17749
17750 static struct die_info *
17751 read_die_and_siblings_1 (const struct die_reader_specs *reader,
17752                          const gdb_byte *info_ptr,
17753                          const gdb_byte **new_info_ptr,
17754                          struct die_info *parent)
17755 {
17756   struct die_info *first_die, *last_sibling;
17757   const gdb_byte *cur_ptr;
17758
17759   cur_ptr = info_ptr;
17760   first_die = last_sibling = NULL;
17761
17762   while (1)
17763     {
17764       struct die_info *die
17765         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
17766
17767       if (die == NULL)
17768         {
17769           *new_info_ptr = cur_ptr;
17770           return first_die;
17771         }
17772
17773       if (!first_die)
17774         first_die = die;
17775       else
17776         last_sibling->sibling = die;
17777
17778       last_sibling = die;
17779     }
17780 }
17781
17782 /* Read a die, all of its descendents, and all of its siblings; set
17783    all of the fields of all of the dies correctly.  Arguments are as
17784    in read_die_and_children.
17785    This the main entry point for reading a DIE and all its children.  */
17786
17787 static struct die_info *
17788 read_die_and_siblings (const struct die_reader_specs *reader,
17789                        const gdb_byte *info_ptr,
17790                        const gdb_byte **new_info_ptr,
17791                        struct die_info *parent)
17792 {
17793   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
17794                                                   new_info_ptr, parent);
17795
17796   if (dwarf_die_debug)
17797     {
17798       fprintf_unfiltered (gdb_stdlog,
17799                           "Read die from %s@0x%x of %s:\n",
17800                           get_section_name (reader->die_section),
17801                           (unsigned) (info_ptr - reader->die_section->buffer),
17802                           bfd_get_filename (reader->abfd));
17803       dump_die (die, dwarf_die_debug);
17804     }
17805
17806   return die;
17807 }
17808
17809 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
17810    attributes.
17811    The caller is responsible for filling in the extra attributes
17812    and updating (*DIEP)->num_attrs.
17813    Set DIEP to point to a newly allocated die with its information,
17814    except for its child, sibling, and parent fields.
17815    Set HAS_CHILDREN to tell whether the die has children or not.  */
17816
17817 static const gdb_byte *
17818 read_full_die_1 (const struct die_reader_specs *reader,
17819                  struct die_info **diep, const gdb_byte *info_ptr,
17820                  int *has_children, int num_extra_attrs)
17821 {
17822   unsigned int abbrev_number, bytes_read, i;
17823   struct abbrev_info *abbrev;
17824   struct die_info *die;
17825   struct dwarf2_cu *cu = reader->cu;
17826   bfd *abfd = reader->abfd;
17827
17828   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
17829   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17830   info_ptr += bytes_read;
17831   if (!abbrev_number)
17832     {
17833       *diep = NULL;
17834       *has_children = 0;
17835       return info_ptr;
17836     }
17837
17838   abbrev = reader->abbrev_table->lookup_abbrev (abbrev_number);
17839   if (!abbrev)
17840     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
17841            abbrev_number,
17842            bfd_get_filename (abfd));
17843
17844   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
17845   die->sect_off = sect_off;
17846   die->tag = abbrev->tag;
17847   die->abbrev = abbrev_number;
17848
17849   /* Make the result usable.
17850      The caller needs to update num_attrs after adding the extra
17851      attributes.  */
17852   die->num_attrs = abbrev->num_attrs;
17853
17854   for (i = 0; i < abbrev->num_attrs; ++i)
17855     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
17856                                info_ptr);
17857
17858   *diep = die;
17859   *has_children = abbrev->has_children;
17860   return info_ptr;
17861 }
17862
17863 /* Read a die and all its attributes.
17864    Set DIEP to point to a newly allocated die with its information,
17865    except for its child, sibling, and parent fields.
17866    Set HAS_CHILDREN to tell whether the die has children or not.  */
17867
17868 static const gdb_byte *
17869 read_full_die (const struct die_reader_specs *reader,
17870                struct die_info **diep, const gdb_byte *info_ptr,
17871                int *has_children)
17872 {
17873   const gdb_byte *result;
17874
17875   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
17876
17877   if (dwarf_die_debug)
17878     {
17879       fprintf_unfiltered (gdb_stdlog,
17880                           "Read die from %s@0x%x of %s:\n",
17881                           get_section_name (reader->die_section),
17882                           (unsigned) (info_ptr - reader->die_section->buffer),
17883                           bfd_get_filename (reader->abfd));
17884       dump_die (*diep, dwarf_die_debug);
17885     }
17886
17887   return result;
17888 }
17889 \f
17890 /* Abbreviation tables.
17891
17892    In DWARF version 2, the description of the debugging information is
17893    stored in a separate .debug_abbrev section.  Before we read any
17894    dies from a section we read in all abbreviations and install them
17895    in a hash table.  */
17896
17897 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
17898
17899 struct abbrev_info *
17900 abbrev_table::alloc_abbrev ()
17901 {
17902   struct abbrev_info *abbrev;
17903
17904   abbrev = XOBNEW (&abbrev_obstack, struct abbrev_info);
17905   memset (abbrev, 0, sizeof (struct abbrev_info));
17906
17907   return abbrev;
17908 }
17909
17910 /* Add an abbreviation to the table.  */
17911
17912 void
17913 abbrev_table::add_abbrev (unsigned int abbrev_number,
17914                           struct abbrev_info *abbrev)
17915 {
17916   unsigned int hash_number;
17917
17918   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17919   abbrev->next = m_abbrevs[hash_number];
17920   m_abbrevs[hash_number] = abbrev;
17921 }
17922
17923 /* Look up an abbrev in the table.
17924    Returns NULL if the abbrev is not found.  */
17925
17926 struct abbrev_info *
17927 abbrev_table::lookup_abbrev (unsigned int abbrev_number)
17928 {
17929   unsigned int hash_number;
17930   struct abbrev_info *abbrev;
17931
17932   hash_number = abbrev_number % ABBREV_HASH_SIZE;
17933   abbrev = m_abbrevs[hash_number];
17934
17935   while (abbrev)
17936     {
17937       if (abbrev->number == abbrev_number)
17938         return abbrev;
17939       abbrev = abbrev->next;
17940     }
17941   return NULL;
17942 }
17943
17944 /* Read in an abbrev table.  */
17945
17946 static abbrev_table_up
17947 abbrev_table_read_table (struct dwarf2_per_objfile *dwarf2_per_objfile,
17948                          struct dwarf2_section_info *section,
17949                          sect_offset sect_off)
17950 {
17951   struct objfile *objfile = dwarf2_per_objfile->objfile;
17952   bfd *abfd = get_section_bfd_owner (section);
17953   const gdb_byte *abbrev_ptr;
17954   struct abbrev_info *cur_abbrev;
17955   unsigned int abbrev_number, bytes_read, abbrev_name;
17956   unsigned int abbrev_form;
17957   struct attr_abbrev *cur_attrs;
17958   unsigned int allocated_attrs;
17959
17960   abbrev_table_up abbrev_table (new struct abbrev_table (sect_off));
17961
17962   dwarf2_read_section (objfile, section);
17963   abbrev_ptr = section->buffer + to_underlying (sect_off);
17964   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17965   abbrev_ptr += bytes_read;
17966
17967   allocated_attrs = ATTR_ALLOC_CHUNK;
17968   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
17969
17970   /* Loop until we reach an abbrev number of 0.  */
17971   while (abbrev_number)
17972     {
17973       cur_abbrev = abbrev_table->alloc_abbrev ();
17974
17975       /* read in abbrev header */
17976       cur_abbrev->number = abbrev_number;
17977       cur_abbrev->tag
17978         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17979       abbrev_ptr += bytes_read;
17980       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
17981       abbrev_ptr += 1;
17982
17983       /* now read in declarations */
17984       for (;;)
17985         {
17986           LONGEST implicit_const;
17987
17988           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17989           abbrev_ptr += bytes_read;
17990           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
17991           abbrev_ptr += bytes_read;
17992           if (abbrev_form == DW_FORM_implicit_const)
17993             {
17994               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
17995                                                    &bytes_read);
17996               abbrev_ptr += bytes_read;
17997             }
17998           else
17999             {
18000               /* Initialize it due to a false compiler warning.  */
18001               implicit_const = -1;
18002             }
18003
18004           if (abbrev_name == 0)
18005             break;
18006
18007           if (cur_abbrev->num_attrs == allocated_attrs)
18008             {
18009               allocated_attrs += ATTR_ALLOC_CHUNK;
18010               cur_attrs
18011                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
18012             }
18013
18014           cur_attrs[cur_abbrev->num_attrs].name
18015             = (enum dwarf_attribute) abbrev_name;
18016           cur_attrs[cur_abbrev->num_attrs].form
18017             = (enum dwarf_form) abbrev_form;
18018           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
18019           ++cur_abbrev->num_attrs;
18020         }
18021
18022       cur_abbrev->attrs =
18023         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
18024                    cur_abbrev->num_attrs);
18025       memcpy (cur_abbrev->attrs, cur_attrs,
18026               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
18027
18028       abbrev_table->add_abbrev (abbrev_number, cur_abbrev);
18029
18030       /* Get next abbreviation.
18031          Under Irix6 the abbreviations for a compilation unit are not
18032          always properly terminated with an abbrev number of 0.
18033          Exit loop if we encounter an abbreviation which we have
18034          already read (which means we are about to read the abbreviations
18035          for the next compile unit) or if the end of the abbreviation
18036          table is reached.  */
18037       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
18038         break;
18039       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
18040       abbrev_ptr += bytes_read;
18041       if (abbrev_table->lookup_abbrev (abbrev_number) != NULL)
18042         break;
18043     }
18044
18045   xfree (cur_attrs);
18046   return abbrev_table;
18047 }
18048
18049 /* Returns nonzero if TAG represents a type that we might generate a partial
18050    symbol for.  */
18051
18052 static int
18053 is_type_tag_for_partial (int tag)
18054 {
18055   switch (tag)
18056     {
18057 #if 0
18058     /* Some types that would be reasonable to generate partial symbols for,
18059        that we don't at present.  */
18060     case DW_TAG_array_type:
18061     case DW_TAG_file_type:
18062     case DW_TAG_ptr_to_member_type:
18063     case DW_TAG_set_type:
18064     case DW_TAG_string_type:
18065     case DW_TAG_subroutine_type:
18066 #endif
18067     case DW_TAG_base_type:
18068     case DW_TAG_class_type:
18069     case DW_TAG_interface_type:
18070     case DW_TAG_enumeration_type:
18071     case DW_TAG_structure_type:
18072     case DW_TAG_subrange_type:
18073     case DW_TAG_typedef:
18074     case DW_TAG_union_type:
18075       return 1;
18076     default:
18077       return 0;
18078     }
18079 }
18080
18081 /* Load all DIEs that are interesting for partial symbols into memory.  */
18082
18083 static struct partial_die_info *
18084 load_partial_dies (const struct die_reader_specs *reader,
18085                    const gdb_byte *info_ptr, int building_psymtab)
18086 {
18087   struct dwarf2_cu *cu = reader->cu;
18088   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18089   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
18090   unsigned int bytes_read;
18091   unsigned int load_all = 0;
18092   int nesting_level = 1;
18093
18094   parent_die = NULL;
18095   last_die = NULL;
18096
18097   gdb_assert (cu->per_cu != NULL);
18098   if (cu->per_cu->load_all_dies)
18099     load_all = 1;
18100
18101   cu->partial_dies
18102     = htab_create_alloc_ex (cu->header.length / 12,
18103                             partial_die_hash,
18104                             partial_die_eq,
18105                             NULL,
18106                             &cu->comp_unit_obstack,
18107                             hashtab_obstack_allocate,
18108                             dummy_obstack_deallocate);
18109
18110   while (1)
18111     {
18112       abbrev_info *abbrev = peek_die_abbrev (*reader, info_ptr, &bytes_read);
18113
18114       /* A NULL abbrev means the end of a series of children.  */
18115       if (abbrev == NULL)
18116         {
18117           if (--nesting_level == 0)
18118             return first_die;
18119
18120           info_ptr += bytes_read;
18121           last_die = parent_die;
18122           parent_die = parent_die->die_parent;
18123           continue;
18124         }
18125
18126       /* Check for template arguments.  We never save these; if
18127          they're seen, we just mark the parent, and go on our way.  */
18128       if (parent_die != NULL
18129           && cu->language == language_cplus
18130           && (abbrev->tag == DW_TAG_template_type_param
18131               || abbrev->tag == DW_TAG_template_value_param))
18132         {
18133           parent_die->has_template_arguments = 1;
18134
18135           if (!load_all)
18136             {
18137               /* We don't need a partial DIE for the template argument.  */
18138               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18139               continue;
18140             }
18141         }
18142
18143       /* We only recurse into c++ subprograms looking for template arguments.
18144          Skip their other children.  */
18145       if (!load_all
18146           && cu->language == language_cplus
18147           && parent_die != NULL
18148           && parent_die->tag == DW_TAG_subprogram)
18149         {
18150           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18151           continue;
18152         }
18153
18154       /* Check whether this DIE is interesting enough to save.  Normally
18155          we would not be interested in members here, but there may be
18156          later variables referencing them via DW_AT_specification (for
18157          static members).  */
18158       if (!load_all
18159           && !is_type_tag_for_partial (abbrev->tag)
18160           && abbrev->tag != DW_TAG_constant
18161           && abbrev->tag != DW_TAG_enumerator
18162           && abbrev->tag != DW_TAG_subprogram
18163           && abbrev->tag != DW_TAG_inlined_subroutine
18164           && abbrev->tag != DW_TAG_lexical_block
18165           && abbrev->tag != DW_TAG_variable
18166           && abbrev->tag != DW_TAG_namespace
18167           && abbrev->tag != DW_TAG_module
18168           && abbrev->tag != DW_TAG_member
18169           && abbrev->tag != DW_TAG_imported_unit
18170           && abbrev->tag != DW_TAG_imported_declaration)
18171         {
18172           /* Otherwise we skip to the next sibling, if any.  */
18173           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
18174           continue;
18175         }
18176
18177       struct partial_die_info pdi ((sect_offset) (info_ptr - reader->buffer),
18178                                    abbrev);
18179
18180       info_ptr = pdi.read (reader, *abbrev, info_ptr + bytes_read);
18181
18182       /* This two-pass algorithm for processing partial symbols has a
18183          high cost in cache pressure.  Thus, handle some simple cases
18184          here which cover the majority of C partial symbols.  DIEs
18185          which neither have specification tags in them, nor could have
18186          specification tags elsewhere pointing at them, can simply be
18187          processed and discarded.
18188
18189          This segment is also optional; scan_partial_symbols and
18190          add_partial_symbol will handle these DIEs if we chain
18191          them in normally.  When compilers which do not emit large
18192          quantities of duplicate debug information are more common,
18193          this code can probably be removed.  */
18194
18195       /* Any complete simple types at the top level (pretty much all
18196          of them, for a language without namespaces), can be processed
18197          directly.  */
18198       if (parent_die == NULL
18199           && pdi.has_specification == 0
18200           && pdi.is_declaration == 0
18201           && ((pdi.tag == DW_TAG_typedef && !pdi.has_children)
18202               || pdi.tag == DW_TAG_base_type
18203               || pdi.tag == DW_TAG_subrange_type))
18204         {
18205           if (building_psymtab && pdi.name != NULL)
18206             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18207                                  VAR_DOMAIN, LOC_TYPEDEF,
18208                                  &objfile->static_psymbols,
18209                                  0, cu->language, objfile);
18210           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18211           continue;
18212         }
18213
18214       /* The exception for DW_TAG_typedef with has_children above is
18215          a workaround of GCC PR debug/47510.  In the case of this complaint
18216          type_name_or_error will error on such types later.
18217
18218          GDB skipped children of DW_TAG_typedef by the shortcut above and then
18219          it could not find the child DIEs referenced later, this is checked
18220          above.  In correct DWARF DW_TAG_typedef should have no children.  */
18221
18222       if (pdi.tag == DW_TAG_typedef && pdi.has_children)
18223         complaint (_("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
18224                      "- DIE at %s [in module %s]"),
18225                    sect_offset_str (pdi.sect_off), objfile_name (objfile));
18226
18227       /* If we're at the second level, and we're an enumerator, and
18228          our parent has no specification (meaning possibly lives in a
18229          namespace elsewhere), then we can add the partial symbol now
18230          instead of queueing it.  */
18231       if (pdi.tag == DW_TAG_enumerator
18232           && parent_die != NULL
18233           && parent_die->die_parent == NULL
18234           && parent_die->tag == DW_TAG_enumeration_type
18235           && parent_die->has_specification == 0)
18236         {
18237           if (pdi.name == NULL)
18238             complaint (_("malformed enumerator DIE ignored"));
18239           else if (building_psymtab)
18240             add_psymbol_to_list (pdi.name, strlen (pdi.name), 0,
18241                                  VAR_DOMAIN, LOC_CONST,
18242                                  cu->language == language_cplus
18243                                  ? &objfile->global_psymbols
18244                                  : &objfile->static_psymbols,
18245                                  0, cu->language, objfile);
18246
18247           info_ptr = locate_pdi_sibling (reader, &pdi, info_ptr);
18248           continue;
18249         }
18250
18251       struct partial_die_info *part_die
18252         = new (&cu->comp_unit_obstack) partial_die_info (pdi);
18253
18254       /* We'll save this DIE so link it in.  */
18255       part_die->die_parent = parent_die;
18256       part_die->die_sibling = NULL;
18257       part_die->die_child = NULL;
18258
18259       if (last_die && last_die == parent_die)
18260         last_die->die_child = part_die;
18261       else if (last_die)
18262         last_die->die_sibling = part_die;
18263
18264       last_die = part_die;
18265
18266       if (first_die == NULL)
18267         first_die = part_die;
18268
18269       /* Maybe add the DIE to the hash table.  Not all DIEs that we
18270          find interesting need to be in the hash table, because we
18271          also have the parent/sibling/child chains; only those that we
18272          might refer to by offset later during partial symbol reading.
18273
18274          For now this means things that might have be the target of a
18275          DW_AT_specification, DW_AT_abstract_origin, or
18276          DW_AT_extension.  DW_AT_extension will refer only to
18277          namespaces; DW_AT_abstract_origin refers to functions (and
18278          many things under the function DIE, but we do not recurse
18279          into function DIEs during partial symbol reading) and
18280          possibly variables as well; DW_AT_specification refers to
18281          declarations.  Declarations ought to have the DW_AT_declaration
18282          flag.  It happens that GCC forgets to put it in sometimes, but
18283          only for functions, not for types.
18284
18285          Adding more things than necessary to the hash table is harmless
18286          except for the performance cost.  Adding too few will result in
18287          wasted time in find_partial_die, when we reread the compilation
18288          unit with load_all_dies set.  */
18289
18290       if (load_all
18291           || abbrev->tag == DW_TAG_constant
18292           || abbrev->tag == DW_TAG_subprogram
18293           || abbrev->tag == DW_TAG_variable
18294           || abbrev->tag == DW_TAG_namespace
18295           || part_die->is_declaration)
18296         {
18297           void **slot;
18298
18299           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
18300                                            to_underlying (part_die->sect_off),
18301                                            INSERT);
18302           *slot = part_die;
18303         }
18304
18305       /* For some DIEs we want to follow their children (if any).  For C
18306          we have no reason to follow the children of structures; for other
18307          languages we have to, so that we can get at method physnames
18308          to infer fully qualified class names, for DW_AT_specification,
18309          and for C++ template arguments.  For C++, we also look one level
18310          inside functions to find template arguments (if the name of the
18311          function does not already contain the template arguments).
18312
18313          For Ada, we need to scan the children of subprograms and lexical
18314          blocks as well because Ada allows the definition of nested
18315          entities that could be interesting for the debugger, such as
18316          nested subprograms for instance.  */
18317       if (last_die->has_children
18318           && (load_all
18319               || last_die->tag == DW_TAG_namespace
18320               || last_die->tag == DW_TAG_module
18321               || last_die->tag == DW_TAG_enumeration_type
18322               || (cu->language == language_cplus
18323                   && last_die->tag == DW_TAG_subprogram
18324                   && (last_die->name == NULL
18325                       || strchr (last_die->name, '<') == NULL))
18326               || (cu->language != language_c
18327                   && (last_die->tag == DW_TAG_class_type
18328                       || last_die->tag == DW_TAG_interface_type
18329                       || last_die->tag == DW_TAG_structure_type
18330                       || last_die->tag == DW_TAG_union_type))
18331               || (cu->language == language_ada
18332                   && (last_die->tag == DW_TAG_subprogram
18333                       || last_die->tag == DW_TAG_lexical_block))))
18334         {
18335           nesting_level++;
18336           parent_die = last_die;
18337           continue;
18338         }
18339
18340       /* Otherwise we skip to the next sibling, if any.  */
18341       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
18342
18343       /* Back to the top, do it again.  */
18344     }
18345 }
18346
18347 partial_die_info::partial_die_info (sect_offset sect_off_,
18348                                     struct abbrev_info *abbrev)
18349   : partial_die_info (sect_off_, abbrev->tag, abbrev->has_children)
18350 {
18351 }
18352
18353 /* Read a minimal amount of information into the minimal die structure.
18354    INFO_PTR should point just after the initial uleb128 of a DIE.  */
18355
18356 const gdb_byte *
18357 partial_die_info::read (const struct die_reader_specs *reader,
18358                         const struct abbrev_info &abbrev, const gdb_byte *info_ptr)
18359 {
18360   struct dwarf2_cu *cu = reader->cu;
18361   struct dwarf2_per_objfile *dwarf2_per_objfile
18362     = cu->per_cu->dwarf2_per_objfile;
18363   unsigned int i;
18364   int has_low_pc_attr = 0;
18365   int has_high_pc_attr = 0;
18366   int high_pc_relative = 0;
18367
18368   for (i = 0; i < abbrev.num_attrs; ++i)
18369     {
18370       struct attribute attr;
18371
18372       info_ptr = read_attribute (reader, &attr, &abbrev.attrs[i], info_ptr);
18373
18374       /* Store the data if it is of an attribute we want to keep in a
18375          partial symbol table.  */
18376       switch (attr.name)
18377         {
18378         case DW_AT_name:
18379           switch (tag)
18380             {
18381             case DW_TAG_compile_unit:
18382             case DW_TAG_partial_unit:
18383             case DW_TAG_type_unit:
18384               /* Compilation units have a DW_AT_name that is a filename, not
18385                  a source language identifier.  */
18386             case DW_TAG_enumeration_type:
18387             case DW_TAG_enumerator:
18388               /* These tags always have simple identifiers already; no need
18389                  to canonicalize them.  */
18390               name = DW_STRING (&attr);
18391               break;
18392             default:
18393               {
18394                 struct objfile *objfile = dwarf2_per_objfile->objfile;
18395
18396                 name
18397                   = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
18398                                               &objfile->per_bfd->storage_obstack);
18399               }
18400               break;
18401             }
18402           break;
18403         case DW_AT_linkage_name:
18404         case DW_AT_MIPS_linkage_name:
18405           /* Note that both forms of linkage name might appear.  We
18406              assume they will be the same, and we only store the last
18407              one we see.  */
18408           if (cu->language == language_ada)
18409             name = DW_STRING (&attr);
18410           linkage_name = DW_STRING (&attr);
18411           break;
18412         case DW_AT_low_pc:
18413           has_low_pc_attr = 1;
18414           lowpc = attr_value_as_address (&attr);
18415           break;
18416         case DW_AT_high_pc:
18417           has_high_pc_attr = 1;
18418           highpc = attr_value_as_address (&attr);
18419           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
18420                 high_pc_relative = 1;
18421           break;
18422         case DW_AT_location:
18423           /* Support the .debug_loc offsets.  */
18424           if (attr_form_is_block (&attr))
18425             {
18426                d.locdesc = DW_BLOCK (&attr);
18427             }
18428           else if (attr_form_is_section_offset (&attr))
18429             {
18430               dwarf2_complex_location_expr_complaint ();
18431             }
18432           else
18433             {
18434               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
18435                                                      "partial symbol information");
18436             }
18437           break;
18438         case DW_AT_external:
18439           is_external = DW_UNSND (&attr);
18440           break;
18441         case DW_AT_declaration:
18442           is_declaration = DW_UNSND (&attr);
18443           break;
18444         case DW_AT_type:
18445           has_type = 1;
18446           break;
18447         case DW_AT_abstract_origin:
18448         case DW_AT_specification:
18449         case DW_AT_extension:
18450           has_specification = 1;
18451           spec_offset = dwarf2_get_ref_die_offset (&attr);
18452           spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18453                                    || cu->per_cu->is_dwz);
18454           break;
18455         case DW_AT_sibling:
18456           /* Ignore absolute siblings, they might point outside of
18457              the current compile unit.  */
18458           if (attr.form == DW_FORM_ref_addr)
18459             complaint (_("ignoring absolute DW_AT_sibling"));
18460           else
18461             {
18462               const gdb_byte *buffer = reader->buffer;
18463               sect_offset off = dwarf2_get_ref_die_offset (&attr);
18464               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
18465
18466               if (sibling_ptr < info_ptr)
18467                 complaint (_("DW_AT_sibling points backwards"));
18468               else if (sibling_ptr > reader->buffer_end)
18469                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
18470               else
18471                 sibling = sibling_ptr;
18472             }
18473           break;
18474         case DW_AT_byte_size:
18475           has_byte_size = 1;
18476           break;
18477         case DW_AT_const_value:
18478           has_const_value = 1;
18479           break;
18480         case DW_AT_calling_convention:
18481           /* DWARF doesn't provide a way to identify a program's source-level
18482              entry point.  DW_AT_calling_convention attributes are only meant
18483              to describe functions' calling conventions.
18484
18485              However, because it's a necessary piece of information in
18486              Fortran, and before DWARF 4 DW_CC_program was the only
18487              piece of debugging information whose definition refers to
18488              a 'main program' at all, several compilers marked Fortran
18489              main programs with DW_CC_program --- even when those
18490              functions use the standard calling conventions.
18491
18492              Although DWARF now specifies a way to provide this
18493              information, we support this practice for backward
18494              compatibility.  */
18495           if (DW_UNSND (&attr) == DW_CC_program
18496               && cu->language == language_fortran)
18497             main_subprogram = 1;
18498           break;
18499         case DW_AT_inline:
18500           if (DW_UNSND (&attr) == DW_INL_inlined
18501               || DW_UNSND (&attr) == DW_INL_declared_inlined)
18502             may_be_inlined = 1;
18503           break;
18504
18505         case DW_AT_import:
18506           if (tag == DW_TAG_imported_unit)
18507             {
18508               d.sect_off = dwarf2_get_ref_die_offset (&attr);
18509               is_dwz = (attr.form == DW_FORM_GNU_ref_alt
18510                                   || cu->per_cu->is_dwz);
18511             }
18512           break;
18513
18514         case DW_AT_main_subprogram:
18515           main_subprogram = DW_UNSND (&attr);
18516           break;
18517
18518         default:
18519           break;
18520         }
18521     }
18522
18523   if (high_pc_relative)
18524     highpc += lowpc;
18525
18526   if (has_low_pc_attr && has_high_pc_attr)
18527     {
18528       /* When using the GNU linker, .gnu.linkonce. sections are used to
18529          eliminate duplicate copies of functions and vtables and such.
18530          The linker will arbitrarily choose one and discard the others.
18531          The AT_*_pc values for such functions refer to local labels in
18532          these sections.  If the section from that file was discarded, the
18533          labels are not in the output, so the relocs get a value of 0.
18534          If this is a discarded function, mark the pc bounds as invalid,
18535          so that GDB will ignore it.  */
18536       if (lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
18537         {
18538           struct objfile *objfile = dwarf2_per_objfile->objfile;
18539           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18540
18541           complaint (_("DW_AT_low_pc %s is zero "
18542                        "for DIE at %s [in module %s]"),
18543                      paddress (gdbarch, lowpc),
18544                      sect_offset_str (sect_off),
18545                      objfile_name (objfile));
18546         }
18547       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
18548       else if (lowpc >= highpc)
18549         {
18550           struct objfile *objfile = dwarf2_per_objfile->objfile;
18551           struct gdbarch *gdbarch = get_objfile_arch (objfile);
18552
18553           complaint (_("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
18554                        "for DIE at %s [in module %s]"),
18555                      paddress (gdbarch, lowpc),
18556                      paddress (gdbarch, highpc),
18557                      sect_offset_str (sect_off),
18558                      objfile_name (objfile));
18559         }
18560       else
18561         has_pc_info = 1;
18562     }
18563
18564   return info_ptr;
18565 }
18566
18567 /* Find a cached partial DIE at OFFSET in CU.  */
18568
18569 struct partial_die_info *
18570 dwarf2_cu::find_partial_die (sect_offset sect_off)
18571 {
18572   struct partial_die_info *lookup_die = NULL;
18573   struct partial_die_info part_die (sect_off);
18574
18575   lookup_die = ((struct partial_die_info *)
18576                 htab_find_with_hash (partial_dies, &part_die,
18577                                      to_underlying (sect_off)));
18578
18579   return lookup_die;
18580 }
18581
18582 /* Find a partial DIE at OFFSET, which may or may not be in CU,
18583    except in the case of .debug_types DIEs which do not reference
18584    outside their CU (they do however referencing other types via
18585    DW_FORM_ref_sig8).  */
18586
18587 static struct partial_die_info *
18588 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
18589 {
18590   struct dwarf2_per_objfile *dwarf2_per_objfile
18591     = cu->per_cu->dwarf2_per_objfile;
18592   struct objfile *objfile = dwarf2_per_objfile->objfile;
18593   struct dwarf2_per_cu_data *per_cu = NULL;
18594   struct partial_die_info *pd = NULL;
18595
18596   if (offset_in_dwz == cu->per_cu->is_dwz
18597       && offset_in_cu_p (&cu->header, sect_off))
18598     {
18599       pd = cu->find_partial_die (sect_off);
18600       if (pd != NULL)
18601         return pd;
18602       /* We missed recording what we needed.
18603          Load all dies and try again.  */
18604       per_cu = cu->per_cu;
18605     }
18606   else
18607     {
18608       /* TUs don't reference other CUs/TUs (except via type signatures).  */
18609       if (cu->per_cu->is_debug_types)
18610         {
18611           error (_("Dwarf Error: Type Unit at offset %s contains"
18612                    " external reference to offset %s [in module %s].\n"),
18613                  sect_offset_str (cu->header.sect_off), sect_offset_str (sect_off),
18614                  bfd_get_filename (objfile->obfd));
18615         }
18616       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
18617                                                  dwarf2_per_objfile);
18618
18619       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
18620         load_partial_comp_unit (per_cu);
18621
18622       per_cu->cu->last_used = 0;
18623       pd = per_cu->cu->find_partial_die (sect_off);
18624     }
18625
18626   /* If we didn't find it, and not all dies have been loaded,
18627      load them all and try again.  */
18628
18629   if (pd == NULL && per_cu->load_all_dies == 0)
18630     {
18631       per_cu->load_all_dies = 1;
18632
18633       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
18634          THIS_CU->cu may already be in use.  So we can't just free it and
18635          replace its DIEs with the ones we read in.  Instead, we leave those
18636          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
18637          and clobber THIS_CU->cu->partial_dies with the hash table for the new
18638          set.  */
18639       load_partial_comp_unit (per_cu);
18640
18641       pd = per_cu->cu->find_partial_die (sect_off);
18642     }
18643
18644   if (pd == NULL)
18645     internal_error (__FILE__, __LINE__,
18646                     _("could not find partial DIE %s "
18647                       "in cache [from module %s]\n"),
18648                     sect_offset_str (sect_off), bfd_get_filename (objfile->obfd));
18649   return pd;
18650 }
18651
18652 /* See if we can figure out if the class lives in a namespace.  We do
18653    this by looking for a member function; its demangled name will
18654    contain namespace info, if there is any.  */
18655
18656 static void
18657 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
18658                                   struct dwarf2_cu *cu)
18659 {
18660   /* NOTE: carlton/2003-10-07: Getting the info this way changes
18661      what template types look like, because the demangler
18662      frequently doesn't give the same name as the debug info.  We
18663      could fix this by only using the demangled name to get the
18664      prefix (but see comment in read_structure_type).  */
18665
18666   struct partial_die_info *real_pdi;
18667   struct partial_die_info *child_pdi;
18668
18669   /* If this DIE (this DIE's specification, if any) has a parent, then
18670      we should not do this.  We'll prepend the parent's fully qualified
18671      name when we create the partial symbol.  */
18672
18673   real_pdi = struct_pdi;
18674   while (real_pdi->has_specification)
18675     real_pdi = find_partial_die (real_pdi->spec_offset,
18676                                  real_pdi->spec_is_dwz, cu);
18677
18678   if (real_pdi->die_parent != NULL)
18679     return;
18680
18681   for (child_pdi = struct_pdi->die_child;
18682        child_pdi != NULL;
18683        child_pdi = child_pdi->die_sibling)
18684     {
18685       if (child_pdi->tag == DW_TAG_subprogram
18686           && child_pdi->linkage_name != NULL)
18687         {
18688           char *actual_class_name
18689             = language_class_name_from_physname (cu->language_defn,
18690                                                  child_pdi->linkage_name);
18691           if (actual_class_name != NULL)
18692             {
18693               struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18694               struct_pdi->name
18695                 = ((const char *)
18696                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
18697                                   actual_class_name,
18698                                   strlen (actual_class_name)));
18699               xfree (actual_class_name);
18700             }
18701           break;
18702         }
18703     }
18704 }
18705
18706 void
18707 partial_die_info::fixup (struct dwarf2_cu *cu)
18708 {
18709   /* Once we've fixed up a die, there's no point in doing so again.
18710      This also avoids a memory leak if we were to call
18711      guess_partial_die_structure_name multiple times.  */
18712   if (fixup_called)
18713     return;
18714
18715   /* If we found a reference attribute and the DIE has no name, try
18716      to find a name in the referred to DIE.  */
18717
18718   if (name == NULL && has_specification)
18719     {
18720       struct partial_die_info *spec_die;
18721
18722       spec_die = find_partial_die (spec_offset, spec_is_dwz, cu);
18723
18724       spec_die->fixup (cu);
18725
18726       if (spec_die->name)
18727         {
18728           name = spec_die->name;
18729
18730           /* Copy DW_AT_external attribute if it is set.  */
18731           if (spec_die->is_external)
18732             is_external = spec_die->is_external;
18733         }
18734     }
18735
18736   /* Set default names for some unnamed DIEs.  */
18737
18738   if (name == NULL && tag == DW_TAG_namespace)
18739     name = CP_ANONYMOUS_NAMESPACE_STR;
18740
18741   /* If there is no parent die to provide a namespace, and there are
18742      children, see if we can determine the namespace from their linkage
18743      name.  */
18744   if (cu->language == language_cplus
18745       && !VEC_empty (dwarf2_section_info_def,
18746                      cu->per_cu->dwarf2_per_objfile->types)
18747       && die_parent == NULL
18748       && has_children
18749       && (tag == DW_TAG_class_type
18750           || tag == DW_TAG_structure_type
18751           || tag == DW_TAG_union_type))
18752     guess_partial_die_structure_name (this, cu);
18753
18754   /* GCC might emit a nameless struct or union that has a linkage
18755      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
18756   if (name == NULL
18757       && (tag == DW_TAG_class_type
18758           || tag == DW_TAG_interface_type
18759           || tag == DW_TAG_structure_type
18760           || tag == DW_TAG_union_type)
18761       && linkage_name != NULL)
18762     {
18763       char *demangled;
18764
18765       demangled = gdb_demangle (linkage_name, DMGL_TYPES);
18766       if (demangled)
18767         {
18768           const char *base;
18769
18770           /* Strip any leading namespaces/classes, keep only the base name.
18771              DW_AT_name for named DIEs does not contain the prefixes.  */
18772           base = strrchr (demangled, ':');
18773           if (base && base > demangled && base[-1] == ':')
18774             base++;
18775           else
18776             base = demangled;
18777
18778           struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
18779           name
18780             = ((const char *)
18781                obstack_copy0 (&objfile->per_bfd->storage_obstack,
18782                               base, strlen (base)));
18783           xfree (demangled);
18784         }
18785     }
18786
18787   fixup_called = 1;
18788 }
18789
18790 /* Read an attribute value described by an attribute form.  */
18791
18792 static const gdb_byte *
18793 read_attribute_value (const struct die_reader_specs *reader,
18794                       struct attribute *attr, unsigned form,
18795                       LONGEST implicit_const, const gdb_byte *info_ptr)
18796 {
18797   struct dwarf2_cu *cu = reader->cu;
18798   struct dwarf2_per_objfile *dwarf2_per_objfile
18799     = cu->per_cu->dwarf2_per_objfile;
18800   struct objfile *objfile = dwarf2_per_objfile->objfile;
18801   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18802   bfd *abfd = reader->abfd;
18803   struct comp_unit_head *cu_header = &cu->header;
18804   unsigned int bytes_read;
18805   struct dwarf_block *blk;
18806
18807   attr->form = (enum dwarf_form) form;
18808   switch (form)
18809     {
18810     case DW_FORM_ref_addr:
18811       if (cu->header.version == 2)
18812         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18813       else
18814         DW_UNSND (attr) = read_offset (abfd, info_ptr,
18815                                        &cu->header, &bytes_read);
18816       info_ptr += bytes_read;
18817       break;
18818     case DW_FORM_GNU_ref_alt:
18819       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18820       info_ptr += bytes_read;
18821       break;
18822     case DW_FORM_addr:
18823       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
18824       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
18825       info_ptr += bytes_read;
18826       break;
18827     case DW_FORM_block2:
18828       blk = dwarf_alloc_block (cu);
18829       blk->size = read_2_bytes (abfd, info_ptr);
18830       info_ptr += 2;
18831       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18832       info_ptr += blk->size;
18833       DW_BLOCK (attr) = blk;
18834       break;
18835     case DW_FORM_block4:
18836       blk = dwarf_alloc_block (cu);
18837       blk->size = read_4_bytes (abfd, info_ptr);
18838       info_ptr += 4;
18839       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18840       info_ptr += blk->size;
18841       DW_BLOCK (attr) = blk;
18842       break;
18843     case DW_FORM_data2:
18844       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
18845       info_ptr += 2;
18846       break;
18847     case DW_FORM_data4:
18848       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
18849       info_ptr += 4;
18850       break;
18851     case DW_FORM_data8:
18852       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
18853       info_ptr += 8;
18854       break;
18855     case DW_FORM_data16:
18856       blk = dwarf_alloc_block (cu);
18857       blk->size = 16;
18858       blk->data = read_n_bytes (abfd, info_ptr, 16);
18859       info_ptr += 16;
18860       DW_BLOCK (attr) = blk;
18861       break;
18862     case DW_FORM_sec_offset:
18863       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
18864       info_ptr += bytes_read;
18865       break;
18866     case DW_FORM_string:
18867       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
18868       DW_STRING_IS_CANONICAL (attr) = 0;
18869       info_ptr += bytes_read;
18870       break;
18871     case DW_FORM_strp:
18872       if (!cu->per_cu->is_dwz)
18873         {
18874           DW_STRING (attr) = read_indirect_string (dwarf2_per_objfile,
18875                                                    abfd, info_ptr, cu_header,
18876                                                    &bytes_read);
18877           DW_STRING_IS_CANONICAL (attr) = 0;
18878           info_ptr += bytes_read;
18879           break;
18880         }
18881       /* FALLTHROUGH */
18882     case DW_FORM_line_strp:
18883       if (!cu->per_cu->is_dwz)
18884         {
18885           DW_STRING (attr) = read_indirect_line_string (dwarf2_per_objfile,
18886                                                         abfd, info_ptr,
18887                                                         cu_header, &bytes_read);
18888           DW_STRING_IS_CANONICAL (attr) = 0;
18889           info_ptr += bytes_read;
18890           break;
18891         }
18892       /* FALLTHROUGH */
18893     case DW_FORM_GNU_strp_alt:
18894       {
18895         struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
18896         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
18897                                           &bytes_read);
18898
18899         DW_STRING (attr) = read_indirect_string_from_dwz (objfile,
18900                                                           dwz, str_offset);
18901         DW_STRING_IS_CANONICAL (attr) = 0;
18902         info_ptr += bytes_read;
18903       }
18904       break;
18905     case DW_FORM_exprloc:
18906     case DW_FORM_block:
18907       blk = dwarf_alloc_block (cu);
18908       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18909       info_ptr += bytes_read;
18910       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18911       info_ptr += blk->size;
18912       DW_BLOCK (attr) = blk;
18913       break;
18914     case DW_FORM_block1:
18915       blk = dwarf_alloc_block (cu);
18916       blk->size = read_1_byte (abfd, info_ptr);
18917       info_ptr += 1;
18918       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
18919       info_ptr += blk->size;
18920       DW_BLOCK (attr) = blk;
18921       break;
18922     case DW_FORM_data1:
18923       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18924       info_ptr += 1;
18925       break;
18926     case DW_FORM_flag:
18927       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
18928       info_ptr += 1;
18929       break;
18930     case DW_FORM_flag_present:
18931       DW_UNSND (attr) = 1;
18932       break;
18933     case DW_FORM_sdata:
18934       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18935       info_ptr += bytes_read;
18936       break;
18937     case DW_FORM_udata:
18938       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18939       info_ptr += bytes_read;
18940       break;
18941     case DW_FORM_ref1:
18942       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18943                          + read_1_byte (abfd, info_ptr));
18944       info_ptr += 1;
18945       break;
18946     case DW_FORM_ref2:
18947       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18948                          + read_2_bytes (abfd, info_ptr));
18949       info_ptr += 2;
18950       break;
18951     case DW_FORM_ref4:
18952       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18953                          + read_4_bytes (abfd, info_ptr));
18954       info_ptr += 4;
18955       break;
18956     case DW_FORM_ref8:
18957       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18958                          + read_8_bytes (abfd, info_ptr));
18959       info_ptr += 8;
18960       break;
18961     case DW_FORM_ref_sig8:
18962       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
18963       info_ptr += 8;
18964       break;
18965     case DW_FORM_ref_udata:
18966       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
18967                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
18968       info_ptr += bytes_read;
18969       break;
18970     case DW_FORM_indirect:
18971       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
18972       info_ptr += bytes_read;
18973       if (form == DW_FORM_implicit_const)
18974         {
18975           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
18976           info_ptr += bytes_read;
18977         }
18978       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
18979                                        info_ptr);
18980       break;
18981     case DW_FORM_implicit_const:
18982       DW_SND (attr) = implicit_const;
18983       break;
18984     case DW_FORM_GNU_addr_index:
18985       if (reader->dwo_file == NULL)
18986         {
18987           /* For now flag a hard error.
18988              Later we can turn this into a complaint.  */
18989           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
18990                  dwarf_form_name (form),
18991                  bfd_get_filename (abfd));
18992         }
18993       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
18994       info_ptr += bytes_read;
18995       break;
18996     case DW_FORM_GNU_str_index:
18997       if (reader->dwo_file == NULL)
18998         {
18999           /* For now flag a hard error.
19000              Later we can turn this into a complaint if warranted.  */
19001           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
19002                  dwarf_form_name (form),
19003                  bfd_get_filename (abfd));
19004         }
19005       {
19006         ULONGEST str_index =
19007           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
19008
19009         DW_STRING (attr) = read_str_index (reader, str_index);
19010         DW_STRING_IS_CANONICAL (attr) = 0;
19011         info_ptr += bytes_read;
19012       }
19013       break;
19014     default:
19015       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
19016              dwarf_form_name (form),
19017              bfd_get_filename (abfd));
19018     }
19019
19020   /* Super hack.  */
19021   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
19022     attr->form = DW_FORM_GNU_ref_alt;
19023
19024   /* We have seen instances where the compiler tried to emit a byte
19025      size attribute of -1 which ended up being encoded as an unsigned
19026      0xffffffff.  Although 0xffffffff is technically a valid size value,
19027      an object of this size seems pretty unlikely so we can relatively
19028      safely treat these cases as if the size attribute was invalid and
19029      treat them as zero by default.  */
19030   if (attr->name == DW_AT_byte_size
19031       && form == DW_FORM_data4
19032       && DW_UNSND (attr) >= 0xffffffff)
19033     {
19034       complaint
19035         (_("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
19036          hex_string (DW_UNSND (attr)));
19037       DW_UNSND (attr) = 0;
19038     }
19039
19040   return info_ptr;
19041 }
19042
19043 /* Read an attribute described by an abbreviated attribute.  */
19044
19045 static const gdb_byte *
19046 read_attribute (const struct die_reader_specs *reader,
19047                 struct attribute *attr, struct attr_abbrev *abbrev,
19048                 const gdb_byte *info_ptr)
19049 {
19050   attr->name = abbrev->name;
19051   return read_attribute_value (reader, attr, abbrev->form,
19052                                abbrev->implicit_const, info_ptr);
19053 }
19054
19055 /* Read dwarf information from a buffer.  */
19056
19057 static unsigned int
19058 read_1_byte (bfd *abfd, const gdb_byte *buf)
19059 {
19060   return bfd_get_8 (abfd, buf);
19061 }
19062
19063 static int
19064 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
19065 {
19066   return bfd_get_signed_8 (abfd, buf);
19067 }
19068
19069 static unsigned int
19070 read_2_bytes (bfd *abfd, const gdb_byte *buf)
19071 {
19072   return bfd_get_16 (abfd, buf);
19073 }
19074
19075 static int
19076 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
19077 {
19078   return bfd_get_signed_16 (abfd, buf);
19079 }
19080
19081 static unsigned int
19082 read_4_bytes (bfd *abfd, const gdb_byte *buf)
19083 {
19084   return bfd_get_32 (abfd, buf);
19085 }
19086
19087 static int
19088 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
19089 {
19090   return bfd_get_signed_32 (abfd, buf);
19091 }
19092
19093 static ULONGEST
19094 read_8_bytes (bfd *abfd, const gdb_byte *buf)
19095 {
19096   return bfd_get_64 (abfd, buf);
19097 }
19098
19099 static CORE_ADDR
19100 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
19101               unsigned int *bytes_read)
19102 {
19103   struct comp_unit_head *cu_header = &cu->header;
19104   CORE_ADDR retval = 0;
19105
19106   if (cu_header->signed_addr_p)
19107     {
19108       switch (cu_header->addr_size)
19109         {
19110         case 2:
19111           retval = bfd_get_signed_16 (abfd, buf);
19112           break;
19113         case 4:
19114           retval = bfd_get_signed_32 (abfd, buf);
19115           break;
19116         case 8:
19117           retval = bfd_get_signed_64 (abfd, buf);
19118           break;
19119         default:
19120           internal_error (__FILE__, __LINE__,
19121                           _("read_address: bad switch, signed [in module %s]"),
19122                           bfd_get_filename (abfd));
19123         }
19124     }
19125   else
19126     {
19127       switch (cu_header->addr_size)
19128         {
19129         case 2:
19130           retval = bfd_get_16 (abfd, buf);
19131           break;
19132         case 4:
19133           retval = bfd_get_32 (abfd, buf);
19134           break;
19135         case 8:
19136           retval = bfd_get_64 (abfd, buf);
19137           break;
19138         default:
19139           internal_error (__FILE__, __LINE__,
19140                           _("read_address: bad switch, "
19141                             "unsigned [in module %s]"),
19142                           bfd_get_filename (abfd));
19143         }
19144     }
19145
19146   *bytes_read = cu_header->addr_size;
19147   return retval;
19148 }
19149
19150 /* Read the initial length from a section.  The (draft) DWARF 3
19151    specification allows the initial length to take up either 4 bytes
19152    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
19153    bytes describe the length and all offsets will be 8 bytes in length
19154    instead of 4.
19155
19156    An older, non-standard 64-bit format is also handled by this
19157    function.  The older format in question stores the initial length
19158    as an 8-byte quantity without an escape value.  Lengths greater
19159    than 2^32 aren't very common which means that the initial 4 bytes
19160    is almost always zero.  Since a length value of zero doesn't make
19161    sense for the 32-bit format, this initial zero can be considered to
19162    be an escape value which indicates the presence of the older 64-bit
19163    format.  As written, the code can't detect (old format) lengths
19164    greater than 4GB.  If it becomes necessary to handle lengths
19165    somewhat larger than 4GB, we could allow other small values (such
19166    as the non-sensical values of 1, 2, and 3) to also be used as
19167    escape values indicating the presence of the old format.
19168
19169    The value returned via bytes_read should be used to increment the
19170    relevant pointer after calling read_initial_length().
19171
19172    [ Note:  read_initial_length() and read_offset() are based on the
19173      document entitled "DWARF Debugging Information Format", revision
19174      3, draft 8, dated November 19, 2001.  This document was obtained
19175      from:
19176
19177         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
19178
19179      This document is only a draft and is subject to change.  (So beware.)
19180
19181      Details regarding the older, non-standard 64-bit format were
19182      determined empirically by examining 64-bit ELF files produced by
19183      the SGI toolchain on an IRIX 6.5 machine.
19184
19185      - Kevin, July 16, 2002
19186    ] */
19187
19188 static LONGEST
19189 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
19190 {
19191   LONGEST length = bfd_get_32 (abfd, buf);
19192
19193   if (length == 0xffffffff)
19194     {
19195       length = bfd_get_64 (abfd, buf + 4);
19196       *bytes_read = 12;
19197     }
19198   else if (length == 0)
19199     {
19200       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
19201       length = bfd_get_64 (abfd, buf);
19202       *bytes_read = 8;
19203     }
19204   else
19205     {
19206       *bytes_read = 4;
19207     }
19208
19209   return length;
19210 }
19211
19212 /* Cover function for read_initial_length.
19213    Returns the length of the object at BUF, and stores the size of the
19214    initial length in *BYTES_READ and stores the size that offsets will be in
19215    *OFFSET_SIZE.
19216    If the initial length size is not equivalent to that specified in
19217    CU_HEADER then issue a complaint.
19218    This is useful when reading non-comp-unit headers.  */
19219
19220 static LONGEST
19221 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
19222                                         const struct comp_unit_head *cu_header,
19223                                         unsigned int *bytes_read,
19224                                         unsigned int *offset_size)
19225 {
19226   LONGEST length = read_initial_length (abfd, buf, bytes_read);
19227
19228   gdb_assert (cu_header->initial_length_size == 4
19229               || cu_header->initial_length_size == 8
19230               || cu_header->initial_length_size == 12);
19231
19232   if (cu_header->initial_length_size != *bytes_read)
19233     complaint (_("intermixed 32-bit and 64-bit DWARF sections"));
19234
19235   *offset_size = (*bytes_read == 4) ? 4 : 8;
19236   return length;
19237 }
19238
19239 /* Read an offset from the data stream.  The size of the offset is
19240    given by cu_header->offset_size.  */
19241
19242 static LONGEST
19243 read_offset (bfd *abfd, const gdb_byte *buf,
19244              const struct comp_unit_head *cu_header,
19245              unsigned int *bytes_read)
19246 {
19247   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
19248
19249   *bytes_read = cu_header->offset_size;
19250   return offset;
19251 }
19252
19253 /* Read an offset from the data stream.  */
19254
19255 static LONGEST
19256 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
19257 {
19258   LONGEST retval = 0;
19259
19260   switch (offset_size)
19261     {
19262     case 4:
19263       retval = bfd_get_32 (abfd, buf);
19264       break;
19265     case 8:
19266       retval = bfd_get_64 (abfd, buf);
19267       break;
19268     default:
19269       internal_error (__FILE__, __LINE__,
19270                       _("read_offset_1: bad switch [in module %s]"),
19271                       bfd_get_filename (abfd));
19272     }
19273
19274   return retval;
19275 }
19276
19277 static const gdb_byte *
19278 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
19279 {
19280   /* If the size of a host char is 8 bits, we can return a pointer
19281      to the buffer, otherwise we have to copy the data to a buffer
19282      allocated on the temporary obstack.  */
19283   gdb_assert (HOST_CHAR_BIT == 8);
19284   return buf;
19285 }
19286
19287 static const char *
19288 read_direct_string (bfd *abfd, const gdb_byte *buf,
19289                     unsigned int *bytes_read_ptr)
19290 {
19291   /* If the size of a host char is 8 bits, we can return a pointer
19292      to the string, otherwise we have to copy the string to a buffer
19293      allocated on the temporary obstack.  */
19294   gdb_assert (HOST_CHAR_BIT == 8);
19295   if (*buf == '\0')
19296     {
19297       *bytes_read_ptr = 1;
19298       return NULL;
19299     }
19300   *bytes_read_ptr = strlen ((const char *) buf) + 1;
19301   return (const char *) buf;
19302 }
19303
19304 /* Return pointer to string at section SECT offset STR_OFFSET with error
19305    reporting strings FORM_NAME and SECT_NAME.  */
19306
19307 static const char *
19308 read_indirect_string_at_offset_from (struct objfile *objfile,
19309                                      bfd *abfd, LONGEST str_offset,
19310                                      struct dwarf2_section_info *sect,
19311                                      const char *form_name,
19312                                      const char *sect_name)
19313 {
19314   dwarf2_read_section (objfile, sect);
19315   if (sect->buffer == NULL)
19316     error (_("%s used without %s section [in module %s]"),
19317            form_name, sect_name, bfd_get_filename (abfd));
19318   if (str_offset >= sect->size)
19319     error (_("%s pointing outside of %s section [in module %s]"),
19320            form_name, sect_name, bfd_get_filename (abfd));
19321   gdb_assert (HOST_CHAR_BIT == 8);
19322   if (sect->buffer[str_offset] == '\0')
19323     return NULL;
19324   return (const char *) (sect->buffer + str_offset);
19325 }
19326
19327 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
19328
19329 static const char *
19330 read_indirect_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19331                                 bfd *abfd, LONGEST str_offset)
19332 {
19333   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19334                                               abfd, str_offset,
19335                                               &dwarf2_per_objfile->str,
19336                                               "DW_FORM_strp", ".debug_str");
19337 }
19338
19339 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
19340
19341 static const char *
19342 read_indirect_line_string_at_offset (struct dwarf2_per_objfile *dwarf2_per_objfile,
19343                                      bfd *abfd, LONGEST str_offset)
19344 {
19345   return read_indirect_string_at_offset_from (dwarf2_per_objfile->objfile,
19346                                               abfd, str_offset,
19347                                               &dwarf2_per_objfile->line_str,
19348                                               "DW_FORM_line_strp",
19349                                               ".debug_line_str");
19350 }
19351
19352 /* Read a string at offset STR_OFFSET in the .debug_str section from
19353    the .dwz file DWZ.  Throw an error if the offset is too large.  If
19354    the string consists of a single NUL byte, return NULL; otherwise
19355    return a pointer to the string.  */
19356
19357 static const char *
19358 read_indirect_string_from_dwz (struct objfile *objfile, struct dwz_file *dwz,
19359                                LONGEST str_offset)
19360 {
19361   dwarf2_read_section (objfile, &dwz->str);
19362
19363   if (dwz->str.buffer == NULL)
19364     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
19365              "section [in module %s]"),
19366            bfd_get_filename (dwz->dwz_bfd));
19367   if (str_offset >= dwz->str.size)
19368     error (_("DW_FORM_GNU_strp_alt pointing outside of "
19369              ".debug_str section [in module %s]"),
19370            bfd_get_filename (dwz->dwz_bfd));
19371   gdb_assert (HOST_CHAR_BIT == 8);
19372   if (dwz->str.buffer[str_offset] == '\0')
19373     return NULL;
19374   return (const char *) (dwz->str.buffer + str_offset);
19375 }
19376
19377 /* Return pointer to string at .debug_str offset as read from BUF.
19378    BUF is assumed to be in a compilation unit described by CU_HEADER.
19379    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19380
19381 static const char *
19382 read_indirect_string (struct dwarf2_per_objfile *dwarf2_per_objfile, bfd *abfd,
19383                       const gdb_byte *buf,
19384                       const struct comp_unit_head *cu_header,
19385                       unsigned int *bytes_read_ptr)
19386 {
19387   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19388
19389   return read_indirect_string_at_offset (dwarf2_per_objfile, abfd, str_offset);
19390 }
19391
19392 /* Return pointer to string at .debug_line_str offset as read from BUF.
19393    BUF is assumed to be in a compilation unit described by CU_HEADER.
19394    Return *BYTES_READ_PTR count of bytes read from BUF.  */
19395
19396 static const char *
19397 read_indirect_line_string (struct dwarf2_per_objfile *dwarf2_per_objfile,
19398                            bfd *abfd, const gdb_byte *buf,
19399                            const struct comp_unit_head *cu_header,
19400                            unsigned int *bytes_read_ptr)
19401 {
19402   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
19403
19404   return read_indirect_line_string_at_offset (dwarf2_per_objfile, abfd,
19405                                               str_offset);
19406 }
19407
19408 ULONGEST
19409 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
19410                           unsigned int *bytes_read_ptr)
19411 {
19412   ULONGEST result;
19413   unsigned int num_read;
19414   int shift;
19415   unsigned char byte;
19416
19417   result = 0;
19418   shift = 0;
19419   num_read = 0;
19420   while (1)
19421     {
19422       byte = bfd_get_8 (abfd, buf);
19423       buf++;
19424       num_read++;
19425       result |= ((ULONGEST) (byte & 127) << shift);
19426       if ((byte & 128) == 0)
19427         {
19428           break;
19429         }
19430       shift += 7;
19431     }
19432   *bytes_read_ptr = num_read;
19433   return result;
19434 }
19435
19436 static LONGEST
19437 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
19438                     unsigned int *bytes_read_ptr)
19439 {
19440   LONGEST result;
19441   int shift, num_read;
19442   unsigned char byte;
19443
19444   result = 0;
19445   shift = 0;
19446   num_read = 0;
19447   while (1)
19448     {
19449       byte = bfd_get_8 (abfd, buf);
19450       buf++;
19451       num_read++;
19452       result |= ((LONGEST) (byte & 127) << shift);
19453       shift += 7;
19454       if ((byte & 128) == 0)
19455         {
19456           break;
19457         }
19458     }
19459   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
19460     result |= -(((LONGEST) 1) << shift);
19461   *bytes_read_ptr = num_read;
19462   return result;
19463 }
19464
19465 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
19466    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
19467    ADDR_SIZE is the size of addresses from the CU header.  */
19468
19469 static CORE_ADDR
19470 read_addr_index_1 (struct dwarf2_per_objfile *dwarf2_per_objfile,
19471                    unsigned int addr_index, ULONGEST addr_base, int addr_size)
19472 {
19473   struct objfile *objfile = dwarf2_per_objfile->objfile;
19474   bfd *abfd = objfile->obfd;
19475   const gdb_byte *info_ptr;
19476
19477   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
19478   if (dwarf2_per_objfile->addr.buffer == NULL)
19479     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
19480            objfile_name (objfile));
19481   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
19482     error (_("DW_FORM_addr_index pointing outside of "
19483              ".debug_addr section [in module %s]"),
19484            objfile_name (objfile));
19485   info_ptr = (dwarf2_per_objfile->addr.buffer
19486               + addr_base + addr_index * addr_size);
19487   if (addr_size == 4)
19488     return bfd_get_32 (abfd, info_ptr);
19489   else
19490     return bfd_get_64 (abfd, info_ptr);
19491 }
19492
19493 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
19494
19495 static CORE_ADDR
19496 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
19497 {
19498   return read_addr_index_1 (cu->per_cu->dwarf2_per_objfile, addr_index,
19499                             cu->addr_base, cu->header.addr_size);
19500 }
19501
19502 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
19503
19504 static CORE_ADDR
19505 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
19506                              unsigned int *bytes_read)
19507 {
19508   bfd *abfd = cu->per_cu->dwarf2_per_objfile->objfile->obfd;
19509   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
19510
19511   return read_addr_index (cu, addr_index);
19512 }
19513
19514 /* Data structure to pass results from dwarf2_read_addr_index_reader
19515    back to dwarf2_read_addr_index.  */
19516
19517 struct dwarf2_read_addr_index_data
19518 {
19519   ULONGEST addr_base;
19520   int addr_size;
19521 };
19522
19523 /* die_reader_func for dwarf2_read_addr_index.  */
19524
19525 static void
19526 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
19527                                const gdb_byte *info_ptr,
19528                                struct die_info *comp_unit_die,
19529                                int has_children,
19530                                void *data)
19531 {
19532   struct dwarf2_cu *cu = reader->cu;
19533   struct dwarf2_read_addr_index_data *aidata =
19534     (struct dwarf2_read_addr_index_data *) data;
19535
19536   aidata->addr_base = cu->addr_base;
19537   aidata->addr_size = cu->header.addr_size;
19538 }
19539
19540 /* Given an index in .debug_addr, fetch the value.
19541    NOTE: This can be called during dwarf expression evaluation,
19542    long after the debug information has been read, and thus per_cu->cu
19543    may no longer exist.  */
19544
19545 CORE_ADDR
19546 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
19547                         unsigned int addr_index)
19548 {
19549   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
19550   struct dwarf2_cu *cu = per_cu->cu;
19551   ULONGEST addr_base;
19552   int addr_size;
19553
19554   /* We need addr_base and addr_size.
19555      If we don't have PER_CU->cu, we have to get it.
19556      Nasty, but the alternative is storing the needed info in PER_CU,
19557      which at this point doesn't seem justified: it's not clear how frequently
19558      it would get used and it would increase the size of every PER_CU.
19559      Entry points like dwarf2_per_cu_addr_size do a similar thing
19560      so we're not in uncharted territory here.
19561      Alas we need to be a bit more complicated as addr_base is contained
19562      in the DIE.
19563
19564      We don't need to read the entire CU(/TU).
19565      We just need the header and top level die.
19566
19567      IWBN to use the aging mechanism to let us lazily later discard the CU.
19568      For now we skip this optimization.  */
19569
19570   if (cu != NULL)
19571     {
19572       addr_base = cu->addr_base;
19573       addr_size = cu->header.addr_size;
19574     }
19575   else
19576     {
19577       struct dwarf2_read_addr_index_data aidata;
19578
19579       /* Note: We can't use init_cutu_and_read_dies_simple here,
19580          we need addr_base.  */
19581       init_cutu_and_read_dies (per_cu, NULL, 0, 0, false,
19582                                dwarf2_read_addr_index_reader, &aidata);
19583       addr_base = aidata.addr_base;
19584       addr_size = aidata.addr_size;
19585     }
19586
19587   return read_addr_index_1 (dwarf2_per_objfile, addr_index, addr_base,
19588                             addr_size);
19589 }
19590
19591 /* Given a DW_FORM_GNU_str_index, fetch the string.
19592    This is only used by the Fission support.  */
19593
19594 static const char *
19595 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
19596 {
19597   struct dwarf2_cu *cu = reader->cu;
19598   struct dwarf2_per_objfile *dwarf2_per_objfile
19599     = cu->per_cu->dwarf2_per_objfile;
19600   struct objfile *objfile = dwarf2_per_objfile->objfile;
19601   const char *objf_name = objfile_name (objfile);
19602   bfd *abfd = objfile->obfd;
19603   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
19604   struct dwarf2_section_info *str_offsets_section =
19605     &reader->dwo_file->sections.str_offsets;
19606   const gdb_byte *info_ptr;
19607   ULONGEST str_offset;
19608   static const char form_name[] = "DW_FORM_GNU_str_index";
19609
19610   dwarf2_read_section (objfile, str_section);
19611   dwarf2_read_section (objfile, str_offsets_section);
19612   if (str_section->buffer == NULL)
19613     error (_("%s used without .debug_str.dwo section"
19614              " in CU at offset %s [in module %s]"),
19615            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19616   if (str_offsets_section->buffer == NULL)
19617     error (_("%s used without .debug_str_offsets.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_index * cu->header.offset_size >= str_offsets_section->size)
19621     error (_("%s pointing outside of .debug_str_offsets.dwo"
19622              " section in CU at offset %s [in module %s]"),
19623            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19624   info_ptr = (str_offsets_section->buffer
19625               + str_index * cu->header.offset_size);
19626   if (cu->header.offset_size == 4)
19627     str_offset = bfd_get_32 (abfd, info_ptr);
19628   else
19629     str_offset = bfd_get_64 (abfd, info_ptr);
19630   if (str_offset >= str_section->size)
19631     error (_("Offset from %s pointing outside of"
19632              " .debug_str.dwo section in CU at offset %s [in module %s]"),
19633            form_name, sect_offset_str (cu->header.sect_off), objf_name);
19634   return (const char *) (str_section->buffer + str_offset);
19635 }
19636
19637 /* Return the length of an LEB128 number in BUF.  */
19638
19639 static int
19640 leb128_size (const gdb_byte *buf)
19641 {
19642   const gdb_byte *begin = buf;
19643   gdb_byte byte;
19644
19645   while (1)
19646     {
19647       byte = *buf++;
19648       if ((byte & 128) == 0)
19649         return buf - begin;
19650     }
19651 }
19652
19653 static void
19654 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
19655 {
19656   switch (lang)
19657     {
19658     case DW_LANG_C89:
19659     case DW_LANG_C99:
19660     case DW_LANG_C11:
19661     case DW_LANG_C:
19662     case DW_LANG_UPC:
19663       cu->language = language_c;
19664       break;
19665     case DW_LANG_Java:
19666     case DW_LANG_C_plus_plus:
19667     case DW_LANG_C_plus_plus_11:
19668     case DW_LANG_C_plus_plus_14:
19669       cu->language = language_cplus;
19670       break;
19671     case DW_LANG_D:
19672       cu->language = language_d;
19673       break;
19674     case DW_LANG_Fortran77:
19675     case DW_LANG_Fortran90:
19676     case DW_LANG_Fortran95:
19677     case DW_LANG_Fortran03:
19678     case DW_LANG_Fortran08:
19679       cu->language = language_fortran;
19680       break;
19681     case DW_LANG_Go:
19682       cu->language = language_go;
19683       break;
19684     case DW_LANG_Mips_Assembler:
19685       cu->language = language_asm;
19686       break;
19687     case DW_LANG_Ada83:
19688     case DW_LANG_Ada95:
19689       cu->language = language_ada;
19690       break;
19691     case DW_LANG_Modula2:
19692       cu->language = language_m2;
19693       break;
19694     case DW_LANG_Pascal83:
19695       cu->language = language_pascal;
19696       break;
19697     case DW_LANG_ObjC:
19698       cu->language = language_objc;
19699       break;
19700     case DW_LANG_Rust:
19701     case DW_LANG_Rust_old:
19702       cu->language = language_rust;
19703       break;
19704     case DW_LANG_Cobol74:
19705     case DW_LANG_Cobol85:
19706     default:
19707       cu->language = language_minimal;
19708       break;
19709     }
19710   cu->language_defn = language_def (cu->language);
19711 }
19712
19713 /* Return the named attribute or NULL if not there.  */
19714
19715 static struct attribute *
19716 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19717 {
19718   for (;;)
19719     {
19720       unsigned int i;
19721       struct attribute *spec = NULL;
19722
19723       for (i = 0; i < die->num_attrs; ++i)
19724         {
19725           if (die->attrs[i].name == name)
19726             return &die->attrs[i];
19727           if (die->attrs[i].name == DW_AT_specification
19728               || die->attrs[i].name == DW_AT_abstract_origin)
19729             spec = &die->attrs[i];
19730         }
19731
19732       if (!spec)
19733         break;
19734
19735       die = follow_die_ref (die, spec, &cu);
19736     }
19737
19738   return NULL;
19739 }
19740
19741 /* Return the named attribute or NULL if not there,
19742    but do not follow DW_AT_specification, etc.
19743    This is for use in contexts where we're reading .debug_types dies.
19744    Following DW_AT_specification, DW_AT_abstract_origin will take us
19745    back up the chain, and we want to go down.  */
19746
19747 static struct attribute *
19748 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
19749 {
19750   unsigned int i;
19751
19752   for (i = 0; i < die->num_attrs; ++i)
19753     if (die->attrs[i].name == name)
19754       return &die->attrs[i];
19755
19756   return NULL;
19757 }
19758
19759 /* Return the string associated with a string-typed attribute, or NULL if it
19760    is either not found or is of an incorrect type.  */
19761
19762 static const char *
19763 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
19764 {
19765   struct attribute *attr;
19766   const char *str = NULL;
19767
19768   attr = dwarf2_attr (die, name, cu);
19769
19770   if (attr != NULL)
19771     {
19772       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
19773           || attr->form == DW_FORM_string
19774           || attr->form == DW_FORM_GNU_str_index
19775           || attr->form == DW_FORM_GNU_strp_alt)
19776         str = DW_STRING (attr);
19777       else
19778         complaint (_("string type expected for attribute %s for "
19779                      "DIE at %s in module %s"),
19780                    dwarf_attr_name (name), sect_offset_str (die->sect_off),
19781                    objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
19782     }
19783
19784   return str;
19785 }
19786
19787 /* Return non-zero iff the attribute NAME is defined for the given DIE,
19788    and holds a non-zero value.  This function should only be used for
19789    DW_FORM_flag or DW_FORM_flag_present attributes.  */
19790
19791 static int
19792 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
19793 {
19794   struct attribute *attr = dwarf2_attr (die, name, cu);
19795
19796   return (attr && DW_UNSND (attr));
19797 }
19798
19799 static int
19800 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
19801 {
19802   /* A DIE is a declaration if it has a DW_AT_declaration attribute
19803      which value is non-zero.  However, we have to be careful with
19804      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
19805      (via dwarf2_flag_true_p) follows this attribute.  So we may
19806      end up accidently finding a declaration attribute that belongs
19807      to a different DIE referenced by the specification attribute,
19808      even though the given DIE does not have a declaration attribute.  */
19809   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
19810           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
19811 }
19812
19813 /* Return the die giving the specification for DIE, if there is
19814    one.  *SPEC_CU is the CU containing DIE on input, and the CU
19815    containing the return value on output.  If there is no
19816    specification, but there is an abstract origin, that is
19817    returned.  */
19818
19819 static struct die_info *
19820 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
19821 {
19822   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
19823                                              *spec_cu);
19824
19825   if (spec_attr == NULL)
19826     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
19827
19828   if (spec_attr == NULL)
19829     return NULL;
19830   else
19831     return follow_die_ref (die, spec_attr, spec_cu);
19832 }
19833
19834 /* Stub for free_line_header to match void * callback types.  */
19835
19836 static void
19837 free_line_header_voidp (void *arg)
19838 {
19839   struct line_header *lh = (struct line_header *) arg;
19840
19841   delete lh;
19842 }
19843
19844 void
19845 line_header::add_include_dir (const char *include_dir)
19846 {
19847   if (dwarf_line_debug >= 2)
19848     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
19849                         include_dirs.size () + 1, include_dir);
19850
19851   include_dirs.push_back (include_dir);
19852 }
19853
19854 void
19855 line_header::add_file_name (const char *name,
19856                             dir_index d_index,
19857                             unsigned int mod_time,
19858                             unsigned int length)
19859 {
19860   if (dwarf_line_debug >= 2)
19861     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
19862                         (unsigned) file_names.size () + 1, name);
19863
19864   file_names.emplace_back (name, d_index, mod_time, length);
19865 }
19866
19867 /* A convenience function to find the proper .debug_line section for a CU.  */
19868
19869 static struct dwarf2_section_info *
19870 get_debug_line_section (struct dwarf2_cu *cu)
19871 {
19872   struct dwarf2_section_info *section;
19873   struct dwarf2_per_objfile *dwarf2_per_objfile
19874     = cu->per_cu->dwarf2_per_objfile;
19875
19876   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
19877      DWO file.  */
19878   if (cu->dwo_unit && cu->per_cu->is_debug_types)
19879     section = &cu->dwo_unit->dwo_file->sections.line;
19880   else if (cu->per_cu->is_dwz)
19881     {
19882       struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
19883
19884       section = &dwz->line;
19885     }
19886   else
19887     section = &dwarf2_per_objfile->line;
19888
19889   return section;
19890 }
19891
19892 /* Read directory or file name entry format, starting with byte of
19893    format count entries, ULEB128 pairs of entry formats, ULEB128 of
19894    entries count and the entries themselves in the described entry
19895    format.  */
19896
19897 static void
19898 read_formatted_entries (struct dwarf2_per_objfile *dwarf2_per_objfile,
19899                         bfd *abfd, const gdb_byte **bufp,
19900                         struct line_header *lh,
19901                         const struct comp_unit_head *cu_header,
19902                         void (*callback) (struct line_header *lh,
19903                                           const char *name,
19904                                           dir_index d_index,
19905                                           unsigned int mod_time,
19906                                           unsigned int length))
19907 {
19908   gdb_byte format_count, formati;
19909   ULONGEST data_count, datai;
19910   const gdb_byte *buf = *bufp;
19911   const gdb_byte *format_header_data;
19912   unsigned int bytes_read;
19913
19914   format_count = read_1_byte (abfd, buf);
19915   buf += 1;
19916   format_header_data = buf;
19917   for (formati = 0; formati < format_count; formati++)
19918     {
19919       read_unsigned_leb128 (abfd, buf, &bytes_read);
19920       buf += bytes_read;
19921       read_unsigned_leb128 (abfd, buf, &bytes_read);
19922       buf += bytes_read;
19923     }
19924
19925   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
19926   buf += bytes_read;
19927   for (datai = 0; datai < data_count; datai++)
19928     {
19929       const gdb_byte *format = format_header_data;
19930       struct file_entry fe;
19931
19932       for (formati = 0; formati < format_count; formati++)
19933         {
19934           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
19935           format += bytes_read;
19936
19937           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
19938           format += bytes_read;
19939
19940           gdb::optional<const char *> string;
19941           gdb::optional<unsigned int> uint;
19942
19943           switch (form)
19944             {
19945             case DW_FORM_string:
19946               string.emplace (read_direct_string (abfd, buf, &bytes_read));
19947               buf += bytes_read;
19948               break;
19949
19950             case DW_FORM_line_strp:
19951               string.emplace (read_indirect_line_string (dwarf2_per_objfile,
19952                                                          abfd, buf,
19953                                                          cu_header,
19954                                                          &bytes_read));
19955               buf += bytes_read;
19956               break;
19957
19958             case DW_FORM_data1:
19959               uint.emplace (read_1_byte (abfd, buf));
19960               buf += 1;
19961               break;
19962
19963             case DW_FORM_data2:
19964               uint.emplace (read_2_bytes (abfd, buf));
19965               buf += 2;
19966               break;
19967
19968             case DW_FORM_data4:
19969               uint.emplace (read_4_bytes (abfd, buf));
19970               buf += 4;
19971               break;
19972
19973             case DW_FORM_data8:
19974               uint.emplace (read_8_bytes (abfd, buf));
19975               buf += 8;
19976               break;
19977
19978             case DW_FORM_udata:
19979               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
19980               buf += bytes_read;
19981               break;
19982
19983             case DW_FORM_block:
19984               /* It is valid only for DW_LNCT_timestamp which is ignored by
19985                  current GDB.  */
19986               break;
19987             }
19988
19989           switch (content_type)
19990             {
19991             case DW_LNCT_path:
19992               if (string.has_value ())
19993                 fe.name = *string;
19994               break;
19995             case DW_LNCT_directory_index:
19996               if (uint.has_value ())
19997                 fe.d_index = (dir_index) *uint;
19998               break;
19999             case DW_LNCT_timestamp:
20000               if (uint.has_value ())
20001                 fe.mod_time = *uint;
20002               break;
20003             case DW_LNCT_size:
20004               if (uint.has_value ())
20005                 fe.length = *uint;
20006               break;
20007             case DW_LNCT_MD5:
20008               break;
20009             default:
20010               complaint (_("Unknown format content type %s"),
20011                          pulongest (content_type));
20012             }
20013         }
20014
20015       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
20016     }
20017
20018   *bufp = buf;
20019 }
20020
20021 /* Read the statement program header starting at OFFSET in
20022    .debug_line, or .debug_line.dwo.  Return a pointer
20023    to a struct line_header, allocated using xmalloc.
20024    Returns NULL if there is a problem reading the header, e.g., if it
20025    has a version we don't understand.
20026
20027    NOTE: the strings in the include directory and file name tables of
20028    the returned object point into the dwarf line section buffer,
20029    and must not be freed.  */
20030
20031 static line_header_up
20032 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
20033 {
20034   const gdb_byte *line_ptr;
20035   unsigned int bytes_read, offset_size;
20036   int i;
20037   const char *cur_dir, *cur_file;
20038   struct dwarf2_section_info *section;
20039   bfd *abfd;
20040   struct dwarf2_per_objfile *dwarf2_per_objfile
20041     = cu->per_cu->dwarf2_per_objfile;
20042
20043   section = get_debug_line_section (cu);
20044   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
20045   if (section->buffer == NULL)
20046     {
20047       if (cu->dwo_unit && cu->per_cu->is_debug_types)
20048         complaint (_("missing .debug_line.dwo section"));
20049       else
20050         complaint (_("missing .debug_line section"));
20051       return 0;
20052     }
20053
20054   /* We can't do this until we know the section is non-empty.
20055      Only then do we know we have such a section.  */
20056   abfd = get_section_bfd_owner (section);
20057
20058   /* Make sure that at least there's room for the total_length field.
20059      That could be 12 bytes long, but we're just going to fudge that.  */
20060   if (to_underlying (sect_off) + 4 >= section->size)
20061     {
20062       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20063       return 0;
20064     }
20065
20066   line_header_up lh (new line_header ());
20067
20068   lh->sect_off = sect_off;
20069   lh->offset_in_dwz = cu->per_cu->is_dwz;
20070
20071   line_ptr = section->buffer + to_underlying (sect_off);
20072
20073   /* Read in the header.  */
20074   lh->total_length =
20075     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
20076                                             &bytes_read, &offset_size);
20077   line_ptr += bytes_read;
20078   if (line_ptr + lh->total_length > (section->buffer + section->size))
20079     {
20080       dwarf2_statement_list_fits_in_line_number_section_complaint ();
20081       return 0;
20082     }
20083   lh->statement_program_end = line_ptr + lh->total_length;
20084   lh->version = read_2_bytes (abfd, line_ptr);
20085   line_ptr += 2;
20086   if (lh->version > 5)
20087     {
20088       /* This is a version we don't understand.  The format could have
20089          changed in ways we don't handle properly so just punt.  */
20090       complaint (_("unsupported version in .debug_line section"));
20091       return NULL;
20092     }
20093   if (lh->version >= 5)
20094     {
20095       gdb_byte segment_selector_size;
20096
20097       /* Skip address size.  */
20098       read_1_byte (abfd, line_ptr);
20099       line_ptr += 1;
20100
20101       segment_selector_size = read_1_byte (abfd, line_ptr);
20102       line_ptr += 1;
20103       if (segment_selector_size != 0)
20104         {
20105           complaint (_("unsupported segment selector size %u "
20106                        "in .debug_line section"),
20107                      segment_selector_size);
20108           return NULL;
20109         }
20110     }
20111   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
20112   line_ptr += offset_size;
20113   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
20114   line_ptr += 1;
20115   if (lh->version >= 4)
20116     {
20117       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
20118       line_ptr += 1;
20119     }
20120   else
20121     lh->maximum_ops_per_instruction = 1;
20122
20123   if (lh->maximum_ops_per_instruction == 0)
20124     {
20125       lh->maximum_ops_per_instruction = 1;
20126       complaint (_("invalid maximum_ops_per_instruction "
20127                    "in `.debug_line' section"));
20128     }
20129
20130   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
20131   line_ptr += 1;
20132   lh->line_base = read_1_signed_byte (abfd, line_ptr);
20133   line_ptr += 1;
20134   lh->line_range = read_1_byte (abfd, line_ptr);
20135   line_ptr += 1;
20136   lh->opcode_base = read_1_byte (abfd, line_ptr);
20137   line_ptr += 1;
20138   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
20139
20140   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
20141   for (i = 1; i < lh->opcode_base; ++i)
20142     {
20143       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
20144       line_ptr += 1;
20145     }
20146
20147   if (lh->version >= 5)
20148     {
20149       /* Read directory table.  */
20150       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20151                               &cu->header,
20152                               [] (struct line_header *lh, const char *name,
20153                                   dir_index d_index, unsigned int mod_time,
20154                                   unsigned int length)
20155         {
20156           lh->add_include_dir (name);
20157         });
20158
20159       /* Read file name table.  */
20160       read_formatted_entries (dwarf2_per_objfile, abfd, &line_ptr, lh.get (),
20161                               &cu->header,
20162                               [] (struct line_header *lh, const char *name,
20163                                   dir_index d_index, unsigned int mod_time,
20164                                   unsigned int length)
20165         {
20166           lh->add_file_name (name, d_index, mod_time, length);
20167         });
20168     }
20169   else
20170     {
20171       /* Read directory table.  */
20172       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20173         {
20174           line_ptr += bytes_read;
20175           lh->add_include_dir (cur_dir);
20176         }
20177       line_ptr += bytes_read;
20178
20179       /* Read file name table.  */
20180       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
20181         {
20182           unsigned int mod_time, length;
20183           dir_index d_index;
20184
20185           line_ptr += bytes_read;
20186           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20187           line_ptr += bytes_read;
20188           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20189           line_ptr += bytes_read;
20190           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20191           line_ptr += bytes_read;
20192
20193           lh->add_file_name (cur_file, d_index, mod_time, length);
20194         }
20195       line_ptr += bytes_read;
20196     }
20197   lh->statement_program_start = line_ptr;
20198
20199   if (line_ptr > (section->buffer + section->size))
20200     complaint (_("line number info header doesn't "
20201                  "fit in `.debug_line' section"));
20202
20203   return lh;
20204 }
20205
20206 /* Subroutine of dwarf_decode_lines to simplify it.
20207    Return the file name of the psymtab for included file FILE_INDEX
20208    in line header LH of PST.
20209    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20210    If space for the result is malloc'd, *NAME_HOLDER will be set.
20211    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.  */
20212
20213 static const char *
20214 psymtab_include_file_name (const struct line_header *lh, int file_index,
20215                            const struct partial_symtab *pst,
20216                            const char *comp_dir,
20217                            gdb::unique_xmalloc_ptr<char> *name_holder)
20218 {
20219   const file_entry &fe = lh->file_names[file_index];
20220   const char *include_name = fe.name;
20221   const char *include_name_to_compare = include_name;
20222   const char *pst_filename;
20223   int file_is_pst;
20224
20225   const char *dir_name = fe.include_dir (lh);
20226
20227   gdb::unique_xmalloc_ptr<char> hold_compare;
20228   if (!IS_ABSOLUTE_PATH (include_name)
20229       && (dir_name != NULL || comp_dir != NULL))
20230     {
20231       /* Avoid creating a duplicate psymtab for PST.
20232          We do this by comparing INCLUDE_NAME and PST_FILENAME.
20233          Before we do the comparison, however, we need to account
20234          for DIR_NAME and COMP_DIR.
20235          First prepend dir_name (if non-NULL).  If we still don't
20236          have an absolute path prepend comp_dir (if non-NULL).
20237          However, the directory we record in the include-file's
20238          psymtab does not contain COMP_DIR (to match the
20239          corresponding symtab(s)).
20240
20241          Example:
20242
20243          bash$ cd /tmp
20244          bash$ gcc -g ./hello.c
20245          include_name = "hello.c"
20246          dir_name = "."
20247          DW_AT_comp_dir = comp_dir = "/tmp"
20248          DW_AT_name = "./hello.c"
20249
20250       */
20251
20252       if (dir_name != NULL)
20253         {
20254           name_holder->reset (concat (dir_name, SLASH_STRING,
20255                                       include_name, (char *) NULL));
20256           include_name = name_holder->get ();
20257           include_name_to_compare = include_name;
20258         }
20259       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
20260         {
20261           hold_compare.reset (concat (comp_dir, SLASH_STRING,
20262                                       include_name, (char *) NULL));
20263           include_name_to_compare = hold_compare.get ();
20264         }
20265     }
20266
20267   pst_filename = pst->filename;
20268   gdb::unique_xmalloc_ptr<char> copied_name;
20269   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
20270     {
20271       copied_name.reset (concat (pst->dirname, SLASH_STRING,
20272                                  pst_filename, (char *) NULL));
20273       pst_filename = copied_name.get ();
20274     }
20275
20276   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
20277
20278   if (file_is_pst)
20279     return NULL;
20280   return include_name;
20281 }
20282
20283 /* State machine to track the state of the line number program.  */
20284
20285 class lnp_state_machine
20286 {
20287 public:
20288   /* Initialize a machine state for the start of a line number
20289      program.  */
20290   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
20291
20292   file_entry *current_file ()
20293   {
20294     /* lh->file_names is 0-based, but the file name numbers in the
20295        statement program are 1-based.  */
20296     return m_line_header->file_name_at (m_file);
20297   }
20298
20299   /* Record the line in the state machine.  END_SEQUENCE is true if
20300      we're processing the end of a sequence.  */
20301   void record_line (bool end_sequence);
20302
20303   /* Check ADDRESS is zero and less than UNRELOCATED_LOWPC and if true
20304      nop-out rest of the lines in this sequence.  */
20305   void check_line_address (struct dwarf2_cu *cu,
20306                            const gdb_byte *line_ptr,
20307                            CORE_ADDR unrelocated_lowpc, CORE_ADDR address);
20308
20309   void handle_set_discriminator (unsigned int discriminator)
20310   {
20311     m_discriminator = discriminator;
20312     m_line_has_non_zero_discriminator |= discriminator != 0;
20313   }
20314
20315   /* Handle DW_LNE_set_address.  */
20316   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
20317   {
20318     m_op_index = 0;
20319     address += baseaddr;
20320     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
20321   }
20322
20323   /* Handle DW_LNS_advance_pc.  */
20324   void handle_advance_pc (CORE_ADDR adjust);
20325
20326   /* Handle a special opcode.  */
20327   void handle_special_opcode (unsigned char op_code);
20328
20329   /* Handle DW_LNS_advance_line.  */
20330   void handle_advance_line (int line_delta)
20331   {
20332     advance_line (line_delta);
20333   }
20334
20335   /* Handle DW_LNS_set_file.  */
20336   void handle_set_file (file_name_index file);
20337
20338   /* Handle DW_LNS_negate_stmt.  */
20339   void handle_negate_stmt ()
20340   {
20341     m_is_stmt = !m_is_stmt;
20342   }
20343
20344   /* Handle DW_LNS_const_add_pc.  */
20345   void handle_const_add_pc ();
20346
20347   /* Handle DW_LNS_fixed_advance_pc.  */
20348   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
20349   {
20350     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20351     m_op_index = 0;
20352   }
20353
20354   /* Handle DW_LNS_copy.  */
20355   void handle_copy ()
20356   {
20357     record_line (false);
20358     m_discriminator = 0;
20359   }
20360
20361   /* Handle DW_LNE_end_sequence.  */
20362   void handle_end_sequence ()
20363   {
20364     m_record_line_callback = ::record_line;
20365   }
20366
20367 private:
20368   /* Advance the line by LINE_DELTA.  */
20369   void advance_line (int line_delta)
20370   {
20371     m_line += line_delta;
20372
20373     if (line_delta != 0)
20374       m_line_has_non_zero_discriminator = m_discriminator != 0;
20375   }
20376
20377   gdbarch *m_gdbarch;
20378
20379   /* True if we're recording lines.
20380      Otherwise we're building partial symtabs and are just interested in
20381      finding include files mentioned by the line number program.  */
20382   bool m_record_lines_p;
20383
20384   /* The line number header.  */
20385   line_header *m_line_header;
20386
20387   /* These are part of the standard DWARF line number state machine,
20388      and initialized according to the DWARF spec.  */
20389
20390   unsigned char m_op_index = 0;
20391   /* The line table index (1-based) of the current file.  */
20392   file_name_index m_file = (file_name_index) 1;
20393   unsigned int m_line = 1;
20394
20395   /* These are initialized in the constructor.  */
20396
20397   CORE_ADDR m_address;
20398   bool m_is_stmt;
20399   unsigned int m_discriminator;
20400
20401   /* Additional bits of state we need to track.  */
20402
20403   /* The last file that we called dwarf2_start_subfile for.
20404      This is only used for TLLs.  */
20405   unsigned int m_last_file = 0;
20406   /* The last file a line number was recorded for.  */
20407   struct subfile *m_last_subfile = NULL;
20408
20409   /* The function to call to record a line.  */
20410   record_line_ftype *m_record_line_callback = NULL;
20411
20412   /* The last line number that was recorded, used to coalesce
20413      consecutive entries for the same line.  This can happen, for
20414      example, when discriminators are present.  PR 17276.  */
20415   unsigned int m_last_line = 0;
20416   bool m_line_has_non_zero_discriminator = false;
20417 };
20418
20419 void
20420 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
20421 {
20422   CORE_ADDR addr_adj = (((m_op_index + adjust)
20423                          / m_line_header->maximum_ops_per_instruction)
20424                         * m_line_header->minimum_instruction_length);
20425   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20426   m_op_index = ((m_op_index + adjust)
20427                 % m_line_header->maximum_ops_per_instruction);
20428 }
20429
20430 void
20431 lnp_state_machine::handle_special_opcode (unsigned char op_code)
20432 {
20433   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
20434   CORE_ADDR addr_adj = (((m_op_index
20435                           + (adj_opcode / m_line_header->line_range))
20436                          / m_line_header->maximum_ops_per_instruction)
20437                         * m_line_header->minimum_instruction_length);
20438   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20439   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
20440                 % m_line_header->maximum_ops_per_instruction);
20441
20442   int line_delta = (m_line_header->line_base
20443                     + (adj_opcode % m_line_header->line_range));
20444   advance_line (line_delta);
20445   record_line (false);
20446   m_discriminator = 0;
20447 }
20448
20449 void
20450 lnp_state_machine::handle_set_file (file_name_index file)
20451 {
20452   m_file = file;
20453
20454   const file_entry *fe = current_file ();
20455   if (fe == NULL)
20456     dwarf2_debug_line_missing_file_complaint ();
20457   else if (m_record_lines_p)
20458     {
20459       const char *dir = fe->include_dir (m_line_header);
20460
20461       m_last_subfile = get_current_subfile ();
20462       m_line_has_non_zero_discriminator = m_discriminator != 0;
20463       dwarf2_start_subfile (fe->name, dir);
20464     }
20465 }
20466
20467 void
20468 lnp_state_machine::handle_const_add_pc ()
20469 {
20470   CORE_ADDR adjust
20471     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
20472
20473   CORE_ADDR addr_adj
20474     = (((m_op_index + adjust)
20475         / m_line_header->maximum_ops_per_instruction)
20476        * m_line_header->minimum_instruction_length);
20477
20478   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
20479   m_op_index = ((m_op_index + adjust)
20480                 % m_line_header->maximum_ops_per_instruction);
20481 }
20482
20483 /* Ignore this record_line request.  */
20484
20485 static void
20486 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
20487 {
20488   return;
20489 }
20490
20491 /* Return non-zero if we should add LINE to the line number table.
20492    LINE is the line to add, LAST_LINE is the last line that was added,
20493    LAST_SUBFILE is the subfile for LAST_LINE.
20494    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
20495    had a non-zero discriminator.
20496
20497    We have to be careful in the presence of discriminators.
20498    E.g., for this line:
20499
20500      for (i = 0; i < 100000; i++);
20501
20502    clang can emit four line number entries for that one line,
20503    each with a different discriminator.
20504    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
20505
20506    However, we want gdb to coalesce all four entries into one.
20507    Otherwise the user could stepi into the middle of the line and
20508    gdb would get confused about whether the pc really was in the
20509    middle of the line.
20510
20511    Things are further complicated by the fact that two consecutive
20512    line number entries for the same line is a heuristic used by gcc
20513    to denote the end of the prologue.  So we can't just discard duplicate
20514    entries, we have to be selective about it.  The heuristic we use is
20515    that we only collapse consecutive entries for the same line if at least
20516    one of those entries has a non-zero discriminator.  PR 17276.
20517
20518    Note: Addresses in the line number state machine can never go backwards
20519    within one sequence, thus this coalescing is ok.  */
20520
20521 static int
20522 dwarf_record_line_p (unsigned int line, unsigned int last_line,
20523                      int line_has_non_zero_discriminator,
20524                      struct subfile *last_subfile)
20525 {
20526   if (get_current_subfile () != last_subfile)
20527     return 1;
20528   if (line != last_line)
20529     return 1;
20530   /* Same line for the same file that we've seen already.
20531      As a last check, for pr 17276, only record the line if the line
20532      has never had a non-zero discriminator.  */
20533   if (!line_has_non_zero_discriminator)
20534     return 1;
20535   return 0;
20536 }
20537
20538 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
20539    in the line table of subfile SUBFILE.  */
20540
20541 static void
20542 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
20543                      unsigned int line, CORE_ADDR address,
20544                      record_line_ftype p_record_line)
20545 {
20546   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
20547
20548   if (dwarf_line_debug)
20549     {
20550       fprintf_unfiltered (gdb_stdlog,
20551                           "Recording line %u, file %s, address %s\n",
20552                           line, lbasename (subfile->name),
20553                           paddress (gdbarch, address));
20554     }
20555
20556   (*p_record_line) (subfile, line, addr);
20557 }
20558
20559 /* Subroutine of dwarf_decode_lines_1 to simplify it.
20560    Mark the end of a set of line number records.
20561    The arguments are the same as for dwarf_record_line_1.
20562    If SUBFILE is NULL the request is ignored.  */
20563
20564 static void
20565 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
20566                    CORE_ADDR address, record_line_ftype p_record_line)
20567 {
20568   if (subfile == NULL)
20569     return;
20570
20571   if (dwarf_line_debug)
20572     {
20573       fprintf_unfiltered (gdb_stdlog,
20574                           "Finishing current line, file %s, address %s\n",
20575                           lbasename (subfile->name),
20576                           paddress (gdbarch, address));
20577     }
20578
20579   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
20580 }
20581
20582 void
20583 lnp_state_machine::record_line (bool end_sequence)
20584 {
20585   if (dwarf_line_debug)
20586     {
20587       fprintf_unfiltered (gdb_stdlog,
20588                           "Processing actual line %u: file %u,"
20589                           " address %s, is_stmt %u, discrim %u\n",
20590                           m_line, to_underlying (m_file),
20591                           paddress (m_gdbarch, m_address),
20592                           m_is_stmt, m_discriminator);
20593     }
20594
20595   file_entry *fe = current_file ();
20596
20597   if (fe == NULL)
20598     dwarf2_debug_line_missing_file_complaint ();
20599   /* For now we ignore lines not starting on an instruction boundary.
20600      But not when processing end_sequence for compatibility with the
20601      previous version of the code.  */
20602   else if (m_op_index == 0 || end_sequence)
20603     {
20604       fe->included_p = 1;
20605       if (m_record_lines_p && m_is_stmt)
20606         {
20607           if (m_last_subfile != get_current_subfile () || end_sequence)
20608             {
20609               dwarf_finish_line (m_gdbarch, m_last_subfile,
20610                                  m_address, m_record_line_callback);
20611             }
20612
20613           if (!end_sequence)
20614             {
20615               if (dwarf_record_line_p (m_line, m_last_line,
20616                                        m_line_has_non_zero_discriminator,
20617                                        m_last_subfile))
20618                 {
20619                   dwarf_record_line_1 (m_gdbarch, get_current_subfile (),
20620                                        m_line, m_address,
20621                                        m_record_line_callback);
20622                 }
20623               m_last_subfile = get_current_subfile ();
20624               m_last_line = m_line;
20625             }
20626         }
20627     }
20628 }
20629
20630 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
20631                                       bool record_lines_p)
20632 {
20633   m_gdbarch = arch;
20634   m_record_lines_p = record_lines_p;
20635   m_line_header = lh;
20636
20637   m_record_line_callback = ::record_line;
20638
20639   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
20640      was a line entry for it so that the backend has a chance to adjust it
20641      and also record it in case it needs it.  This is currently used by MIPS
20642      code, cf. `mips_adjust_dwarf2_line'.  */
20643   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
20644   m_is_stmt = lh->default_is_stmt;
20645   m_discriminator = 0;
20646 }
20647
20648 void
20649 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
20650                                        const gdb_byte *line_ptr,
20651                                        CORE_ADDR unrelocated_lowpc, CORE_ADDR address)
20652 {
20653   /* If ADDRESS < UNRELOCATED_LOWPC then it's not a usable value, it's outside
20654      the pc range of the CU.  However, we restrict the test to only ADDRESS
20655      values of zero to preserve GDB's previous behaviour which is to handle
20656      the specific case of a function being GC'd by the linker.  */
20657
20658   if (address == 0 && address < unrelocated_lowpc)
20659     {
20660       /* This line table is for a function which has been
20661          GCd by the linker.  Ignore it.  PR gdb/12528 */
20662
20663       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20664       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
20665
20666       complaint (_(".debug_line address at offset 0x%lx is 0 [in module %s]"),
20667                  line_offset, objfile_name (objfile));
20668       m_record_line_callback = noop_record_line;
20669       /* Note: record_line_callback is left as noop_record_line until
20670          we see DW_LNE_end_sequence.  */
20671     }
20672 }
20673
20674 /* Subroutine of dwarf_decode_lines to simplify it.
20675    Process the line number information in LH.
20676    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
20677    program in order to set included_p for every referenced header.  */
20678
20679 static void
20680 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
20681                       const int decode_for_pst_p, CORE_ADDR lowpc)
20682 {
20683   const gdb_byte *line_ptr, *extended_end;
20684   const gdb_byte *line_end;
20685   unsigned int bytes_read, extended_len;
20686   unsigned char op_code, extended_op;
20687   CORE_ADDR baseaddr;
20688   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20689   bfd *abfd = objfile->obfd;
20690   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20691   /* True if we're recording line info (as opposed to building partial
20692      symtabs and just interested in finding include files mentioned by
20693      the line number program).  */
20694   bool record_lines_p = !decode_for_pst_p;
20695
20696   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20697
20698   line_ptr = lh->statement_program_start;
20699   line_end = lh->statement_program_end;
20700
20701   /* Read the statement sequences until there's nothing left.  */
20702   while (line_ptr < line_end)
20703     {
20704       /* The DWARF line number program state machine.  Reset the state
20705          machine at the start of each sequence.  */
20706       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
20707       bool end_sequence = false;
20708
20709       if (record_lines_p)
20710         {
20711           /* Start a subfile for the current file of the state
20712              machine.  */
20713           const file_entry *fe = state_machine.current_file ();
20714
20715           if (fe != NULL)
20716             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
20717         }
20718
20719       /* Decode the table.  */
20720       while (line_ptr < line_end && !end_sequence)
20721         {
20722           op_code = read_1_byte (abfd, line_ptr);
20723           line_ptr += 1;
20724
20725           if (op_code >= lh->opcode_base)
20726             {
20727               /* Special opcode.  */
20728               state_machine.handle_special_opcode (op_code);
20729             }
20730           else switch (op_code)
20731             {
20732             case DW_LNS_extended_op:
20733               extended_len = read_unsigned_leb128 (abfd, line_ptr,
20734                                                    &bytes_read);
20735               line_ptr += bytes_read;
20736               extended_end = line_ptr + extended_len;
20737               extended_op = read_1_byte (abfd, line_ptr);
20738               line_ptr += 1;
20739               switch (extended_op)
20740                 {
20741                 case DW_LNE_end_sequence:
20742                   state_machine.handle_end_sequence ();
20743                   end_sequence = true;
20744                   break;
20745                 case DW_LNE_set_address:
20746                   {
20747                     CORE_ADDR address
20748                       = read_address (abfd, line_ptr, cu, &bytes_read);
20749                     line_ptr += bytes_read;
20750
20751                     state_machine.check_line_address (cu, line_ptr,
20752                                                       lowpc - baseaddr, address);
20753                     state_machine.handle_set_address (baseaddr, address);
20754                   }
20755                   break;
20756                 case DW_LNE_define_file:
20757                   {
20758                     const char *cur_file;
20759                     unsigned int mod_time, length;
20760                     dir_index dindex;
20761
20762                     cur_file = read_direct_string (abfd, line_ptr,
20763                                                    &bytes_read);
20764                     line_ptr += bytes_read;
20765                     dindex = (dir_index)
20766                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20767                     line_ptr += bytes_read;
20768                     mod_time =
20769                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20770                     line_ptr += bytes_read;
20771                     length =
20772                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20773                     line_ptr += bytes_read;
20774                     lh->add_file_name (cur_file, dindex, mod_time, length);
20775                   }
20776                   break;
20777                 case DW_LNE_set_discriminator:
20778                   {
20779                     /* The discriminator is not interesting to the
20780                        debugger; just ignore it.  We still need to
20781                        check its value though:
20782                        if there are consecutive entries for the same
20783                        (non-prologue) line we want to coalesce them.
20784                        PR 17276.  */
20785                     unsigned int discr
20786                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20787                     line_ptr += bytes_read;
20788
20789                     state_machine.handle_set_discriminator (discr);
20790                   }
20791                   break;
20792                 default:
20793                   complaint (_("mangled .debug_line section"));
20794                   return;
20795                 }
20796               /* Make sure that we parsed the extended op correctly.  If e.g.
20797                  we expected a different address size than the producer used,
20798                  we may have read the wrong number of bytes.  */
20799               if (line_ptr != extended_end)
20800                 {
20801                   complaint (_("mangled .debug_line section"));
20802                   return;
20803                 }
20804               break;
20805             case DW_LNS_copy:
20806               state_machine.handle_copy ();
20807               break;
20808             case DW_LNS_advance_pc:
20809               {
20810                 CORE_ADDR adjust
20811                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20812                 line_ptr += bytes_read;
20813
20814                 state_machine.handle_advance_pc (adjust);
20815               }
20816               break;
20817             case DW_LNS_advance_line:
20818               {
20819                 int line_delta
20820                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
20821                 line_ptr += bytes_read;
20822
20823                 state_machine.handle_advance_line (line_delta);
20824               }
20825               break;
20826             case DW_LNS_set_file:
20827               {
20828                 file_name_index file
20829                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
20830                                                             &bytes_read);
20831                 line_ptr += bytes_read;
20832
20833                 state_machine.handle_set_file (file);
20834               }
20835               break;
20836             case DW_LNS_set_column:
20837               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20838               line_ptr += bytes_read;
20839               break;
20840             case DW_LNS_negate_stmt:
20841               state_machine.handle_negate_stmt ();
20842               break;
20843             case DW_LNS_set_basic_block:
20844               break;
20845             /* Add to the address register of the state machine the
20846                address increment value corresponding to special opcode
20847                255.  I.e., this value is scaled by the minimum
20848                instruction length since special opcode 255 would have
20849                scaled the increment.  */
20850             case DW_LNS_const_add_pc:
20851               state_machine.handle_const_add_pc ();
20852               break;
20853             case DW_LNS_fixed_advance_pc:
20854               {
20855                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
20856                 line_ptr += 2;
20857
20858                 state_machine.handle_fixed_advance_pc (addr_adj);
20859               }
20860               break;
20861             default:
20862               {
20863                 /* Unknown standard opcode, ignore it.  */
20864                 int i;
20865
20866                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
20867                   {
20868                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
20869                     line_ptr += bytes_read;
20870                   }
20871               }
20872             }
20873         }
20874
20875       if (!end_sequence)
20876         dwarf2_debug_line_missing_end_sequence_complaint ();
20877
20878       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
20879          in which case we still finish recording the last line).  */
20880       state_machine.record_line (true);
20881     }
20882 }
20883
20884 /* Decode the Line Number Program (LNP) for the given line_header
20885    structure and CU.  The actual information extracted and the type
20886    of structures created from the LNP depends on the value of PST.
20887
20888    1. If PST is NULL, then this procedure uses the data from the program
20889       to create all necessary symbol tables, and their linetables.
20890
20891    2. If PST is not NULL, this procedure reads the program to determine
20892       the list of files included by the unit represented by PST, and
20893       builds all the associated partial symbol tables.
20894
20895    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
20896    It is used for relative paths in the line table.
20897    NOTE: When processing partial symtabs (pst != NULL),
20898    comp_dir == pst->dirname.
20899
20900    NOTE: It is important that psymtabs have the same file name (via strcmp)
20901    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
20902    symtab we don't use it in the name of the psymtabs we create.
20903    E.g. expand_line_sal requires this when finding psymtabs to expand.
20904    A good testcase for this is mb-inline.exp.
20905
20906    LOWPC is the lowest address in CU (or 0 if not known).
20907
20908    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
20909    for its PC<->lines mapping information.  Otherwise only the filename
20910    table is read in.  */
20911
20912 static void
20913 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
20914                     struct dwarf2_cu *cu, struct partial_symtab *pst,
20915                     CORE_ADDR lowpc, int decode_mapping)
20916 {
20917   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
20918   const int decode_for_pst_p = (pst != NULL);
20919
20920   if (decode_mapping)
20921     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
20922
20923   if (decode_for_pst_p)
20924     {
20925       int file_index;
20926
20927       /* Now that we're done scanning the Line Header Program, we can
20928          create the psymtab of each included file.  */
20929       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
20930         if (lh->file_names[file_index].included_p == 1)
20931           {
20932             gdb::unique_xmalloc_ptr<char> name_holder;
20933             const char *include_name =
20934               psymtab_include_file_name (lh, file_index, pst, comp_dir,
20935                                          &name_holder);
20936             if (include_name != NULL)
20937               dwarf2_create_include_psymtab (include_name, pst, objfile);
20938           }
20939     }
20940   else
20941     {
20942       /* Make sure a symtab is created for every file, even files
20943          which contain only variables (i.e. no code with associated
20944          line numbers).  */
20945       struct compunit_symtab *cust = buildsym_compunit_symtab ();
20946       int i;
20947
20948       for (i = 0; i < lh->file_names.size (); i++)
20949         {
20950           file_entry &fe = lh->file_names[i];
20951
20952           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
20953
20954           if (get_current_subfile ()->symtab == NULL)
20955             {
20956               get_current_subfile ()->symtab
20957                 = allocate_symtab (cust, get_current_subfile ()->name);
20958             }
20959           fe.symtab = get_current_subfile ()->symtab;
20960         }
20961     }
20962 }
20963
20964 /* Start a subfile for DWARF.  FILENAME is the name of the file and
20965    DIRNAME the name of the source directory which contains FILENAME
20966    or NULL if not known.
20967    This routine tries to keep line numbers from identical absolute and
20968    relative file names in a common subfile.
20969
20970    Using the `list' example from the GDB testsuite, which resides in
20971    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
20972    of /srcdir/list0.c yields the following debugging information for list0.c:
20973
20974    DW_AT_name:          /srcdir/list0.c
20975    DW_AT_comp_dir:      /compdir
20976    files.files[0].name: list0.h
20977    files.files[0].dir:  /srcdir
20978    files.files[1].name: list0.c
20979    files.files[1].dir:  /srcdir
20980
20981    The line number information for list0.c has to end up in a single
20982    subfile, so that `break /srcdir/list0.c:1' works as expected.
20983    start_subfile will ensure that this happens provided that we pass the
20984    concatenation of files.files[1].dir and files.files[1].name as the
20985    subfile's name.  */
20986
20987 static void
20988 dwarf2_start_subfile (const char *filename, const char *dirname)
20989 {
20990   char *copy = NULL;
20991
20992   /* In order not to lose the line information directory,
20993      we concatenate it to the filename when it makes sense.
20994      Note that the Dwarf3 standard says (speaking of filenames in line
20995      information): ``The directory index is ignored for file names
20996      that represent full path names''.  Thus ignoring dirname in the
20997      `else' branch below isn't an issue.  */
20998
20999   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
21000     {
21001       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
21002       filename = copy;
21003     }
21004
21005   start_subfile (filename);
21006
21007   if (copy != NULL)
21008     xfree (copy);
21009 }
21010
21011 /* Start a symtab for DWARF.
21012    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
21013
21014 static struct compunit_symtab *
21015 dwarf2_start_symtab (struct dwarf2_cu *cu,
21016                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
21017 {
21018   struct compunit_symtab *cust
21019     = start_symtab (cu->per_cu->dwarf2_per_objfile->objfile, name, comp_dir,
21020                     low_pc, cu->language);
21021
21022   record_debugformat ("DWARF 2");
21023   record_producer (cu->producer);
21024
21025   cu->processing_has_namespace_info = 0;
21026
21027   return cust;
21028 }
21029
21030 static void
21031 var_decode_location (struct attribute *attr, struct symbol *sym,
21032                      struct dwarf2_cu *cu)
21033 {
21034   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21035   struct comp_unit_head *cu_header = &cu->header;
21036
21037   /* NOTE drow/2003-01-30: There used to be a comment and some special
21038      code here to turn a symbol with DW_AT_external and a
21039      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
21040      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
21041      with some versions of binutils) where shared libraries could have
21042      relocations against symbols in their debug information - the
21043      minimal symbol would have the right address, but the debug info
21044      would not.  It's no longer necessary, because we will explicitly
21045      apply relocations when we read in the debug information now.  */
21046
21047   /* A DW_AT_location attribute with no contents indicates that a
21048      variable has been optimized away.  */
21049   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
21050     {
21051       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21052       return;
21053     }
21054
21055   /* Handle one degenerate form of location expression specially, to
21056      preserve GDB's previous behavior when section offsets are
21057      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
21058      then mark this symbol as LOC_STATIC.  */
21059
21060   if (attr_form_is_block (attr)
21061       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
21062            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
21063           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
21064               && (DW_BLOCK (attr)->size
21065                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
21066     {
21067       unsigned int dummy;
21068
21069       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
21070         SYMBOL_VALUE_ADDRESS (sym) =
21071           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
21072       else
21073         SYMBOL_VALUE_ADDRESS (sym) =
21074           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
21075       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
21076       fixup_symbol_section (sym, objfile);
21077       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
21078                                               SYMBOL_SECTION (sym));
21079       return;
21080     }
21081
21082   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
21083      expression evaluator, and use LOC_COMPUTED only when necessary
21084      (i.e. when the value of a register or memory location is
21085      referenced, or a thread-local block, etc.).  Then again, it might
21086      not be worthwhile.  I'm assuming that it isn't unless performance
21087      or memory numbers show me otherwise.  */
21088
21089   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
21090
21091   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
21092     cu->has_loclist = 1;
21093 }
21094
21095 /* Given a pointer to a DWARF information entry, figure out if we need
21096    to make a symbol table entry for it, and if so, create a new entry
21097    and return a pointer to it.
21098    If TYPE is NULL, determine symbol type from the die, otherwise
21099    used the passed type.
21100    If SPACE is not NULL, use it to hold the new symbol.  If it is
21101    NULL, allocate a new symbol on the objfile's obstack.  */
21102
21103 static struct symbol *
21104 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
21105             struct symbol *space)
21106 {
21107   struct dwarf2_per_objfile *dwarf2_per_objfile
21108     = cu->per_cu->dwarf2_per_objfile;
21109   struct objfile *objfile = dwarf2_per_objfile->objfile;
21110   struct gdbarch *gdbarch = get_objfile_arch (objfile);
21111   struct symbol *sym = NULL;
21112   const char *name;
21113   struct attribute *attr = NULL;
21114   struct attribute *attr2 = NULL;
21115   CORE_ADDR baseaddr;
21116   struct pending **list_to_add = NULL;
21117
21118   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
21119
21120   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
21121
21122   name = dwarf2_name (die, cu);
21123   if (name)
21124     {
21125       const char *linkagename;
21126       int suppress_add = 0;
21127
21128       if (space)
21129         sym = space;
21130       else
21131         sym = allocate_symbol (objfile);
21132       OBJSTAT (objfile, n_syms++);
21133
21134       /* Cache this symbol's name and the name's demangled form (if any).  */
21135       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
21136       linkagename = dwarf2_physname (name, die, cu);
21137       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
21138
21139       /* Fortran does not have mangling standard and the mangling does differ
21140          between gfortran, iFort etc.  */
21141       if (cu->language == language_fortran
21142           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
21143         symbol_set_demangled_name (&(sym->ginfo),
21144                                    dwarf2_full_name (name, die, cu),
21145                                    NULL);
21146
21147       /* Default assumptions.
21148          Use the passed type or decode it from the die.  */
21149       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21150       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
21151       if (type != NULL)
21152         SYMBOL_TYPE (sym) = type;
21153       else
21154         SYMBOL_TYPE (sym) = die_type (die, cu);
21155       attr = dwarf2_attr (die,
21156                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
21157                           cu);
21158       if (attr)
21159         {
21160           SYMBOL_LINE (sym) = DW_UNSND (attr);
21161         }
21162
21163       attr = dwarf2_attr (die,
21164                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
21165                           cu);
21166       if (attr)
21167         {
21168           file_name_index file_index = (file_name_index) DW_UNSND (attr);
21169           struct file_entry *fe;
21170
21171           if (cu->line_header != NULL)
21172             fe = cu->line_header->file_name_at (file_index);
21173           else
21174             fe = NULL;
21175
21176           if (fe == NULL)
21177             complaint (_("file index out of range"));
21178           else
21179             symbol_set_symtab (sym, fe->symtab);
21180         }
21181
21182       switch (die->tag)
21183         {
21184         case DW_TAG_label:
21185           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
21186           if (attr)
21187             {
21188               CORE_ADDR addr;
21189
21190               addr = attr_value_as_address (attr);
21191               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
21192               SYMBOL_VALUE_ADDRESS (sym) = addr;
21193             }
21194           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
21195           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
21196           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
21197           add_symbol_to_list (sym, cu->list_in_scope);
21198           break;
21199         case DW_TAG_subprogram:
21200           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21201              finish_block.  */
21202           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21203           attr2 = dwarf2_attr (die, DW_AT_external, cu);
21204           if ((attr2 && (DW_UNSND (attr2) != 0))
21205               || cu->language == language_ada)
21206             {
21207               /* Subprograms marked external are stored as a global symbol.
21208                  Ada subprograms, whether marked external or not, are always
21209                  stored as a global symbol, because we want to be able to
21210                  access them globally.  For instance, we want to be able
21211                  to break on a nested subprogram without having to
21212                  specify the context.  */
21213               list_to_add = &global_symbols;
21214             }
21215           else
21216             {
21217               list_to_add = cu->list_in_scope;
21218             }
21219           break;
21220         case DW_TAG_inlined_subroutine:
21221           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
21222              finish_block.  */
21223           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
21224           SYMBOL_INLINED (sym) = 1;
21225           list_to_add = cu->list_in_scope;
21226           break;
21227         case DW_TAG_template_value_param:
21228           suppress_add = 1;
21229           /* Fall through.  */
21230         case DW_TAG_constant:
21231         case DW_TAG_variable:
21232         case DW_TAG_member:
21233           /* Compilation with minimal debug info may result in
21234              variables with missing type entries.  Change the
21235              misleading `void' type to something sensible.  */
21236           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
21237             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
21238
21239           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21240           /* In the case of DW_TAG_member, we should only be called for
21241              static const members.  */
21242           if (die->tag == DW_TAG_member)
21243             {
21244               /* dwarf2_add_field uses die_is_declaration,
21245                  so we do the same.  */
21246               gdb_assert (die_is_declaration (die, cu));
21247               gdb_assert (attr);
21248             }
21249           if (attr)
21250             {
21251               dwarf2_const_value (attr, sym, cu);
21252               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21253               if (!suppress_add)
21254                 {
21255                   if (attr2 && (DW_UNSND (attr2) != 0))
21256                     list_to_add = &global_symbols;
21257                   else
21258                     list_to_add = cu->list_in_scope;
21259                 }
21260               break;
21261             }
21262           attr = dwarf2_attr (die, DW_AT_location, cu);
21263           if (attr)
21264             {
21265               var_decode_location (attr, sym, cu);
21266               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21267
21268               /* Fortran explicitly imports any global symbols to the local
21269                  scope by DW_TAG_common_block.  */
21270               if (cu->language == language_fortran && die->parent
21271                   && die->parent->tag == DW_TAG_common_block)
21272                 attr2 = NULL;
21273
21274               if (SYMBOL_CLASS (sym) == LOC_STATIC
21275                   && SYMBOL_VALUE_ADDRESS (sym) == 0
21276                   && !dwarf2_per_objfile->has_section_at_zero)
21277                 {
21278                   /* When a static variable is eliminated by the linker,
21279                      the corresponding debug information is not stripped
21280                      out, but the variable address is set to null;
21281                      do not add such variables into symbol table.  */
21282                 }
21283               else if (attr2 && (DW_UNSND (attr2) != 0))
21284                 {
21285                   /* Workaround gfortran PR debug/40040 - it uses
21286                      DW_AT_location for variables in -fPIC libraries which may
21287                      get overriden by other libraries/executable and get
21288                      a different address.  Resolve it by the minimal symbol
21289                      which may come from inferior's executable using copy
21290                      relocation.  Make this workaround only for gfortran as for
21291                      other compilers GDB cannot guess the minimal symbol
21292                      Fortran mangling kind.  */
21293                   if (cu->language == language_fortran && die->parent
21294                       && die->parent->tag == DW_TAG_module
21295                       && cu->producer
21296                       && startswith (cu->producer, "GNU Fortran"))
21297                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21298
21299                   /* A variable with DW_AT_external is never static,
21300                      but it may be block-scoped.  */
21301                   list_to_add = (cu->list_in_scope == &file_symbols
21302                                  ? &global_symbols : cu->list_in_scope);
21303                 }
21304               else
21305                 list_to_add = cu->list_in_scope;
21306             }
21307           else
21308             {
21309               /* We do not know the address of this symbol.
21310                  If it is an external symbol and we have type information
21311                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
21312                  The address of the variable will then be determined from
21313                  the minimal symbol table whenever the variable is
21314                  referenced.  */
21315               attr2 = dwarf2_attr (die, DW_AT_external, cu);
21316
21317               /* Fortran explicitly imports any global symbols to the local
21318                  scope by DW_TAG_common_block.  */
21319               if (cu->language == language_fortran && die->parent
21320                   && die->parent->tag == DW_TAG_common_block)
21321                 {
21322                   /* SYMBOL_CLASS doesn't matter here because
21323                      read_common_block is going to reset it.  */
21324                   if (!suppress_add)
21325                     list_to_add = cu->list_in_scope;
21326                 }
21327               else if (attr2 && (DW_UNSND (attr2) != 0)
21328                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
21329                 {
21330                   /* A variable with DW_AT_external is never static, but it
21331                      may be block-scoped.  */
21332                   list_to_add = (cu->list_in_scope == &file_symbols
21333                                  ? &global_symbols : cu->list_in_scope);
21334
21335                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
21336                 }
21337               else if (!die_is_declaration (die, cu))
21338                 {
21339                   /* Use the default LOC_OPTIMIZED_OUT class.  */
21340                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
21341                   if (!suppress_add)
21342                     list_to_add = cu->list_in_scope;
21343                 }
21344             }
21345           break;
21346         case DW_TAG_formal_parameter:
21347           {
21348             /* If we are inside a function, mark this as an argument.  If
21349                not, we might be looking at an argument to an inlined function
21350                when we do not have enough information to show inlined frames;
21351                pretend it's a local variable in that case so that the user can
21352                still see it.  */
21353             struct context_stack *curr = get_current_context_stack ();
21354             if (curr != nullptr && curr->name != nullptr)
21355               SYMBOL_IS_ARGUMENT (sym) = 1;
21356             attr = dwarf2_attr (die, DW_AT_location, cu);
21357             if (attr)
21358               {
21359                 var_decode_location (attr, sym, cu);
21360               }
21361             attr = dwarf2_attr (die, DW_AT_const_value, cu);
21362             if (attr)
21363               {
21364                 dwarf2_const_value (attr, sym, cu);
21365               }
21366
21367             list_to_add = cu->list_in_scope;
21368           }
21369           break;
21370         case DW_TAG_unspecified_parameters:
21371           /* From varargs functions; gdb doesn't seem to have any
21372              interest in this information, so just ignore it for now.
21373              (FIXME?) */
21374           break;
21375         case DW_TAG_template_type_param:
21376           suppress_add = 1;
21377           /* Fall through.  */
21378         case DW_TAG_class_type:
21379         case DW_TAG_interface_type:
21380         case DW_TAG_structure_type:
21381         case DW_TAG_union_type:
21382         case DW_TAG_set_type:
21383         case DW_TAG_enumeration_type:
21384           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21385           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
21386
21387           {
21388             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
21389                really ever be static objects: otherwise, if you try
21390                to, say, break of a class's method and you're in a file
21391                which doesn't mention that class, it won't work unless
21392                the check for all static symbols in lookup_symbol_aux
21393                saves you.  See the OtherFileClass tests in
21394                gdb.c++/namespace.exp.  */
21395
21396             if (!suppress_add)
21397               {
21398                 list_to_add = (cu->list_in_scope == &file_symbols
21399                                && cu->language == language_cplus
21400                                ? &global_symbols : cu->list_in_scope);
21401
21402                 /* The semantics of C++ state that "struct foo {
21403                    ... }" also defines a typedef for "foo".  */
21404                 if (cu->language == language_cplus
21405                     || cu->language == language_ada
21406                     || cu->language == language_d
21407                     || cu->language == language_rust)
21408                   {
21409                     /* The symbol's name is already allocated along
21410                        with this objfile, so we don't need to
21411                        duplicate it for the type.  */
21412                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
21413                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
21414                   }
21415               }
21416           }
21417           break;
21418         case DW_TAG_typedef:
21419           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21420           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21421           list_to_add = cu->list_in_scope;
21422           break;
21423         case DW_TAG_base_type:
21424         case DW_TAG_subrange_type:
21425           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21426           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
21427           list_to_add = cu->list_in_scope;
21428           break;
21429         case DW_TAG_enumerator:
21430           attr = dwarf2_attr (die, DW_AT_const_value, cu);
21431           if (attr)
21432             {
21433               dwarf2_const_value (attr, sym, cu);
21434             }
21435           {
21436             /* NOTE: carlton/2003-11-10: See comment above in the
21437                DW_TAG_class_type, etc. block.  */
21438
21439             list_to_add = (cu->list_in_scope == &file_symbols
21440                            && cu->language == language_cplus
21441                            ? &global_symbols : cu->list_in_scope);
21442           }
21443           break;
21444         case DW_TAG_imported_declaration:
21445         case DW_TAG_namespace:
21446           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21447           list_to_add = &global_symbols;
21448           break;
21449         case DW_TAG_module:
21450           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
21451           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
21452           list_to_add = &global_symbols;
21453           break;
21454         case DW_TAG_common_block:
21455           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
21456           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
21457           add_symbol_to_list (sym, cu->list_in_scope);
21458           break;
21459         default:
21460           /* Not a tag we recognize.  Hopefully we aren't processing
21461              trash data, but since we must specifically ignore things
21462              we don't recognize, there is nothing else we should do at
21463              this point.  */
21464           complaint (_("unsupported tag: '%s'"),
21465                      dwarf_tag_name (die->tag));
21466           break;
21467         }
21468
21469       if (suppress_add)
21470         {
21471           sym->hash_next = objfile->template_symbols;
21472           objfile->template_symbols = sym;
21473           list_to_add = NULL;
21474         }
21475
21476       if (list_to_add != NULL)
21477         add_symbol_to_list (sym, list_to_add);
21478
21479       /* For the benefit of old versions of GCC, check for anonymous
21480          namespaces based on the demangled name.  */
21481       if (!cu->processing_has_namespace_info
21482           && cu->language == language_cplus)
21483         cp_scan_for_anonymous_namespaces (sym, objfile);
21484     }
21485   return (sym);
21486 }
21487
21488 /* Given an attr with a DW_FORM_dataN value in host byte order,
21489    zero-extend it as appropriate for the symbol's type.  The DWARF
21490    standard (v4) is not entirely clear about the meaning of using
21491    DW_FORM_dataN for a constant with a signed type, where the type is
21492    wider than the data.  The conclusion of a discussion on the DWARF
21493    list was that this is unspecified.  We choose to always zero-extend
21494    because that is the interpretation long in use by GCC.  */
21495
21496 static gdb_byte *
21497 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
21498                          struct dwarf2_cu *cu, LONGEST *value, int bits)
21499 {
21500   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21501   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
21502                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
21503   LONGEST l = DW_UNSND (attr);
21504
21505   if (bits < sizeof (*value) * 8)
21506     {
21507       l &= ((LONGEST) 1 << bits) - 1;
21508       *value = l;
21509     }
21510   else if (bits == sizeof (*value) * 8)
21511     *value = l;
21512   else
21513     {
21514       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
21515       store_unsigned_integer (bytes, bits / 8, byte_order, l);
21516       return bytes;
21517     }
21518
21519   return NULL;
21520 }
21521
21522 /* Read a constant value from an attribute.  Either set *VALUE, or if
21523    the value does not fit in *VALUE, set *BYTES - either already
21524    allocated on the objfile obstack, or newly allocated on OBSTACK,
21525    or, set *BATON, if we translated the constant to a location
21526    expression.  */
21527
21528 static void
21529 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
21530                          const char *name, struct obstack *obstack,
21531                          struct dwarf2_cu *cu,
21532                          LONGEST *value, const gdb_byte **bytes,
21533                          struct dwarf2_locexpr_baton **baton)
21534 {
21535   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21536   struct comp_unit_head *cu_header = &cu->header;
21537   struct dwarf_block *blk;
21538   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
21539                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21540
21541   *value = 0;
21542   *bytes = NULL;
21543   *baton = NULL;
21544
21545   switch (attr->form)
21546     {
21547     case DW_FORM_addr:
21548     case DW_FORM_GNU_addr_index:
21549       {
21550         gdb_byte *data;
21551
21552         if (TYPE_LENGTH (type) != cu_header->addr_size)
21553           dwarf2_const_value_length_mismatch_complaint (name,
21554                                                         cu_header->addr_size,
21555                                                         TYPE_LENGTH (type));
21556         /* Symbols of this form are reasonably rare, so we just
21557            piggyback on the existing location code rather than writing
21558            a new implementation of symbol_computed_ops.  */
21559         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
21560         (*baton)->per_cu = cu->per_cu;
21561         gdb_assert ((*baton)->per_cu);
21562
21563         (*baton)->size = 2 + cu_header->addr_size;
21564         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
21565         (*baton)->data = data;
21566
21567         data[0] = DW_OP_addr;
21568         store_unsigned_integer (&data[1], cu_header->addr_size,
21569                                 byte_order, DW_ADDR (attr));
21570         data[cu_header->addr_size + 1] = DW_OP_stack_value;
21571       }
21572       break;
21573     case DW_FORM_string:
21574     case DW_FORM_strp:
21575     case DW_FORM_GNU_str_index:
21576     case DW_FORM_GNU_strp_alt:
21577       /* DW_STRING is already allocated on the objfile obstack, point
21578          directly to it.  */
21579       *bytes = (const gdb_byte *) DW_STRING (attr);
21580       break;
21581     case DW_FORM_block1:
21582     case DW_FORM_block2:
21583     case DW_FORM_block4:
21584     case DW_FORM_block:
21585     case DW_FORM_exprloc:
21586     case DW_FORM_data16:
21587       blk = DW_BLOCK (attr);
21588       if (TYPE_LENGTH (type) != blk->size)
21589         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
21590                                                       TYPE_LENGTH (type));
21591       *bytes = blk->data;
21592       break;
21593
21594       /* The DW_AT_const_value attributes are supposed to carry the
21595          symbol's value "represented as it would be on the target
21596          architecture."  By the time we get here, it's already been
21597          converted to host endianness, so we just need to sign- or
21598          zero-extend it as appropriate.  */
21599     case DW_FORM_data1:
21600       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
21601       break;
21602     case DW_FORM_data2:
21603       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
21604       break;
21605     case DW_FORM_data4:
21606       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
21607       break;
21608     case DW_FORM_data8:
21609       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
21610       break;
21611
21612     case DW_FORM_sdata:
21613     case DW_FORM_implicit_const:
21614       *value = DW_SND (attr);
21615       break;
21616
21617     case DW_FORM_udata:
21618       *value = DW_UNSND (attr);
21619       break;
21620
21621     default:
21622       complaint (_("unsupported const value attribute form: '%s'"),
21623                  dwarf_form_name (attr->form));
21624       *value = 0;
21625       break;
21626     }
21627 }
21628
21629
21630 /* Copy constant value from an attribute to a symbol.  */
21631
21632 static void
21633 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
21634                     struct dwarf2_cu *cu)
21635 {
21636   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21637   LONGEST value;
21638   const gdb_byte *bytes;
21639   struct dwarf2_locexpr_baton *baton;
21640
21641   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
21642                            SYMBOL_PRINT_NAME (sym),
21643                            &objfile->objfile_obstack, cu,
21644                            &value, &bytes, &baton);
21645
21646   if (baton != NULL)
21647     {
21648       SYMBOL_LOCATION_BATON (sym) = baton;
21649       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
21650     }
21651   else if (bytes != NULL)
21652      {
21653       SYMBOL_VALUE_BYTES (sym) = bytes;
21654       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
21655     }
21656   else
21657     {
21658       SYMBOL_VALUE (sym) = value;
21659       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
21660     }
21661 }
21662
21663 /* Return the type of the die in question using its DW_AT_type attribute.  */
21664
21665 static struct type *
21666 die_type (struct die_info *die, struct dwarf2_cu *cu)
21667 {
21668   struct attribute *type_attr;
21669
21670   type_attr = dwarf2_attr (die, DW_AT_type, cu);
21671   if (!type_attr)
21672     {
21673       struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21674       /* A missing DW_AT_type represents a void type.  */
21675       return objfile_type (objfile)->builtin_void;
21676     }
21677
21678   return lookup_die_type (die, type_attr, cu);
21679 }
21680
21681 /* True iff CU's producer generates GNAT Ada auxiliary information
21682    that allows to find parallel types through that information instead
21683    of having to do expensive parallel lookups by type name.  */
21684
21685 static int
21686 need_gnat_info (struct dwarf2_cu *cu)
21687 {
21688   /* Assume that the Ada compiler was GNAT, which always produces
21689      the auxiliary information.  */
21690   return (cu->language == language_ada);
21691 }
21692
21693 /* Return the auxiliary type of the die in question using its
21694    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
21695    attribute is not present.  */
21696
21697 static struct type *
21698 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
21699 {
21700   struct attribute *type_attr;
21701
21702   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
21703   if (!type_attr)
21704     return NULL;
21705
21706   return lookup_die_type (die, type_attr, cu);
21707 }
21708
21709 /* If DIE has a descriptive_type attribute, then set the TYPE's
21710    descriptive type accordingly.  */
21711
21712 static void
21713 set_descriptive_type (struct type *type, struct die_info *die,
21714                       struct dwarf2_cu *cu)
21715 {
21716   struct type *descriptive_type = die_descriptive_type (die, cu);
21717
21718   if (descriptive_type)
21719     {
21720       ALLOCATE_GNAT_AUX_TYPE (type);
21721       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
21722     }
21723 }
21724
21725 /* Return the containing type of the die in question using its
21726    DW_AT_containing_type attribute.  */
21727
21728 static struct type *
21729 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
21730 {
21731   struct attribute *type_attr;
21732   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21733
21734   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
21735   if (!type_attr)
21736     error (_("Dwarf Error: Problem turning containing type into gdb type "
21737              "[in module %s]"), objfile_name (objfile));
21738
21739   return lookup_die_type (die, type_attr, cu);
21740 }
21741
21742 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
21743
21744 static struct type *
21745 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
21746 {
21747   struct dwarf2_per_objfile *dwarf2_per_objfile
21748     = cu->per_cu->dwarf2_per_objfile;
21749   struct objfile *objfile = dwarf2_per_objfile->objfile;
21750   char *message, *saved;
21751
21752   message = xstrprintf (_("<unknown type in %s, CU %s, DIE %s>"),
21753                         objfile_name (objfile),
21754                         sect_offset_str (cu->header.sect_off),
21755                         sect_offset_str (die->sect_off));
21756   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
21757                                   message, strlen (message));
21758   xfree (message);
21759
21760   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
21761 }
21762
21763 /* Look up the type of DIE in CU using its type attribute ATTR.
21764    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
21765    DW_AT_containing_type.
21766    If there is no type substitute an error marker.  */
21767
21768 static struct type *
21769 lookup_die_type (struct die_info *die, const struct attribute *attr,
21770                  struct dwarf2_cu *cu)
21771 {
21772   struct dwarf2_per_objfile *dwarf2_per_objfile
21773     = cu->per_cu->dwarf2_per_objfile;
21774   struct objfile *objfile = dwarf2_per_objfile->objfile;
21775   struct type *this_type;
21776
21777   gdb_assert (attr->name == DW_AT_type
21778               || attr->name == DW_AT_GNAT_descriptive_type
21779               || attr->name == DW_AT_containing_type);
21780
21781   /* First see if we have it cached.  */
21782
21783   if (attr->form == DW_FORM_GNU_ref_alt)
21784     {
21785       struct dwarf2_per_cu_data *per_cu;
21786       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21787
21788       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1,
21789                                                  dwarf2_per_objfile);
21790       this_type = get_die_type_at_offset (sect_off, per_cu);
21791     }
21792   else if (attr_form_is_ref (attr))
21793     {
21794       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21795
21796       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
21797     }
21798   else if (attr->form == DW_FORM_ref_sig8)
21799     {
21800       ULONGEST signature = DW_SIGNATURE (attr);
21801
21802       return get_signatured_type (die, signature, cu);
21803     }
21804   else
21805     {
21806       complaint (_("Dwarf Error: Bad type attribute %s in DIE"
21807                    " at %s [in module %s]"),
21808                  dwarf_attr_name (attr->name), sect_offset_str (die->sect_off),
21809                  objfile_name (objfile));
21810       return build_error_marker_type (cu, die);
21811     }
21812
21813   /* If not cached we need to read it in.  */
21814
21815   if (this_type == NULL)
21816     {
21817       struct die_info *type_die = NULL;
21818       struct dwarf2_cu *type_cu = cu;
21819
21820       if (attr_form_is_ref (attr))
21821         type_die = follow_die_ref (die, attr, &type_cu);
21822       if (type_die == NULL)
21823         return build_error_marker_type (cu, die);
21824       /* If we find the type now, it's probably because the type came
21825          from an inter-CU reference and the type's CU got expanded before
21826          ours.  */
21827       this_type = read_type_die (type_die, type_cu);
21828     }
21829
21830   /* If we still don't have a type use an error marker.  */
21831
21832   if (this_type == NULL)
21833     return build_error_marker_type (cu, die);
21834
21835   return this_type;
21836 }
21837
21838 /* Return the type in DIE, CU.
21839    Returns NULL for invalid types.
21840
21841    This first does a lookup in die_type_hash,
21842    and only reads the die in if necessary.
21843
21844    NOTE: This can be called when reading in partial or full symbols.  */
21845
21846 static struct type *
21847 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
21848 {
21849   struct type *this_type;
21850
21851   this_type = get_die_type (die, cu);
21852   if (this_type)
21853     return this_type;
21854
21855   return read_type_die_1 (die, cu);
21856 }
21857
21858 /* Read the type in DIE, CU.
21859    Returns NULL for invalid types.  */
21860
21861 static struct type *
21862 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
21863 {
21864   struct type *this_type = NULL;
21865
21866   switch (die->tag)
21867     {
21868     case DW_TAG_class_type:
21869     case DW_TAG_interface_type:
21870     case DW_TAG_structure_type:
21871     case DW_TAG_union_type:
21872       this_type = read_structure_type (die, cu);
21873       break;
21874     case DW_TAG_enumeration_type:
21875       this_type = read_enumeration_type (die, cu);
21876       break;
21877     case DW_TAG_subprogram:
21878     case DW_TAG_subroutine_type:
21879     case DW_TAG_inlined_subroutine:
21880       this_type = read_subroutine_type (die, cu);
21881       break;
21882     case DW_TAG_array_type:
21883       this_type = read_array_type (die, cu);
21884       break;
21885     case DW_TAG_set_type:
21886       this_type = read_set_type (die, cu);
21887       break;
21888     case DW_TAG_pointer_type:
21889       this_type = read_tag_pointer_type (die, cu);
21890       break;
21891     case DW_TAG_ptr_to_member_type:
21892       this_type = read_tag_ptr_to_member_type (die, cu);
21893       break;
21894     case DW_TAG_reference_type:
21895       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
21896       break;
21897     case DW_TAG_rvalue_reference_type:
21898       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
21899       break;
21900     case DW_TAG_const_type:
21901       this_type = read_tag_const_type (die, cu);
21902       break;
21903     case DW_TAG_volatile_type:
21904       this_type = read_tag_volatile_type (die, cu);
21905       break;
21906     case DW_TAG_restrict_type:
21907       this_type = read_tag_restrict_type (die, cu);
21908       break;
21909     case DW_TAG_string_type:
21910       this_type = read_tag_string_type (die, cu);
21911       break;
21912     case DW_TAG_typedef:
21913       this_type = read_typedef (die, cu);
21914       break;
21915     case DW_TAG_subrange_type:
21916       this_type = read_subrange_type (die, cu);
21917       break;
21918     case DW_TAG_base_type:
21919       this_type = read_base_type (die, cu);
21920       break;
21921     case DW_TAG_unspecified_type:
21922       this_type = read_unspecified_type (die, cu);
21923       break;
21924     case DW_TAG_namespace:
21925       this_type = read_namespace_type (die, cu);
21926       break;
21927     case DW_TAG_module:
21928       this_type = read_module_type (die, cu);
21929       break;
21930     case DW_TAG_atomic_type:
21931       this_type = read_tag_atomic_type (die, cu);
21932       break;
21933     default:
21934       complaint (_("unexpected tag in read_type_die: '%s'"),
21935                  dwarf_tag_name (die->tag));
21936       break;
21937     }
21938
21939   return this_type;
21940 }
21941
21942 /* See if we can figure out if the class lives in a namespace.  We do
21943    this by looking for a member function; its demangled name will
21944    contain namespace info, if there is any.
21945    Return the computed name or NULL.
21946    Space for the result is allocated on the objfile's obstack.
21947    This is the full-die version of guess_partial_die_structure_name.
21948    In this case we know DIE has no useful parent.  */
21949
21950 static char *
21951 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
21952 {
21953   struct die_info *spec_die;
21954   struct dwarf2_cu *spec_cu;
21955   struct die_info *child;
21956   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
21957
21958   spec_cu = cu;
21959   spec_die = die_specification (die, &spec_cu);
21960   if (spec_die != NULL)
21961     {
21962       die = spec_die;
21963       cu = spec_cu;
21964     }
21965
21966   for (child = die->child;
21967        child != NULL;
21968        child = child->sibling)
21969     {
21970       if (child->tag == DW_TAG_subprogram)
21971         {
21972           const char *linkage_name = dw2_linkage_name (child, cu);
21973
21974           if (linkage_name != NULL)
21975             {
21976               char *actual_name
21977                 = language_class_name_from_physname (cu->language_defn,
21978                                                      linkage_name);
21979               char *name = NULL;
21980
21981               if (actual_name != NULL)
21982                 {
21983                   const char *die_name = dwarf2_name (die, cu);
21984
21985                   if (die_name != NULL
21986                       && strcmp (die_name, actual_name) != 0)
21987                     {
21988                       /* Strip off the class name from the full name.
21989                          We want the prefix.  */
21990                       int die_name_len = strlen (die_name);
21991                       int actual_name_len = strlen (actual_name);
21992
21993                       /* Test for '::' as a sanity check.  */
21994                       if (actual_name_len > die_name_len + 2
21995                           && actual_name[actual_name_len
21996                                          - die_name_len - 1] == ':')
21997                         name = (char *) obstack_copy0 (
21998                           &objfile->per_bfd->storage_obstack,
21999                           actual_name, actual_name_len - die_name_len - 2);
22000                     }
22001                 }
22002               xfree (actual_name);
22003               return name;
22004             }
22005         }
22006     }
22007
22008   return NULL;
22009 }
22010
22011 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
22012    prefix part in such case.  See
22013    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22014
22015 static const char *
22016 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
22017 {
22018   struct attribute *attr;
22019   const char *base;
22020
22021   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
22022       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
22023     return NULL;
22024
22025   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
22026     return NULL;
22027
22028   attr = dw2_linkage_name_attr (die, cu);
22029   if (attr == NULL || DW_STRING (attr) == NULL)
22030     return NULL;
22031
22032   /* dwarf2_name had to be already called.  */
22033   gdb_assert (DW_STRING_IS_CANONICAL (attr));
22034
22035   /* Strip the base name, keep any leading namespaces/classes.  */
22036   base = strrchr (DW_STRING (attr), ':');
22037   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
22038     return "";
22039
22040   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22041   return (char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
22042                                  DW_STRING (attr),
22043                                  &base[-1] - DW_STRING (attr));
22044 }
22045
22046 /* Return the name of the namespace/class that DIE is defined within,
22047    or "" if we can't tell.  The caller should not xfree the result.
22048
22049    For example, if we're within the method foo() in the following
22050    code:
22051
22052    namespace N {
22053      class C {
22054        void foo () {
22055        }
22056      };
22057    }
22058
22059    then determine_prefix on foo's die will return "N::C".  */
22060
22061 static const char *
22062 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
22063 {
22064   struct dwarf2_per_objfile *dwarf2_per_objfile
22065     = cu->per_cu->dwarf2_per_objfile;
22066   struct die_info *parent, *spec_die;
22067   struct dwarf2_cu *spec_cu;
22068   struct type *parent_type;
22069   const char *retval;
22070
22071   if (cu->language != language_cplus
22072       && cu->language != language_fortran && cu->language != language_d
22073       && cu->language != language_rust)
22074     return "";
22075
22076   retval = anonymous_struct_prefix (die, cu);
22077   if (retval)
22078     return retval;
22079
22080   /* We have to be careful in the presence of DW_AT_specification.
22081      For example, with GCC 3.4, given the code
22082
22083      namespace N {
22084        void foo() {
22085          // Definition of N::foo.
22086        }
22087      }
22088
22089      then we'll have a tree of DIEs like this:
22090
22091      1: DW_TAG_compile_unit
22092        2: DW_TAG_namespace        // N
22093          3: DW_TAG_subprogram     // declaration of N::foo
22094        4: DW_TAG_subprogram       // definition of N::foo
22095             DW_AT_specification   // refers to die #3
22096
22097      Thus, when processing die #4, we have to pretend that we're in
22098      the context of its DW_AT_specification, namely the contex of die
22099      #3.  */
22100   spec_cu = cu;
22101   spec_die = die_specification (die, &spec_cu);
22102   if (spec_die == NULL)
22103     parent = die->parent;
22104   else
22105     {
22106       parent = spec_die->parent;
22107       cu = spec_cu;
22108     }
22109
22110   if (parent == NULL)
22111     return "";
22112   else if (parent->building_fullname)
22113     {
22114       const char *name;
22115       const char *parent_name;
22116
22117       /* It has been seen on RealView 2.2 built binaries,
22118          DW_TAG_template_type_param types actually _defined_ as
22119          children of the parent class:
22120
22121          enum E {};
22122          template class <class Enum> Class{};
22123          Class<enum E> class_e;
22124
22125          1: DW_TAG_class_type (Class)
22126            2: DW_TAG_enumeration_type (E)
22127              3: DW_TAG_enumerator (enum1:0)
22128              3: DW_TAG_enumerator (enum2:1)
22129              ...
22130            2: DW_TAG_template_type_param
22131               DW_AT_type  DW_FORM_ref_udata (E)
22132
22133          Besides being broken debug info, it can put GDB into an
22134          infinite loop.  Consider:
22135
22136          When we're building the full name for Class<E>, we'll start
22137          at Class, and go look over its template type parameters,
22138          finding E.  We'll then try to build the full name of E, and
22139          reach here.  We're now trying to build the full name of E,
22140          and look over the parent DIE for containing scope.  In the
22141          broken case, if we followed the parent DIE of E, we'd again
22142          find Class, and once again go look at its template type
22143          arguments, etc., etc.  Simply don't consider such parent die
22144          as source-level parent of this die (it can't be, the language
22145          doesn't allow it), and break the loop here.  */
22146       name = dwarf2_name (die, cu);
22147       parent_name = dwarf2_name (parent, cu);
22148       complaint (_("template param type '%s' defined within parent '%s'"),
22149                  name ? name : "<unknown>",
22150                  parent_name ? parent_name : "<unknown>");
22151       return "";
22152     }
22153   else
22154     switch (parent->tag)
22155       {
22156       case DW_TAG_namespace:
22157         parent_type = read_type_die (parent, cu);
22158         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
22159            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
22160            Work around this problem here.  */
22161         if (cu->language == language_cplus
22162             && strcmp (TYPE_NAME (parent_type), "::") == 0)
22163           return "";
22164         /* We give a name to even anonymous namespaces.  */
22165         return TYPE_NAME (parent_type);
22166       case DW_TAG_class_type:
22167       case DW_TAG_interface_type:
22168       case DW_TAG_structure_type:
22169       case DW_TAG_union_type:
22170       case DW_TAG_module:
22171         parent_type = read_type_die (parent, cu);
22172         if (TYPE_NAME (parent_type) != NULL)
22173           return TYPE_NAME (parent_type);
22174         else
22175           /* An anonymous structure is only allowed non-static data
22176              members; no typedefs, no member functions, et cetera.
22177              So it does not need a prefix.  */
22178           return "";
22179       case DW_TAG_compile_unit:
22180       case DW_TAG_partial_unit:
22181         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
22182         if (cu->language == language_cplus
22183             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
22184             && die->child != NULL
22185             && (die->tag == DW_TAG_class_type
22186                 || die->tag == DW_TAG_structure_type
22187                 || die->tag == DW_TAG_union_type))
22188           {
22189             char *name = guess_full_die_structure_name (die, cu);
22190             if (name != NULL)
22191               return name;
22192           }
22193         return "";
22194       case DW_TAG_enumeration_type:
22195         parent_type = read_type_die (parent, cu);
22196         if (TYPE_DECLARED_CLASS (parent_type))
22197           {
22198             if (TYPE_NAME (parent_type) != NULL)
22199               return TYPE_NAME (parent_type);
22200             return "";
22201           }
22202         /* Fall through.  */
22203       default:
22204         return determine_prefix (parent, cu);
22205       }
22206 }
22207
22208 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
22209    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
22210    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
22211    an obconcat, otherwise allocate storage for the result.  The CU argument is
22212    used to determine the language and hence, the appropriate separator.  */
22213
22214 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
22215
22216 static char *
22217 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
22218                  int physname, struct dwarf2_cu *cu)
22219 {
22220   const char *lead = "";
22221   const char *sep;
22222
22223   if (suffix == NULL || suffix[0] == '\0'
22224       || prefix == NULL || prefix[0] == '\0')
22225     sep = "";
22226   else if (cu->language == language_d)
22227     {
22228       /* For D, the 'main' function could be defined in any module, but it
22229          should never be prefixed.  */
22230       if (strcmp (suffix, "D main") == 0)
22231         {
22232           prefix = "";
22233           sep = "";
22234         }
22235       else
22236         sep = ".";
22237     }
22238   else if (cu->language == language_fortran && physname)
22239     {
22240       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
22241          DW_AT_MIPS_linkage_name is preferred and used instead.  */
22242
22243       lead = "__";
22244       sep = "_MOD_";
22245     }
22246   else
22247     sep = "::";
22248
22249   if (prefix == NULL)
22250     prefix = "";
22251   if (suffix == NULL)
22252     suffix = "";
22253
22254   if (obs == NULL)
22255     {
22256       char *retval
22257         = ((char *)
22258            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
22259
22260       strcpy (retval, lead);
22261       strcat (retval, prefix);
22262       strcat (retval, sep);
22263       strcat (retval, suffix);
22264       return retval;
22265     }
22266   else
22267     {
22268       /* We have an obstack.  */
22269       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
22270     }
22271 }
22272
22273 /* Return sibling of die, NULL if no sibling.  */
22274
22275 static struct die_info *
22276 sibling_die (struct die_info *die)
22277 {
22278   return die->sibling;
22279 }
22280
22281 /* Get name of a die, return NULL if not found.  */
22282
22283 static const char *
22284 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
22285                           struct obstack *obstack)
22286 {
22287   if (name && cu->language == language_cplus)
22288     {
22289       std::string canon_name = cp_canonicalize_string (name);
22290
22291       if (!canon_name.empty ())
22292         {
22293           if (canon_name != name)
22294             name = (const char *) obstack_copy0 (obstack,
22295                                                  canon_name.c_str (),
22296                                                  canon_name.length ());
22297         }
22298     }
22299
22300   return name;
22301 }
22302
22303 /* Get name of a die, return NULL if not found.
22304    Anonymous namespaces are converted to their magic string.  */
22305
22306 static const char *
22307 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
22308 {
22309   struct attribute *attr;
22310   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
22311
22312   attr = dwarf2_attr (die, DW_AT_name, cu);
22313   if ((!attr || !DW_STRING (attr))
22314       && die->tag != DW_TAG_namespace
22315       && die->tag != DW_TAG_class_type
22316       && die->tag != DW_TAG_interface_type
22317       && die->tag != DW_TAG_structure_type
22318       && die->tag != DW_TAG_union_type)
22319     return NULL;
22320
22321   switch (die->tag)
22322     {
22323     case DW_TAG_compile_unit:
22324     case DW_TAG_partial_unit:
22325       /* Compilation units have a DW_AT_name that is a filename, not
22326          a source language identifier.  */
22327     case DW_TAG_enumeration_type:
22328     case DW_TAG_enumerator:
22329       /* These tags always have simple identifiers already; no need
22330          to canonicalize them.  */
22331       return DW_STRING (attr);
22332
22333     case DW_TAG_namespace:
22334       if (attr != NULL && DW_STRING (attr) != NULL)
22335         return DW_STRING (attr);
22336       return CP_ANONYMOUS_NAMESPACE_STR;
22337
22338     case DW_TAG_class_type:
22339     case DW_TAG_interface_type:
22340     case DW_TAG_structure_type:
22341     case DW_TAG_union_type:
22342       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
22343          structures or unions.  These were of the form "._%d" in GCC 4.1,
22344          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
22345          and GCC 4.4.  We work around this problem by ignoring these.  */
22346       if (attr && DW_STRING (attr)
22347           && (startswith (DW_STRING (attr), "._")
22348               || startswith (DW_STRING (attr), "<anonymous")))
22349         return NULL;
22350
22351       /* GCC might emit a nameless typedef that has a linkage name.  See
22352          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
22353       if (!attr || DW_STRING (attr) == NULL)
22354         {
22355           char *demangled = NULL;
22356
22357           attr = dw2_linkage_name_attr (die, cu);
22358           if (attr == NULL || DW_STRING (attr) == NULL)
22359             return NULL;
22360
22361           /* Avoid demangling DW_STRING (attr) the second time on a second
22362              call for the same DIE.  */
22363           if (!DW_STRING_IS_CANONICAL (attr))
22364             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
22365
22366           if (demangled)
22367             {
22368               const char *base;
22369
22370               /* FIXME: we already did this for the partial symbol... */
22371               DW_STRING (attr)
22372                 = ((const char *)
22373                    obstack_copy0 (&objfile->per_bfd->storage_obstack,
22374                                   demangled, strlen (demangled)));
22375               DW_STRING_IS_CANONICAL (attr) = 1;
22376               xfree (demangled);
22377
22378               /* Strip any leading namespaces/classes, keep only the base name.
22379                  DW_AT_name for named DIEs does not contain the prefixes.  */
22380               base = strrchr (DW_STRING (attr), ':');
22381               if (base && base > DW_STRING (attr) && base[-1] == ':')
22382                 return &base[1];
22383               else
22384                 return DW_STRING (attr);
22385             }
22386         }
22387       break;
22388
22389     default:
22390       break;
22391     }
22392
22393   if (!DW_STRING_IS_CANONICAL (attr))
22394     {
22395       DW_STRING (attr)
22396         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
22397                                     &objfile->per_bfd->storage_obstack);
22398       DW_STRING_IS_CANONICAL (attr) = 1;
22399     }
22400   return DW_STRING (attr);
22401 }
22402
22403 /* Return the die that this die in an extension of, or NULL if there
22404    is none.  *EXT_CU is the CU containing DIE on input, and the CU
22405    containing the return value on output.  */
22406
22407 static struct die_info *
22408 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
22409 {
22410   struct attribute *attr;
22411
22412   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
22413   if (attr == NULL)
22414     return NULL;
22415
22416   return follow_die_ref (die, attr, ext_cu);
22417 }
22418
22419 /* Convert a DIE tag into its string name.  */
22420
22421 static const char *
22422 dwarf_tag_name (unsigned tag)
22423 {
22424   const char *name = get_DW_TAG_name (tag);
22425
22426   if (name == NULL)
22427     return "DW_TAG_<unknown>";
22428
22429   return name;
22430 }
22431
22432 /* Convert a DWARF attribute code into its string name.  */
22433
22434 static const char *
22435 dwarf_attr_name (unsigned attr)
22436 {
22437   const char *name;
22438
22439 #ifdef MIPS /* collides with DW_AT_HP_block_index */
22440   if (attr == DW_AT_MIPS_fde)
22441     return "DW_AT_MIPS_fde";
22442 #else
22443   if (attr == DW_AT_HP_block_index)
22444     return "DW_AT_HP_block_index";
22445 #endif
22446
22447   name = get_DW_AT_name (attr);
22448
22449   if (name == NULL)
22450     return "DW_AT_<unknown>";
22451
22452   return name;
22453 }
22454
22455 /* Convert a DWARF value form code into its string name.  */
22456
22457 static const char *
22458 dwarf_form_name (unsigned form)
22459 {
22460   const char *name = get_DW_FORM_name (form);
22461
22462   if (name == NULL)
22463     return "DW_FORM_<unknown>";
22464
22465   return name;
22466 }
22467
22468 static const char *
22469 dwarf_bool_name (unsigned mybool)
22470 {
22471   if (mybool)
22472     return "TRUE";
22473   else
22474     return "FALSE";
22475 }
22476
22477 /* Convert a DWARF type code into its string name.  */
22478
22479 static const char *
22480 dwarf_type_encoding_name (unsigned enc)
22481 {
22482   const char *name = get_DW_ATE_name (enc);
22483
22484   if (name == NULL)
22485     return "DW_ATE_<unknown>";
22486
22487   return name;
22488 }
22489
22490 static void
22491 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
22492 {
22493   unsigned int i;
22494
22495   print_spaces (indent, f);
22496   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset %s)\n",
22497                       dwarf_tag_name (die->tag), die->abbrev,
22498                       sect_offset_str (die->sect_off));
22499
22500   if (die->parent != NULL)
22501     {
22502       print_spaces (indent, f);
22503       fprintf_unfiltered (f, "  parent at offset: %s\n",
22504                           sect_offset_str (die->parent->sect_off));
22505     }
22506
22507   print_spaces (indent, f);
22508   fprintf_unfiltered (f, "  has children: %s\n",
22509            dwarf_bool_name (die->child != NULL));
22510
22511   print_spaces (indent, f);
22512   fprintf_unfiltered (f, "  attributes:\n");
22513
22514   for (i = 0; i < die->num_attrs; ++i)
22515     {
22516       print_spaces (indent, f);
22517       fprintf_unfiltered (f, "    %s (%s) ",
22518                dwarf_attr_name (die->attrs[i].name),
22519                dwarf_form_name (die->attrs[i].form));
22520
22521       switch (die->attrs[i].form)
22522         {
22523         case DW_FORM_addr:
22524         case DW_FORM_GNU_addr_index:
22525           fprintf_unfiltered (f, "address: ");
22526           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
22527           break;
22528         case DW_FORM_block2:
22529         case DW_FORM_block4:
22530         case DW_FORM_block:
22531         case DW_FORM_block1:
22532           fprintf_unfiltered (f, "block: size %s",
22533                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22534           break;
22535         case DW_FORM_exprloc:
22536           fprintf_unfiltered (f, "expression: size %s",
22537                               pulongest (DW_BLOCK (&die->attrs[i])->size));
22538           break;
22539         case DW_FORM_data16:
22540           fprintf_unfiltered (f, "constant of 16 bytes");
22541           break;
22542         case DW_FORM_ref_addr:
22543           fprintf_unfiltered (f, "ref address: ");
22544           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22545           break;
22546         case DW_FORM_GNU_ref_alt:
22547           fprintf_unfiltered (f, "alt ref address: ");
22548           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
22549           break;
22550         case DW_FORM_ref1:
22551         case DW_FORM_ref2:
22552         case DW_FORM_ref4:
22553         case DW_FORM_ref8:
22554         case DW_FORM_ref_udata:
22555           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
22556                               (long) (DW_UNSND (&die->attrs[i])));
22557           break;
22558         case DW_FORM_data1:
22559         case DW_FORM_data2:
22560         case DW_FORM_data4:
22561         case DW_FORM_data8:
22562         case DW_FORM_udata:
22563         case DW_FORM_sdata:
22564           fprintf_unfiltered (f, "constant: %s",
22565                               pulongest (DW_UNSND (&die->attrs[i])));
22566           break;
22567         case DW_FORM_sec_offset:
22568           fprintf_unfiltered (f, "section offset: %s",
22569                               pulongest (DW_UNSND (&die->attrs[i])));
22570           break;
22571         case DW_FORM_ref_sig8:
22572           fprintf_unfiltered (f, "signature: %s",
22573                               hex_string (DW_SIGNATURE (&die->attrs[i])));
22574           break;
22575         case DW_FORM_string:
22576         case DW_FORM_strp:
22577         case DW_FORM_line_strp:
22578         case DW_FORM_GNU_str_index:
22579         case DW_FORM_GNU_strp_alt:
22580           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
22581                    DW_STRING (&die->attrs[i])
22582                    ? DW_STRING (&die->attrs[i]) : "",
22583                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
22584           break;
22585         case DW_FORM_flag:
22586           if (DW_UNSND (&die->attrs[i]))
22587             fprintf_unfiltered (f, "flag: TRUE");
22588           else
22589             fprintf_unfiltered (f, "flag: FALSE");
22590           break;
22591         case DW_FORM_flag_present:
22592           fprintf_unfiltered (f, "flag: TRUE");
22593           break;
22594         case DW_FORM_indirect:
22595           /* The reader will have reduced the indirect form to
22596              the "base form" so this form should not occur.  */
22597           fprintf_unfiltered (f, 
22598                               "unexpected attribute form: DW_FORM_indirect");
22599           break;
22600         case DW_FORM_implicit_const:
22601           fprintf_unfiltered (f, "constant: %s",
22602                               plongest (DW_SND (&die->attrs[i])));
22603           break;
22604         default:
22605           fprintf_unfiltered (f, "unsupported attribute form: %d.",
22606                    die->attrs[i].form);
22607           break;
22608         }
22609       fprintf_unfiltered (f, "\n");
22610     }
22611 }
22612
22613 static void
22614 dump_die_for_error (struct die_info *die)
22615 {
22616   dump_die_shallow (gdb_stderr, 0, die);
22617 }
22618
22619 static void
22620 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
22621 {
22622   int indent = level * 4;
22623
22624   gdb_assert (die != NULL);
22625
22626   if (level >= max_level)
22627     return;
22628
22629   dump_die_shallow (f, indent, die);
22630
22631   if (die->child != NULL)
22632     {
22633       print_spaces (indent, f);
22634       fprintf_unfiltered (f, "  Children:");
22635       if (level + 1 < max_level)
22636         {
22637           fprintf_unfiltered (f, "\n");
22638           dump_die_1 (f, level + 1, max_level, die->child);
22639         }
22640       else
22641         {
22642           fprintf_unfiltered (f,
22643                               " [not printed, max nesting level reached]\n");
22644         }
22645     }
22646
22647   if (die->sibling != NULL && level > 0)
22648     {
22649       dump_die_1 (f, level, max_level, die->sibling);
22650     }
22651 }
22652
22653 /* This is called from the pdie macro in gdbinit.in.
22654    It's not static so gcc will keep a copy callable from gdb.  */
22655
22656 void
22657 dump_die (struct die_info *die, int max_level)
22658 {
22659   dump_die_1 (gdb_stdlog, 0, max_level, die);
22660 }
22661
22662 static void
22663 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
22664 {
22665   void **slot;
22666
22667   slot = htab_find_slot_with_hash (cu->die_hash, die,
22668                                    to_underlying (die->sect_off),
22669                                    INSERT);
22670
22671   *slot = die;
22672 }
22673
22674 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
22675    required kind.  */
22676
22677 static sect_offset
22678 dwarf2_get_ref_die_offset (const struct attribute *attr)
22679 {
22680   if (attr_form_is_ref (attr))
22681     return (sect_offset) DW_UNSND (attr);
22682
22683   complaint (_("unsupported die ref attribute form: '%s'"),
22684              dwarf_form_name (attr->form));
22685   return {};
22686 }
22687
22688 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
22689  * the value held by the attribute is not constant.  */
22690
22691 static LONGEST
22692 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
22693 {
22694   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
22695     return DW_SND (attr);
22696   else if (attr->form == DW_FORM_udata
22697            || attr->form == DW_FORM_data1
22698            || attr->form == DW_FORM_data2
22699            || attr->form == DW_FORM_data4
22700            || attr->form == DW_FORM_data8)
22701     return DW_UNSND (attr);
22702   else
22703     {
22704       /* For DW_FORM_data16 see attr_form_is_constant.  */
22705       complaint (_("Attribute value is not a constant (%s)"),
22706                  dwarf_form_name (attr->form));
22707       return default_value;
22708     }
22709 }
22710
22711 /* Follow reference or signature attribute ATTR of SRC_DIE.
22712    On entry *REF_CU is the CU of SRC_DIE.
22713    On exit *REF_CU is the CU of the result.  */
22714
22715 static struct die_info *
22716 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
22717                        struct dwarf2_cu **ref_cu)
22718 {
22719   struct die_info *die;
22720
22721   if (attr_form_is_ref (attr))
22722     die = follow_die_ref (src_die, attr, ref_cu);
22723   else if (attr->form == DW_FORM_ref_sig8)
22724     die = follow_die_sig (src_die, attr, ref_cu);
22725   else
22726     {
22727       dump_die_for_error (src_die);
22728       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
22729              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
22730     }
22731
22732   return die;
22733 }
22734
22735 /* Follow reference OFFSET.
22736    On entry *REF_CU is the CU of the source die referencing OFFSET.
22737    On exit *REF_CU is the CU of the result.
22738    Returns NULL if OFFSET is invalid.  */
22739
22740 static struct die_info *
22741 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
22742                    struct dwarf2_cu **ref_cu)
22743 {
22744   struct die_info temp_die;
22745   struct dwarf2_cu *target_cu, *cu = *ref_cu;
22746   struct dwarf2_per_objfile *dwarf2_per_objfile
22747     = cu->per_cu->dwarf2_per_objfile;
22748
22749   gdb_assert (cu->per_cu != NULL);
22750
22751   target_cu = cu;
22752
22753   if (cu->per_cu->is_debug_types)
22754     {
22755       /* .debug_types CUs cannot reference anything outside their CU.
22756          If they need to, they have to reference a signatured type via
22757          DW_FORM_ref_sig8.  */
22758       if (!offset_in_cu_p (&cu->header, sect_off))
22759         return NULL;
22760     }
22761   else if (offset_in_dwz != cu->per_cu->is_dwz
22762            || !offset_in_cu_p (&cu->header, sect_off))
22763     {
22764       struct dwarf2_per_cu_data *per_cu;
22765
22766       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
22767                                                  dwarf2_per_objfile);
22768
22769       /* If necessary, add it to the queue and load its DIEs.  */
22770       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
22771         load_full_comp_unit (per_cu, false, cu->language);
22772
22773       target_cu = per_cu->cu;
22774     }
22775   else if (cu->dies == NULL)
22776     {
22777       /* We're loading full DIEs during partial symbol reading.  */
22778       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
22779       load_full_comp_unit (cu->per_cu, false, language_minimal);
22780     }
22781
22782   *ref_cu = target_cu;
22783   temp_die.sect_off = sect_off;
22784   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
22785                                                   &temp_die,
22786                                                   to_underlying (sect_off));
22787 }
22788
22789 /* Follow reference attribute ATTR of SRC_DIE.
22790    On entry *REF_CU is the CU of SRC_DIE.
22791    On exit *REF_CU is the CU of the result.  */
22792
22793 static struct die_info *
22794 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
22795                 struct dwarf2_cu **ref_cu)
22796 {
22797   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
22798   struct dwarf2_cu *cu = *ref_cu;
22799   struct die_info *die;
22800
22801   die = follow_die_offset (sect_off,
22802                            (attr->form == DW_FORM_GNU_ref_alt
22803                             || cu->per_cu->is_dwz),
22804                            ref_cu);
22805   if (!die)
22806     error (_("Dwarf Error: Cannot find DIE at %s referenced from DIE "
22807            "at %s [in module %s]"),
22808            sect_offset_str (sect_off), sect_offset_str (src_die->sect_off),
22809            objfile_name (cu->per_cu->dwarf2_per_objfile->objfile));
22810
22811   return die;
22812 }
22813
22814 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
22815    Returned value is intended for DW_OP_call*.  Returned
22816    dwarf2_locexpr_baton->data has lifetime of
22817    PER_CU->DWARF2_PER_OBJFILE->OBJFILE.  */
22818
22819 struct dwarf2_locexpr_baton
22820 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
22821                                struct dwarf2_per_cu_data *per_cu,
22822                                CORE_ADDR (*get_frame_pc) (void *baton),
22823                                void *baton)
22824 {
22825   struct dwarf2_cu *cu;
22826   struct die_info *die;
22827   struct attribute *attr;
22828   struct dwarf2_locexpr_baton retval;
22829   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
22830   struct objfile *objfile = dwarf2_per_objfile->objfile;
22831
22832   if (per_cu->cu == NULL)
22833     load_cu (per_cu, false);
22834   cu = per_cu->cu;
22835   if (cu == NULL)
22836     {
22837       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22838          Instead just throw an error, not much else we can do.  */
22839       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22840              sect_offset_str (sect_off), objfile_name (objfile));
22841     }
22842
22843   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22844   if (!die)
22845     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22846            sect_offset_str (sect_off), objfile_name (objfile));
22847
22848   attr = dwarf2_attr (die, DW_AT_location, cu);
22849   if (!attr)
22850     {
22851       /* DWARF: "If there is no such attribute, then there is no effect.".
22852          DATA is ignored if SIZE is 0.  */
22853
22854       retval.data = NULL;
22855       retval.size = 0;
22856     }
22857   else if (attr_form_is_section_offset (attr))
22858     {
22859       struct dwarf2_loclist_baton loclist_baton;
22860       CORE_ADDR pc = (*get_frame_pc) (baton);
22861       size_t size;
22862
22863       fill_in_loclist_baton (cu, &loclist_baton, attr);
22864
22865       retval.data = dwarf2_find_location_expression (&loclist_baton,
22866                                                      &size, pc);
22867       retval.size = size;
22868     }
22869   else
22870     {
22871       if (!attr_form_is_block (attr))
22872         error (_("Dwarf Error: DIE at %s referenced in module %s "
22873                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
22874                sect_offset_str (sect_off), objfile_name (objfile));
22875
22876       retval.data = DW_BLOCK (attr)->data;
22877       retval.size = DW_BLOCK (attr)->size;
22878     }
22879   retval.per_cu = cu->per_cu;
22880
22881   age_cached_comp_units (dwarf2_per_objfile);
22882
22883   return retval;
22884 }
22885
22886 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
22887    offset.  */
22888
22889 struct dwarf2_locexpr_baton
22890 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
22891                              struct dwarf2_per_cu_data *per_cu,
22892                              CORE_ADDR (*get_frame_pc) (void *baton),
22893                              void *baton)
22894 {
22895   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
22896
22897   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
22898 }
22899
22900 /* Write a constant of a given type as target-ordered bytes into
22901    OBSTACK.  */
22902
22903 static const gdb_byte *
22904 write_constant_as_bytes (struct obstack *obstack,
22905                          enum bfd_endian byte_order,
22906                          struct type *type,
22907                          ULONGEST value,
22908                          LONGEST *len)
22909 {
22910   gdb_byte *result;
22911
22912   *len = TYPE_LENGTH (type);
22913   result = (gdb_byte *) obstack_alloc (obstack, *len);
22914   store_unsigned_integer (result, *len, byte_order, value);
22915
22916   return result;
22917 }
22918
22919 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
22920    pointer to the constant bytes and set LEN to the length of the
22921    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
22922    does not have a DW_AT_const_value, return NULL.  */
22923
22924 const gdb_byte *
22925 dwarf2_fetch_constant_bytes (sect_offset sect_off,
22926                              struct dwarf2_per_cu_data *per_cu,
22927                              struct obstack *obstack,
22928                              LONGEST *len)
22929 {
22930   struct dwarf2_cu *cu;
22931   struct die_info *die;
22932   struct attribute *attr;
22933   const gdb_byte *result = NULL;
22934   struct type *type;
22935   LONGEST value;
22936   enum bfd_endian byte_order;
22937   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
22938
22939   if (per_cu->cu == NULL)
22940     load_cu (per_cu, false);
22941   cu = per_cu->cu;
22942   if (cu == NULL)
22943     {
22944       /* We shouldn't get here for a dummy CU, but don't crash on the user.
22945          Instead just throw an error, not much else we can do.  */
22946       error (_("Dwarf Error: Dummy CU at %s referenced in module %s"),
22947              sect_offset_str (sect_off), objfile_name (objfile));
22948     }
22949
22950   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
22951   if (!die)
22952     error (_("Dwarf Error: Cannot find DIE at %s referenced in module %s"),
22953            sect_offset_str (sect_off), objfile_name (objfile));
22954
22955   attr = dwarf2_attr (die, DW_AT_const_value, cu);
22956   if (attr == NULL)
22957     return NULL;
22958
22959   byte_order = (bfd_big_endian (objfile->obfd)
22960                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
22961
22962   switch (attr->form)
22963     {
22964     case DW_FORM_addr:
22965     case DW_FORM_GNU_addr_index:
22966       {
22967         gdb_byte *tem;
22968
22969         *len = cu->header.addr_size;
22970         tem = (gdb_byte *) obstack_alloc (obstack, *len);
22971         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
22972         result = tem;
22973       }
22974       break;
22975     case DW_FORM_string:
22976     case DW_FORM_strp:
22977     case DW_FORM_GNU_str_index:
22978     case DW_FORM_GNU_strp_alt:
22979       /* DW_STRING is already allocated on the objfile obstack, point
22980          directly to it.  */
22981       result = (const gdb_byte *) DW_STRING (attr);
22982       *len = strlen (DW_STRING (attr));
22983       break;
22984     case DW_FORM_block1:
22985     case DW_FORM_block2:
22986     case DW_FORM_block4:
22987     case DW_FORM_block:
22988     case DW_FORM_exprloc:
22989     case DW_FORM_data16:
22990       result = DW_BLOCK (attr)->data;
22991       *len = DW_BLOCK (attr)->size;
22992       break;
22993
22994       /* The DW_AT_const_value attributes are supposed to carry the
22995          symbol's value "represented as it would be on the target
22996          architecture."  By the time we get here, it's already been
22997          converted to host endianness, so we just need to sign- or
22998          zero-extend it as appropriate.  */
22999     case DW_FORM_data1:
23000       type = die_type (die, cu);
23001       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
23002       if (result == NULL)
23003         result = write_constant_as_bytes (obstack, byte_order,
23004                                           type, value, len);
23005       break;
23006     case DW_FORM_data2:
23007       type = die_type (die, cu);
23008       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
23009       if (result == NULL)
23010         result = write_constant_as_bytes (obstack, byte_order,
23011                                           type, value, len);
23012       break;
23013     case DW_FORM_data4:
23014       type = die_type (die, cu);
23015       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
23016       if (result == NULL)
23017         result = write_constant_as_bytes (obstack, byte_order,
23018                                           type, value, len);
23019       break;
23020     case DW_FORM_data8:
23021       type = die_type (die, cu);
23022       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
23023       if (result == NULL)
23024         result = write_constant_as_bytes (obstack, byte_order,
23025                                           type, value, len);
23026       break;
23027
23028     case DW_FORM_sdata:
23029     case DW_FORM_implicit_const:
23030       type = die_type (die, cu);
23031       result = write_constant_as_bytes (obstack, byte_order,
23032                                         type, DW_SND (attr), len);
23033       break;
23034
23035     case DW_FORM_udata:
23036       type = die_type (die, cu);
23037       result = write_constant_as_bytes (obstack, byte_order,
23038                                         type, DW_UNSND (attr), len);
23039       break;
23040
23041     default:
23042       complaint (_("unsupported const value attribute form: '%s'"),
23043                  dwarf_form_name (attr->form));
23044       break;
23045     }
23046
23047   return result;
23048 }
23049
23050 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
23051    valid type for this die is found.  */
23052
23053 struct type *
23054 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
23055                                 struct dwarf2_per_cu_data *per_cu)
23056 {
23057   struct dwarf2_cu *cu;
23058   struct die_info *die;
23059
23060   if (per_cu->cu == NULL)
23061     load_cu (per_cu, false);
23062   cu = per_cu->cu;
23063   if (!cu)
23064     return NULL;
23065
23066   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
23067   if (!die)
23068     return NULL;
23069
23070   return die_type (die, cu);
23071 }
23072
23073 /* Return the type of the DIE at DIE_OFFSET in the CU named by
23074    PER_CU.  */
23075
23076 struct type *
23077 dwarf2_get_die_type (cu_offset die_offset,
23078                      struct dwarf2_per_cu_data *per_cu)
23079 {
23080   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
23081   return get_die_type_at_offset (die_offset_sect, per_cu);
23082 }
23083
23084 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
23085    On entry *REF_CU is the CU of SRC_DIE.
23086    On exit *REF_CU is the CU of the result.
23087    Returns NULL if the referenced DIE isn't found.  */
23088
23089 static struct die_info *
23090 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
23091                   struct dwarf2_cu **ref_cu)
23092 {
23093   struct die_info temp_die;
23094   struct dwarf2_cu *sig_cu;
23095   struct die_info *die;
23096
23097   /* While it might be nice to assert sig_type->type == NULL here,
23098      we can get here for DW_AT_imported_declaration where we need
23099      the DIE not the type.  */
23100
23101   /* If necessary, add it to the queue and load its DIEs.  */
23102
23103   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
23104     read_signatured_type (sig_type);
23105
23106   sig_cu = sig_type->per_cu.cu;
23107   gdb_assert (sig_cu != NULL);
23108   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
23109   temp_die.sect_off = sig_type->type_offset_in_section;
23110   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
23111                                                  to_underlying (temp_die.sect_off));
23112   if (die)
23113     {
23114       struct dwarf2_per_objfile *dwarf2_per_objfile
23115         = (*ref_cu)->per_cu->dwarf2_per_objfile;
23116
23117       /* For .gdb_index version 7 keep track of included TUs.
23118          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
23119       if (dwarf2_per_objfile->index_table != NULL
23120           && dwarf2_per_objfile->index_table->version <= 7)
23121         {
23122           VEC_safe_push (dwarf2_per_cu_ptr,
23123                          (*ref_cu)->per_cu->imported_symtabs,
23124                          sig_cu->per_cu);
23125         }
23126
23127       *ref_cu = sig_cu;
23128       return die;
23129     }
23130
23131   return NULL;
23132 }
23133
23134 /* Follow signatured type referenced by ATTR in SRC_DIE.
23135    On entry *REF_CU is the CU of SRC_DIE.
23136    On exit *REF_CU is the CU of the result.
23137    The result is the DIE of the type.
23138    If the referenced type cannot be found an error is thrown.  */
23139
23140 static struct die_info *
23141 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
23142                 struct dwarf2_cu **ref_cu)
23143 {
23144   ULONGEST signature = DW_SIGNATURE (attr);
23145   struct signatured_type *sig_type;
23146   struct die_info *die;
23147
23148   gdb_assert (attr->form == DW_FORM_ref_sig8);
23149
23150   sig_type = lookup_signatured_type (*ref_cu, signature);
23151   /* sig_type will be NULL if the signatured type is missing from
23152      the debug info.  */
23153   if (sig_type == NULL)
23154     {
23155       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23156                " from DIE at %s [in module %s]"),
23157              hex_string (signature), sect_offset_str (src_die->sect_off),
23158              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23159     }
23160
23161   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
23162   if (die == NULL)
23163     {
23164       dump_die_for_error (src_die);
23165       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23166                " from DIE at %s [in module %s]"),
23167              hex_string (signature), sect_offset_str (src_die->sect_off),
23168              objfile_name ((*ref_cu)->per_cu->dwarf2_per_objfile->objfile));
23169     }
23170
23171   return die;
23172 }
23173
23174 /* Get the type specified by SIGNATURE referenced in DIE/CU,
23175    reading in and processing the type unit if necessary.  */
23176
23177 static struct type *
23178 get_signatured_type (struct die_info *die, ULONGEST signature,
23179                      struct dwarf2_cu *cu)
23180 {
23181   struct dwarf2_per_objfile *dwarf2_per_objfile
23182     = cu->per_cu->dwarf2_per_objfile;
23183   struct signatured_type *sig_type;
23184   struct dwarf2_cu *type_cu;
23185   struct die_info *type_die;
23186   struct type *type;
23187
23188   sig_type = lookup_signatured_type (cu, signature);
23189   /* sig_type will be NULL if the signatured type is missing from
23190      the debug info.  */
23191   if (sig_type == NULL)
23192     {
23193       complaint (_("Dwarf Error: Cannot find signatured DIE %s referenced"
23194                    " from DIE at %s [in module %s]"),
23195                  hex_string (signature), sect_offset_str (die->sect_off),
23196                  objfile_name (dwarf2_per_objfile->objfile));
23197       return build_error_marker_type (cu, die);
23198     }
23199
23200   /* If we already know the type we're done.  */
23201   if (sig_type->type != NULL)
23202     return sig_type->type;
23203
23204   type_cu = cu;
23205   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
23206   if (type_die != NULL)
23207     {
23208       /* N.B. We need to call get_die_type to ensure only one type for this DIE
23209          is created.  This is important, for example, because for c++ classes
23210          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
23211       type = read_type_die (type_die, type_cu);
23212       if (type == NULL)
23213         {
23214           complaint (_("Dwarf Error: Cannot build signatured type %s"
23215                        " referenced from DIE at %s [in module %s]"),
23216                      hex_string (signature), sect_offset_str (die->sect_off),
23217                      objfile_name (dwarf2_per_objfile->objfile));
23218           type = build_error_marker_type (cu, die);
23219         }
23220     }
23221   else
23222     {
23223       complaint (_("Dwarf Error: Problem reading signatured DIE %s referenced"
23224                    " from DIE at %s [in module %s]"),
23225                  hex_string (signature), sect_offset_str (die->sect_off),
23226                  objfile_name (dwarf2_per_objfile->objfile));
23227       type = build_error_marker_type (cu, die);
23228     }
23229   sig_type->type = type;
23230
23231   return type;
23232 }
23233
23234 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
23235    reading in and processing the type unit if necessary.  */
23236
23237 static struct type *
23238 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
23239                           struct dwarf2_cu *cu) /* ARI: editCase function */
23240 {
23241   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
23242   if (attr_form_is_ref (attr))
23243     {
23244       struct dwarf2_cu *type_cu = cu;
23245       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
23246
23247       return read_type_die (type_die, type_cu);
23248     }
23249   else if (attr->form == DW_FORM_ref_sig8)
23250     {
23251       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
23252     }
23253   else
23254     {
23255       struct dwarf2_per_objfile *dwarf2_per_objfile
23256         = cu->per_cu->dwarf2_per_objfile;
23257
23258       complaint (_("Dwarf Error: DW_AT_signature has bad form %s in DIE"
23259                    " at %s [in module %s]"),
23260                  dwarf_form_name (attr->form), sect_offset_str (die->sect_off),
23261                  objfile_name (dwarf2_per_objfile->objfile));
23262       return build_error_marker_type (cu, die);
23263     }
23264 }
23265
23266 /* Load the DIEs associated with type unit PER_CU into memory.  */
23267
23268 static void
23269 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
23270 {
23271   struct signatured_type *sig_type;
23272
23273   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
23274   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
23275
23276   /* We have the per_cu, but we need the signatured_type.
23277      Fortunately this is an easy translation.  */
23278   gdb_assert (per_cu->is_debug_types);
23279   sig_type = (struct signatured_type *) per_cu;
23280
23281   gdb_assert (per_cu->cu == NULL);
23282
23283   read_signatured_type (sig_type);
23284
23285   gdb_assert (per_cu->cu != NULL);
23286 }
23287
23288 /* die_reader_func for read_signatured_type.
23289    This is identical to load_full_comp_unit_reader,
23290    but is kept separate for now.  */
23291
23292 static void
23293 read_signatured_type_reader (const struct die_reader_specs *reader,
23294                              const gdb_byte *info_ptr,
23295                              struct die_info *comp_unit_die,
23296                              int has_children,
23297                              void *data)
23298 {
23299   struct dwarf2_cu *cu = reader->cu;
23300
23301   gdb_assert (cu->die_hash == NULL);
23302   cu->die_hash =
23303     htab_create_alloc_ex (cu->header.length / 12,
23304                           die_hash,
23305                           die_eq,
23306                           NULL,
23307                           &cu->comp_unit_obstack,
23308                           hashtab_obstack_allocate,
23309                           dummy_obstack_deallocate);
23310
23311   if (has_children)
23312     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
23313                                                   &info_ptr, comp_unit_die);
23314   cu->dies = comp_unit_die;
23315   /* comp_unit_die is not stored in die_hash, no need.  */
23316
23317   /* We try not to read any attributes in this function, because not
23318      all CUs needed for references have been loaded yet, and symbol
23319      table processing isn't initialized.  But we have to set the CU language,
23320      or we won't be able to build types correctly.
23321      Similarly, if we do not read the producer, we can not apply
23322      producer-specific interpretation.  */
23323   prepare_one_comp_unit (cu, cu->dies, language_minimal);
23324 }
23325
23326 /* Read in a signatured type and build its CU and DIEs.
23327    If the type is a stub for the real type in a DWO file,
23328    read in the real type from the DWO file as well.  */
23329
23330 static void
23331 read_signatured_type (struct signatured_type *sig_type)
23332 {
23333   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
23334
23335   gdb_assert (per_cu->is_debug_types);
23336   gdb_assert (per_cu->cu == NULL);
23337
23338   init_cutu_and_read_dies (per_cu, NULL, 0, 1, false,
23339                            read_signatured_type_reader, NULL);
23340   sig_type->per_cu.tu_read = 1;
23341 }
23342
23343 /* Decode simple location descriptions.
23344    Given a pointer to a dwarf block that defines a location, compute
23345    the location and return the value.
23346
23347    NOTE drow/2003-11-18: This function is called in two situations
23348    now: for the address of static or global variables (partial symbols
23349    only) and for offsets into structures which are expected to be
23350    (more or less) constant.  The partial symbol case should go away,
23351    and only the constant case should remain.  That will let this
23352    function complain more accurately.  A few special modes are allowed
23353    without complaint for global variables (for instance, global
23354    register values and thread-local values).
23355
23356    A location description containing no operations indicates that the
23357    object is optimized out.  The return value is 0 for that case.
23358    FIXME drow/2003-11-16: No callers check for this case any more; soon all
23359    callers will only want a very basic result and this can become a
23360    complaint.
23361
23362    Note that stack[0] is unused except as a default error return.  */
23363
23364 static CORE_ADDR
23365 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
23366 {
23367   struct objfile *objfile = cu->per_cu->dwarf2_per_objfile->objfile;
23368   size_t i;
23369   size_t size = blk->size;
23370   const gdb_byte *data = blk->data;
23371   CORE_ADDR stack[64];
23372   int stacki;
23373   unsigned int bytes_read, unsnd;
23374   gdb_byte op;
23375
23376   i = 0;
23377   stacki = 0;
23378   stack[stacki] = 0;
23379   stack[++stacki] = 0;
23380
23381   while (i < size)
23382     {
23383       op = data[i++];
23384       switch (op)
23385         {
23386         case DW_OP_lit0:
23387         case DW_OP_lit1:
23388         case DW_OP_lit2:
23389         case DW_OP_lit3:
23390         case DW_OP_lit4:
23391         case DW_OP_lit5:
23392         case DW_OP_lit6:
23393         case DW_OP_lit7:
23394         case DW_OP_lit8:
23395         case DW_OP_lit9:
23396         case DW_OP_lit10:
23397         case DW_OP_lit11:
23398         case DW_OP_lit12:
23399         case DW_OP_lit13:
23400         case DW_OP_lit14:
23401         case DW_OP_lit15:
23402         case DW_OP_lit16:
23403         case DW_OP_lit17:
23404         case DW_OP_lit18:
23405         case DW_OP_lit19:
23406         case DW_OP_lit20:
23407         case DW_OP_lit21:
23408         case DW_OP_lit22:
23409         case DW_OP_lit23:
23410         case DW_OP_lit24:
23411         case DW_OP_lit25:
23412         case DW_OP_lit26:
23413         case DW_OP_lit27:
23414         case DW_OP_lit28:
23415         case DW_OP_lit29:
23416         case DW_OP_lit30:
23417         case DW_OP_lit31:
23418           stack[++stacki] = op - DW_OP_lit0;
23419           break;
23420
23421         case DW_OP_reg0:
23422         case DW_OP_reg1:
23423         case DW_OP_reg2:
23424         case DW_OP_reg3:
23425         case DW_OP_reg4:
23426         case DW_OP_reg5:
23427         case DW_OP_reg6:
23428         case DW_OP_reg7:
23429         case DW_OP_reg8:
23430         case DW_OP_reg9:
23431         case DW_OP_reg10:
23432         case DW_OP_reg11:
23433         case DW_OP_reg12:
23434         case DW_OP_reg13:
23435         case DW_OP_reg14:
23436         case DW_OP_reg15:
23437         case DW_OP_reg16:
23438         case DW_OP_reg17:
23439         case DW_OP_reg18:
23440         case DW_OP_reg19:
23441         case DW_OP_reg20:
23442         case DW_OP_reg21:
23443         case DW_OP_reg22:
23444         case DW_OP_reg23:
23445         case DW_OP_reg24:
23446         case DW_OP_reg25:
23447         case DW_OP_reg26:
23448         case DW_OP_reg27:
23449         case DW_OP_reg28:
23450         case DW_OP_reg29:
23451         case DW_OP_reg30:
23452         case DW_OP_reg31:
23453           stack[++stacki] = op - DW_OP_reg0;
23454           if (i < size)
23455             dwarf2_complex_location_expr_complaint ();
23456           break;
23457
23458         case DW_OP_regx:
23459           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
23460           i += bytes_read;
23461           stack[++stacki] = unsnd;
23462           if (i < size)
23463             dwarf2_complex_location_expr_complaint ();
23464           break;
23465
23466         case DW_OP_addr:
23467           stack[++stacki] = read_address (objfile->obfd, &data[i],
23468                                           cu, &bytes_read);
23469           i += bytes_read;
23470           break;
23471
23472         case DW_OP_const1u:
23473           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
23474           i += 1;
23475           break;
23476
23477         case DW_OP_const1s:
23478           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
23479           i += 1;
23480           break;
23481
23482         case DW_OP_const2u:
23483           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
23484           i += 2;
23485           break;
23486
23487         case DW_OP_const2s:
23488           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
23489           i += 2;
23490           break;
23491
23492         case DW_OP_const4u:
23493           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
23494           i += 4;
23495           break;
23496
23497         case DW_OP_const4s:
23498           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
23499           i += 4;
23500           break;
23501
23502         case DW_OP_const8u:
23503           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
23504           i += 8;
23505           break;
23506
23507         case DW_OP_constu:
23508           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
23509                                                   &bytes_read);
23510           i += bytes_read;
23511           break;
23512
23513         case DW_OP_consts:
23514           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
23515           i += bytes_read;
23516           break;
23517
23518         case DW_OP_dup:
23519           stack[stacki + 1] = stack[stacki];
23520           stacki++;
23521           break;
23522
23523         case DW_OP_plus:
23524           stack[stacki - 1] += stack[stacki];
23525           stacki--;
23526           break;
23527
23528         case DW_OP_plus_uconst:
23529           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
23530                                                  &bytes_read);
23531           i += bytes_read;
23532           break;
23533
23534         case DW_OP_minus:
23535           stack[stacki - 1] -= stack[stacki];
23536           stacki--;
23537           break;
23538
23539         case DW_OP_deref:
23540           /* If we're not the last op, then we definitely can't encode
23541              this using GDB's address_class enum.  This is valid for partial
23542              global symbols, although the variable's address will be bogus
23543              in the psymtab.  */
23544           if (i < size)
23545             dwarf2_complex_location_expr_complaint ();
23546           break;
23547
23548         case DW_OP_GNU_push_tls_address:
23549         case DW_OP_form_tls_address:
23550           /* The top of the stack has the offset from the beginning
23551              of the thread control block at which the variable is located.  */
23552           /* Nothing should follow this operator, so the top of stack would
23553              be returned.  */
23554           /* This is valid for partial global symbols, but the variable's
23555              address will be bogus in the psymtab.  Make it always at least
23556              non-zero to not look as a variable garbage collected by linker
23557              which have DW_OP_addr 0.  */
23558           if (i < size)
23559             dwarf2_complex_location_expr_complaint ();
23560           stack[stacki]++;
23561           break;
23562
23563         case DW_OP_GNU_uninit:
23564           break;
23565
23566         case DW_OP_GNU_addr_index:
23567         case DW_OP_GNU_const_index:
23568           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
23569                                                          &bytes_read);
23570           i += bytes_read;
23571           break;
23572
23573         default:
23574           {
23575             const char *name = get_DW_OP_name (op);
23576
23577             if (name)
23578               complaint (_("unsupported stack op: '%s'"),
23579                          name);
23580             else
23581               complaint (_("unsupported stack op: '%02x'"),
23582                          op);
23583           }
23584
23585           return (stack[stacki]);
23586         }
23587
23588       /* Enforce maximum stack depth of SIZE-1 to avoid writing
23589          outside of the allocated space.  Also enforce minimum>0.  */
23590       if (stacki >= ARRAY_SIZE (stack) - 1)
23591         {
23592           complaint (_("location description stack overflow"));
23593           return 0;
23594         }
23595
23596       if (stacki <= 0)
23597         {
23598           complaint (_("location description stack underflow"));
23599           return 0;
23600         }
23601     }
23602   return (stack[stacki]);
23603 }
23604
23605 /* memory allocation interface */
23606
23607 static struct dwarf_block *
23608 dwarf_alloc_block (struct dwarf2_cu *cu)
23609 {
23610   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
23611 }
23612
23613 static struct die_info *
23614 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
23615 {
23616   struct die_info *die;
23617   size_t size = sizeof (struct die_info);
23618
23619   if (num_attrs > 1)
23620     size += (num_attrs - 1) * sizeof (struct attribute);
23621
23622   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
23623   memset (die, 0, sizeof (struct die_info));
23624   return (die);
23625 }
23626
23627 \f
23628 /* Macro support.  */
23629
23630 /* Return file name relative to the compilation directory of file number I in
23631    *LH's file name table.  The result is allocated using xmalloc; the caller is
23632    responsible for freeing it.  */
23633
23634 static char *
23635 file_file_name (int file, struct line_header *lh)
23636 {
23637   /* Is the file number a valid index into the line header's file name
23638      table?  Remember that file numbers start with one, not zero.  */
23639   if (1 <= file && file <= lh->file_names.size ())
23640     {
23641       const file_entry &fe = lh->file_names[file - 1];
23642
23643       if (!IS_ABSOLUTE_PATH (fe.name))
23644         {
23645           const char *dir = fe.include_dir (lh);
23646           if (dir != NULL)
23647             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
23648         }
23649       return xstrdup (fe.name);
23650     }
23651   else
23652     {
23653       /* The compiler produced a bogus file number.  We can at least
23654          record the macro definitions made in the file, even if we
23655          won't be able to find the file by name.  */
23656       char fake_name[80];
23657
23658       xsnprintf (fake_name, sizeof (fake_name),
23659                  "<bad macro file number %d>", file);
23660
23661       complaint (_("bad file number in macro information (%d)"),
23662                  file);
23663
23664       return xstrdup (fake_name);
23665     }
23666 }
23667
23668 /* Return the full name of file number I in *LH's file name table.
23669    Use COMP_DIR as the name of the current directory of the
23670    compilation.  The result is allocated using xmalloc; the caller is
23671    responsible for freeing it.  */
23672 static char *
23673 file_full_name (int file, struct line_header *lh, const char *comp_dir)
23674 {
23675   /* Is the file number a valid index into the line header's file name
23676      table?  Remember that file numbers start with one, not zero.  */
23677   if (1 <= file && file <= lh->file_names.size ())
23678     {
23679       char *relative = file_file_name (file, lh);
23680
23681       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
23682         return relative;
23683       return reconcat (relative, comp_dir, SLASH_STRING,
23684                        relative, (char *) NULL);
23685     }
23686   else
23687     return file_file_name (file, lh);
23688 }
23689
23690
23691 static struct macro_source_file *
23692 macro_start_file (int file, int line,
23693                   struct macro_source_file *current_file,
23694                   struct line_header *lh)
23695 {
23696   /* File name relative to the compilation directory of this source file.  */
23697   char *file_name = file_file_name (file, lh);
23698
23699   if (! current_file)
23700     {
23701       /* Note: We don't create a macro table for this compilation unit
23702          at all until we actually get a filename.  */
23703       struct macro_table *macro_table = get_macro_table ();
23704
23705       /* If we have no current file, then this must be the start_file
23706          directive for the compilation unit's main source file.  */
23707       current_file = macro_set_main (macro_table, file_name);
23708       macro_define_special (macro_table);
23709     }
23710   else
23711     current_file = macro_include (current_file, line, file_name);
23712
23713   xfree (file_name);
23714
23715   return current_file;
23716 }
23717
23718 static const char *
23719 consume_improper_spaces (const char *p, const char *body)
23720 {
23721   if (*p == ' ')
23722     {
23723       complaint (_("macro definition contains spaces "
23724                    "in formal argument list:\n`%s'"),
23725                  body);
23726
23727       while (*p == ' ')
23728         p++;
23729     }
23730
23731   return p;
23732 }
23733
23734
23735 static void
23736 parse_macro_definition (struct macro_source_file *file, int line,
23737                         const char *body)
23738 {
23739   const char *p;
23740
23741   /* The body string takes one of two forms.  For object-like macro
23742      definitions, it should be:
23743
23744         <macro name> " " <definition>
23745
23746      For function-like macro definitions, it should be:
23747
23748         <macro name> "() " <definition>
23749      or
23750         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
23751
23752      Spaces may appear only where explicitly indicated, and in the
23753      <definition>.
23754
23755      The Dwarf 2 spec says that an object-like macro's name is always
23756      followed by a space, but versions of GCC around March 2002 omit
23757      the space when the macro's definition is the empty string.
23758
23759      The Dwarf 2 spec says that there should be no spaces between the
23760      formal arguments in a function-like macro's formal argument list,
23761      but versions of GCC around March 2002 include spaces after the
23762      commas.  */
23763
23764
23765   /* Find the extent of the macro name.  The macro name is terminated
23766      by either a space or null character (for an object-like macro) or
23767      an opening paren (for a function-like macro).  */
23768   for (p = body; *p; p++)
23769     if (*p == ' ' || *p == '(')
23770       break;
23771
23772   if (*p == ' ' || *p == '\0')
23773     {
23774       /* It's an object-like macro.  */
23775       int name_len = p - body;
23776       char *name = savestring (body, name_len);
23777       const char *replacement;
23778
23779       if (*p == ' ')
23780         replacement = body + name_len + 1;
23781       else
23782         {
23783           dwarf2_macro_malformed_definition_complaint (body);
23784           replacement = body + name_len;
23785         }
23786
23787       macro_define_object (file, line, name, replacement);
23788
23789       xfree (name);
23790     }
23791   else if (*p == '(')
23792     {
23793       /* It's a function-like macro.  */
23794       char *name = savestring (body, p - body);
23795       int argc = 0;
23796       int argv_size = 1;
23797       char **argv = XNEWVEC (char *, argv_size);
23798
23799       p++;
23800
23801       p = consume_improper_spaces (p, body);
23802
23803       /* Parse the formal argument list.  */
23804       while (*p && *p != ')')
23805         {
23806           /* Find the extent of the current argument name.  */
23807           const char *arg_start = p;
23808
23809           while (*p && *p != ',' && *p != ')' && *p != ' ')
23810             p++;
23811
23812           if (! *p || p == arg_start)
23813             dwarf2_macro_malformed_definition_complaint (body);
23814           else
23815             {
23816               /* Make sure argv has room for the new argument.  */
23817               if (argc >= argv_size)
23818                 {
23819                   argv_size *= 2;
23820                   argv = XRESIZEVEC (char *, argv, argv_size);
23821                 }
23822
23823               argv[argc++] = savestring (arg_start, p - arg_start);
23824             }
23825
23826           p = consume_improper_spaces (p, body);
23827
23828           /* Consume the comma, if present.  */
23829           if (*p == ',')
23830             {
23831               p++;
23832
23833               p = consume_improper_spaces (p, body);
23834             }
23835         }
23836
23837       if (*p == ')')
23838         {
23839           p++;
23840
23841           if (*p == ' ')
23842             /* Perfectly formed definition, no complaints.  */
23843             macro_define_function (file, line, name,
23844                                    argc, (const char **) argv,
23845                                    p + 1);
23846           else if (*p == '\0')
23847             {
23848               /* Complain, but do define it.  */
23849               dwarf2_macro_malformed_definition_complaint (body);
23850               macro_define_function (file, line, name,
23851                                      argc, (const char **) argv,
23852                                      p);
23853             }
23854           else
23855             /* Just complain.  */
23856             dwarf2_macro_malformed_definition_complaint (body);
23857         }
23858       else
23859         /* Just complain.  */
23860         dwarf2_macro_malformed_definition_complaint (body);
23861
23862       xfree (name);
23863       {
23864         int i;
23865
23866         for (i = 0; i < argc; i++)
23867           xfree (argv[i]);
23868       }
23869       xfree (argv);
23870     }
23871   else
23872     dwarf2_macro_malformed_definition_complaint (body);
23873 }
23874
23875 /* Skip some bytes from BYTES according to the form given in FORM.
23876    Returns the new pointer.  */
23877
23878 static const gdb_byte *
23879 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
23880                  enum dwarf_form form,
23881                  unsigned int offset_size,
23882                  struct dwarf2_section_info *section)
23883 {
23884   unsigned int bytes_read;
23885
23886   switch (form)
23887     {
23888     case DW_FORM_data1:
23889     case DW_FORM_flag:
23890       ++bytes;
23891       break;
23892
23893     case DW_FORM_data2:
23894       bytes += 2;
23895       break;
23896
23897     case DW_FORM_data4:
23898       bytes += 4;
23899       break;
23900
23901     case DW_FORM_data8:
23902       bytes += 8;
23903       break;
23904
23905     case DW_FORM_data16:
23906       bytes += 16;
23907       break;
23908
23909     case DW_FORM_string:
23910       read_direct_string (abfd, bytes, &bytes_read);
23911       bytes += bytes_read;
23912       break;
23913
23914     case DW_FORM_sec_offset:
23915     case DW_FORM_strp:
23916     case DW_FORM_GNU_strp_alt:
23917       bytes += offset_size;
23918       break;
23919
23920     case DW_FORM_block:
23921       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
23922       bytes += bytes_read;
23923       break;
23924
23925     case DW_FORM_block1:
23926       bytes += 1 + read_1_byte (abfd, bytes);
23927       break;
23928     case DW_FORM_block2:
23929       bytes += 2 + read_2_bytes (abfd, bytes);
23930       break;
23931     case DW_FORM_block4:
23932       bytes += 4 + read_4_bytes (abfd, bytes);
23933       break;
23934
23935     case DW_FORM_sdata:
23936     case DW_FORM_udata:
23937     case DW_FORM_GNU_addr_index:
23938     case DW_FORM_GNU_str_index:
23939       bytes = gdb_skip_leb128 (bytes, buffer_end);
23940       if (bytes == NULL)
23941         {
23942           dwarf2_section_buffer_overflow_complaint (section);
23943           return NULL;
23944         }
23945       break;
23946
23947     case DW_FORM_implicit_const:
23948       break;
23949
23950     default:
23951       {
23952         complaint (_("invalid form 0x%x in `%s'"),
23953                    form, get_section_name (section));
23954         return NULL;
23955       }
23956     }
23957
23958   return bytes;
23959 }
23960
23961 /* A helper for dwarf_decode_macros that handles skipping an unknown
23962    opcode.  Returns an updated pointer to the macro data buffer; or,
23963    on error, issues a complaint and returns NULL.  */
23964
23965 static const gdb_byte *
23966 skip_unknown_opcode (unsigned int opcode,
23967                      const gdb_byte **opcode_definitions,
23968                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
23969                      bfd *abfd,
23970                      unsigned int offset_size,
23971                      struct dwarf2_section_info *section)
23972 {
23973   unsigned int bytes_read, i;
23974   unsigned long arg;
23975   const gdb_byte *defn;
23976
23977   if (opcode_definitions[opcode] == NULL)
23978     {
23979       complaint (_("unrecognized DW_MACFINO opcode 0x%x"),
23980                  opcode);
23981       return NULL;
23982     }
23983
23984   defn = opcode_definitions[opcode];
23985   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
23986   defn += bytes_read;
23987
23988   for (i = 0; i < arg; ++i)
23989     {
23990       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
23991                                  (enum dwarf_form) defn[i], offset_size,
23992                                  section);
23993       if (mac_ptr == NULL)
23994         {
23995           /* skip_form_bytes already issued the complaint.  */
23996           return NULL;
23997         }
23998     }
23999
24000   return mac_ptr;
24001 }
24002
24003 /* A helper function which parses the header of a macro section.
24004    If the macro section is the extended (for now called "GNU") type,
24005    then this updates *OFFSET_SIZE.  Returns a pointer to just after
24006    the header, or issues a complaint and returns NULL on error.  */
24007
24008 static const gdb_byte *
24009 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
24010                           bfd *abfd,
24011                           const gdb_byte *mac_ptr,
24012                           unsigned int *offset_size,
24013                           int section_is_gnu)
24014 {
24015   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
24016
24017   if (section_is_gnu)
24018     {
24019       unsigned int version, flags;
24020
24021       version = read_2_bytes (abfd, mac_ptr);
24022       if (version != 4 && version != 5)
24023         {
24024           complaint (_("unrecognized version `%d' in .debug_macro section"),
24025                      version);
24026           return NULL;
24027         }
24028       mac_ptr += 2;
24029
24030       flags = read_1_byte (abfd, mac_ptr);
24031       ++mac_ptr;
24032       *offset_size = (flags & 1) ? 8 : 4;
24033
24034       if ((flags & 2) != 0)
24035         /* We don't need the line table offset.  */
24036         mac_ptr += *offset_size;
24037
24038       /* Vendor opcode descriptions.  */
24039       if ((flags & 4) != 0)
24040         {
24041           unsigned int i, count;
24042
24043           count = read_1_byte (abfd, mac_ptr);
24044           ++mac_ptr;
24045           for (i = 0; i < count; ++i)
24046             {
24047               unsigned int opcode, bytes_read;
24048               unsigned long arg;
24049
24050               opcode = read_1_byte (abfd, mac_ptr);
24051               ++mac_ptr;
24052               opcode_definitions[opcode] = mac_ptr;
24053               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24054               mac_ptr += bytes_read;
24055               mac_ptr += arg;
24056             }
24057         }
24058     }
24059
24060   return mac_ptr;
24061 }
24062
24063 /* A helper for dwarf_decode_macros that handles the GNU extensions,
24064    including DW_MACRO_import.  */
24065
24066 static void
24067 dwarf_decode_macro_bytes (struct dwarf2_per_objfile *dwarf2_per_objfile,
24068                           bfd *abfd,
24069                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
24070                           struct macro_source_file *current_file,
24071                           struct line_header *lh,
24072                           struct dwarf2_section_info *section,
24073                           int section_is_gnu, int section_is_dwz,
24074                           unsigned int offset_size,
24075                           htab_t include_hash)
24076 {
24077   struct objfile *objfile = dwarf2_per_objfile->objfile;
24078   enum dwarf_macro_record_type macinfo_type;
24079   int at_commandline;
24080   const gdb_byte *opcode_definitions[256];
24081
24082   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24083                                       &offset_size, section_is_gnu);
24084   if (mac_ptr == NULL)
24085     {
24086       /* We already issued a complaint.  */
24087       return;
24088     }
24089
24090   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
24091      GDB is still reading the definitions from command line.  First
24092      DW_MACINFO_start_file will need to be ignored as it was already executed
24093      to create CURRENT_FILE for the main source holding also the command line
24094      definitions.  On first met DW_MACINFO_start_file this flag is reset to
24095      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
24096
24097   at_commandline = 1;
24098
24099   do
24100     {
24101       /* Do we at least have room for a macinfo type byte?  */
24102       if (mac_ptr >= mac_end)
24103         {
24104           dwarf2_section_buffer_overflow_complaint (section);
24105           break;
24106         }
24107
24108       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24109       mac_ptr++;
24110
24111       /* Note that we rely on the fact that the corresponding GNU and
24112          DWARF constants are the same.  */
24113       DIAGNOSTIC_PUSH
24114       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24115       switch (macinfo_type)
24116         {
24117           /* A zero macinfo type indicates the end of the macro
24118              information.  */
24119         case 0:
24120           break;
24121
24122         case DW_MACRO_define:
24123         case DW_MACRO_undef:
24124         case DW_MACRO_define_strp:
24125         case DW_MACRO_undef_strp:
24126         case DW_MACRO_define_sup:
24127         case DW_MACRO_undef_sup:
24128           {
24129             unsigned int bytes_read;
24130             int line;
24131             const char *body;
24132             int is_define;
24133
24134             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24135             mac_ptr += bytes_read;
24136
24137             if (macinfo_type == DW_MACRO_define
24138                 || macinfo_type == DW_MACRO_undef)
24139               {
24140                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
24141                 mac_ptr += bytes_read;
24142               }
24143             else
24144               {
24145                 LONGEST str_offset;
24146
24147                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
24148                 mac_ptr += offset_size;
24149
24150                 if (macinfo_type == DW_MACRO_define_sup
24151                     || macinfo_type == DW_MACRO_undef_sup
24152                     || section_is_dwz)
24153                   {
24154                     struct dwz_file *dwz
24155                       = dwarf2_get_dwz_file (dwarf2_per_objfile);
24156
24157                     body = read_indirect_string_from_dwz (objfile,
24158                                                           dwz, str_offset);
24159                   }
24160                 else
24161                   body = read_indirect_string_at_offset (dwarf2_per_objfile,
24162                                                          abfd, str_offset);
24163               }
24164
24165             is_define = (macinfo_type == DW_MACRO_define
24166                          || macinfo_type == DW_MACRO_define_strp
24167                          || macinfo_type == DW_MACRO_define_sup);
24168             if (! current_file)
24169               {
24170                 /* DWARF violation as no main source is present.  */
24171                 complaint (_("debug info with no main source gives macro %s "
24172                              "on line %d: %s"),
24173                            is_define ? _("definition") : _("undefinition"),
24174                            line, body);
24175                 break;
24176               }
24177             if ((line == 0 && !at_commandline)
24178                 || (line != 0 && at_commandline))
24179               complaint (_("debug info gives %s macro %s with %s line %d: %s"),
24180                          at_commandline ? _("command-line") : _("in-file"),
24181                          is_define ? _("definition") : _("undefinition"),
24182                          line == 0 ? _("zero") : _("non-zero"), line, body);
24183
24184             if (is_define)
24185               parse_macro_definition (current_file, line, body);
24186             else
24187               {
24188                 gdb_assert (macinfo_type == DW_MACRO_undef
24189                             || macinfo_type == DW_MACRO_undef_strp
24190                             || macinfo_type == DW_MACRO_undef_sup);
24191                 macro_undef (current_file, line, body);
24192               }
24193           }
24194           break;
24195
24196         case DW_MACRO_start_file:
24197           {
24198             unsigned int bytes_read;
24199             int line, file;
24200
24201             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24202             mac_ptr += bytes_read;
24203             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24204             mac_ptr += bytes_read;
24205
24206             if ((line == 0 && !at_commandline)
24207                 || (line != 0 && at_commandline))
24208               complaint (_("debug info gives source %d included "
24209                            "from %s at %s line %d"),
24210                          file, at_commandline ? _("command-line") : _("file"),
24211                          line == 0 ? _("zero") : _("non-zero"), line);
24212
24213             if (at_commandline)
24214               {
24215                 /* This DW_MACRO_start_file was executed in the
24216                    pass one.  */
24217                 at_commandline = 0;
24218               }
24219             else
24220               current_file = macro_start_file (file, line, current_file, lh);
24221           }
24222           break;
24223
24224         case DW_MACRO_end_file:
24225           if (! current_file)
24226             complaint (_("macro debug info has an unmatched "
24227                          "`close_file' directive"));
24228           else
24229             {
24230               current_file = current_file->included_by;
24231               if (! current_file)
24232                 {
24233                   enum dwarf_macro_record_type next_type;
24234
24235                   /* GCC circa March 2002 doesn't produce the zero
24236                      type byte marking the end of the compilation
24237                      unit.  Complain if it's not there, but exit no
24238                      matter what.  */
24239
24240                   /* Do we at least have room for a macinfo type byte?  */
24241                   if (mac_ptr >= mac_end)
24242                     {
24243                       dwarf2_section_buffer_overflow_complaint (section);
24244                       return;
24245                     }
24246
24247                   /* We don't increment mac_ptr here, so this is just
24248                      a look-ahead.  */
24249                   next_type
24250                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
24251                                                                   mac_ptr);
24252                   if (next_type != 0)
24253                     complaint (_("no terminating 0-type entry for "
24254                                  "macros in `.debug_macinfo' section"));
24255
24256                   return;
24257                 }
24258             }
24259           break;
24260
24261         case DW_MACRO_import:
24262         case DW_MACRO_import_sup:
24263           {
24264             LONGEST offset;
24265             void **slot;
24266             bfd *include_bfd = abfd;
24267             struct dwarf2_section_info *include_section = section;
24268             const gdb_byte *include_mac_end = mac_end;
24269             int is_dwz = section_is_dwz;
24270             const gdb_byte *new_mac_ptr;
24271
24272             offset = read_offset_1 (abfd, mac_ptr, offset_size);
24273             mac_ptr += offset_size;
24274
24275             if (macinfo_type == DW_MACRO_import_sup)
24276               {
24277                 struct dwz_file *dwz = dwarf2_get_dwz_file (dwarf2_per_objfile);
24278
24279                 dwarf2_read_section (objfile, &dwz->macro);
24280
24281                 include_section = &dwz->macro;
24282                 include_bfd = get_section_bfd_owner (include_section);
24283                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
24284                 is_dwz = 1;
24285               }
24286
24287             new_mac_ptr = include_section->buffer + offset;
24288             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
24289
24290             if (*slot != NULL)
24291               {
24292                 /* This has actually happened; see
24293                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
24294                 complaint (_("recursive DW_MACRO_import in "
24295                              ".debug_macro section"));
24296               }
24297             else
24298               {
24299                 *slot = (void *) new_mac_ptr;
24300
24301                 dwarf_decode_macro_bytes (dwarf2_per_objfile,
24302                                           include_bfd, new_mac_ptr,
24303                                           include_mac_end, current_file, lh,
24304                                           section, section_is_gnu, is_dwz,
24305                                           offset_size, include_hash);
24306
24307                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
24308               }
24309           }
24310           break;
24311
24312         case DW_MACINFO_vendor_ext:
24313           if (!section_is_gnu)
24314             {
24315               unsigned int bytes_read;
24316
24317               /* This reads the constant, but since we don't recognize
24318                  any vendor extensions, we ignore it.  */
24319               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24320               mac_ptr += bytes_read;
24321               read_direct_string (abfd, mac_ptr, &bytes_read);
24322               mac_ptr += bytes_read;
24323
24324               /* We don't recognize any vendor extensions.  */
24325               break;
24326             }
24327           /* FALLTHROUGH */
24328
24329         default:
24330           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24331                                          mac_ptr, mac_end, abfd, offset_size,
24332                                          section);
24333           if (mac_ptr == NULL)
24334             return;
24335           break;
24336         }
24337       DIAGNOSTIC_POP
24338     } while (macinfo_type != 0);
24339 }
24340
24341 static void
24342 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
24343                      int section_is_gnu)
24344 {
24345   struct dwarf2_per_objfile *dwarf2_per_objfile
24346     = cu->per_cu->dwarf2_per_objfile;
24347   struct objfile *objfile = dwarf2_per_objfile->objfile;
24348   struct line_header *lh = cu->line_header;
24349   bfd *abfd;
24350   const gdb_byte *mac_ptr, *mac_end;
24351   struct macro_source_file *current_file = 0;
24352   enum dwarf_macro_record_type macinfo_type;
24353   unsigned int offset_size = cu->header.offset_size;
24354   const gdb_byte *opcode_definitions[256];
24355   void **slot;
24356   struct dwarf2_section_info *section;
24357   const char *section_name;
24358
24359   if (cu->dwo_unit != NULL)
24360     {
24361       if (section_is_gnu)
24362         {
24363           section = &cu->dwo_unit->dwo_file->sections.macro;
24364           section_name = ".debug_macro.dwo";
24365         }
24366       else
24367         {
24368           section = &cu->dwo_unit->dwo_file->sections.macinfo;
24369           section_name = ".debug_macinfo.dwo";
24370         }
24371     }
24372   else
24373     {
24374       if (section_is_gnu)
24375         {
24376           section = &dwarf2_per_objfile->macro;
24377           section_name = ".debug_macro";
24378         }
24379       else
24380         {
24381           section = &dwarf2_per_objfile->macinfo;
24382           section_name = ".debug_macinfo";
24383         }
24384     }
24385
24386   dwarf2_read_section (objfile, section);
24387   if (section->buffer == NULL)
24388     {
24389       complaint (_("missing %s section"), section_name);
24390       return;
24391     }
24392   abfd = get_section_bfd_owner (section);
24393
24394   /* First pass: Find the name of the base filename.
24395      This filename is needed in order to process all macros whose definition
24396      (or undefinition) comes from the command line.  These macros are defined
24397      before the first DW_MACINFO_start_file entry, and yet still need to be
24398      associated to the base file.
24399
24400      To determine the base file name, we scan the macro definitions until we
24401      reach the first DW_MACINFO_start_file entry.  We then initialize
24402      CURRENT_FILE accordingly so that any macro definition found before the
24403      first DW_MACINFO_start_file can still be associated to the base file.  */
24404
24405   mac_ptr = section->buffer + offset;
24406   mac_end = section->buffer + section->size;
24407
24408   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
24409                                       &offset_size, section_is_gnu);
24410   if (mac_ptr == NULL)
24411     {
24412       /* We already issued a complaint.  */
24413       return;
24414     }
24415
24416   do
24417     {
24418       /* Do we at least have room for a macinfo type byte?  */
24419       if (mac_ptr >= mac_end)
24420         {
24421           /* Complaint is printed during the second pass as GDB will probably
24422              stop the first pass earlier upon finding
24423              DW_MACINFO_start_file.  */
24424           break;
24425         }
24426
24427       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
24428       mac_ptr++;
24429
24430       /* Note that we rely on the fact that the corresponding GNU and
24431          DWARF constants are the same.  */
24432       DIAGNOSTIC_PUSH
24433       DIAGNOSTIC_IGNORE_SWITCH_DIFFERENT_ENUM_TYPES
24434       switch (macinfo_type)
24435         {
24436           /* A zero macinfo type indicates the end of the macro
24437              information.  */
24438         case 0:
24439           break;
24440
24441         case DW_MACRO_define:
24442         case DW_MACRO_undef:
24443           /* Only skip the data by MAC_PTR.  */
24444           {
24445             unsigned int bytes_read;
24446
24447             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24448             mac_ptr += bytes_read;
24449             read_direct_string (abfd, mac_ptr, &bytes_read);
24450             mac_ptr += bytes_read;
24451           }
24452           break;
24453
24454         case DW_MACRO_start_file:
24455           {
24456             unsigned int bytes_read;
24457             int line, file;
24458
24459             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24460             mac_ptr += bytes_read;
24461             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24462             mac_ptr += bytes_read;
24463
24464             current_file = macro_start_file (file, line, current_file, lh);
24465           }
24466           break;
24467
24468         case DW_MACRO_end_file:
24469           /* No data to skip by MAC_PTR.  */
24470           break;
24471
24472         case DW_MACRO_define_strp:
24473         case DW_MACRO_undef_strp:
24474         case DW_MACRO_define_sup:
24475         case DW_MACRO_undef_sup:
24476           {
24477             unsigned int bytes_read;
24478
24479             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24480             mac_ptr += bytes_read;
24481             mac_ptr += offset_size;
24482           }
24483           break;
24484
24485         case DW_MACRO_import:
24486         case DW_MACRO_import_sup:
24487           /* Note that, according to the spec, a transparent include
24488              chain cannot call DW_MACRO_start_file.  So, we can just
24489              skip this opcode.  */
24490           mac_ptr += offset_size;
24491           break;
24492
24493         case DW_MACINFO_vendor_ext:
24494           /* Only skip the data by MAC_PTR.  */
24495           if (!section_is_gnu)
24496             {
24497               unsigned int bytes_read;
24498
24499               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
24500               mac_ptr += bytes_read;
24501               read_direct_string (abfd, mac_ptr, &bytes_read);
24502               mac_ptr += bytes_read;
24503             }
24504           /* FALLTHROUGH */
24505
24506         default:
24507           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
24508                                          mac_ptr, mac_end, abfd, offset_size,
24509                                          section);
24510           if (mac_ptr == NULL)
24511             return;
24512           break;
24513         }
24514       DIAGNOSTIC_POP
24515     } while (macinfo_type != 0 && current_file == NULL);
24516
24517   /* Second pass: Process all entries.
24518
24519      Use the AT_COMMAND_LINE flag to determine whether we are still processing
24520      command-line macro definitions/undefinitions.  This flag is unset when we
24521      reach the first DW_MACINFO_start_file entry.  */
24522
24523   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
24524                                            htab_eq_pointer,
24525                                            NULL, xcalloc, xfree));
24526   mac_ptr = section->buffer + offset;
24527   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
24528   *slot = (void *) mac_ptr;
24529   dwarf_decode_macro_bytes (dwarf2_per_objfile,
24530                             abfd, mac_ptr, mac_end,
24531                             current_file, lh, section,
24532                             section_is_gnu, 0, offset_size,
24533                             include_hash.get ());
24534 }
24535
24536 /* Check if the attribute's form is a DW_FORM_block*
24537    if so return true else false.  */
24538
24539 static int
24540 attr_form_is_block (const struct attribute *attr)
24541 {
24542   return (attr == NULL ? 0 :
24543       attr->form == DW_FORM_block1
24544       || attr->form == DW_FORM_block2
24545       || attr->form == DW_FORM_block4
24546       || attr->form == DW_FORM_block
24547       || attr->form == DW_FORM_exprloc);
24548 }
24549
24550 /* Return non-zero if ATTR's value is a section offset --- classes
24551    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
24552    You may use DW_UNSND (attr) to retrieve such offsets.
24553
24554    Section 7.5.4, "Attribute Encodings", explains that no attribute
24555    may have a value that belongs to more than one of these classes; it
24556    would be ambiguous if we did, because we use the same forms for all
24557    of them.  */
24558
24559 static int
24560 attr_form_is_section_offset (const struct attribute *attr)
24561 {
24562   return (attr->form == DW_FORM_data4
24563           || attr->form == DW_FORM_data8
24564           || attr->form == DW_FORM_sec_offset);
24565 }
24566
24567 /* Return non-zero if ATTR's value falls in the 'constant' class, or
24568    zero otherwise.  When this function returns true, you can apply
24569    dwarf2_get_attr_constant_value to it.
24570
24571    However, note that for some attributes you must check
24572    attr_form_is_section_offset before using this test.  DW_FORM_data4
24573    and DW_FORM_data8 are members of both the constant class, and of
24574    the classes that contain offsets into other debug sections
24575    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
24576    that, if an attribute's can be either a constant or one of the
24577    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
24578    taken as section offsets, not constants.
24579
24580    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
24581    cannot handle that.  */
24582
24583 static int
24584 attr_form_is_constant (const struct attribute *attr)
24585 {
24586   switch (attr->form)
24587     {
24588     case DW_FORM_sdata:
24589     case DW_FORM_udata:
24590     case DW_FORM_data1:
24591     case DW_FORM_data2:
24592     case DW_FORM_data4:
24593     case DW_FORM_data8:
24594     case DW_FORM_implicit_const:
24595       return 1;
24596     default:
24597       return 0;
24598     }
24599 }
24600
24601
24602 /* DW_ADDR is always stored already as sect_offset; despite for the forms
24603    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
24604
24605 static int
24606 attr_form_is_ref (const struct attribute *attr)
24607 {
24608   switch (attr->form)
24609     {
24610     case DW_FORM_ref_addr:
24611     case DW_FORM_ref1:
24612     case DW_FORM_ref2:
24613     case DW_FORM_ref4:
24614     case DW_FORM_ref8:
24615     case DW_FORM_ref_udata:
24616     case DW_FORM_GNU_ref_alt:
24617       return 1;
24618     default:
24619       return 0;
24620     }
24621 }
24622
24623 /* Return the .debug_loc section to use for CU.
24624    For DWO files use .debug_loc.dwo.  */
24625
24626 static struct dwarf2_section_info *
24627 cu_debug_loc_section (struct dwarf2_cu *cu)
24628 {
24629   struct dwarf2_per_objfile *dwarf2_per_objfile
24630     = cu->per_cu->dwarf2_per_objfile;
24631
24632   if (cu->dwo_unit)
24633     {
24634       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
24635       
24636       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
24637     }
24638   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
24639                                   : &dwarf2_per_objfile->loc);
24640 }
24641
24642 /* A helper function that fills in a dwarf2_loclist_baton.  */
24643
24644 static void
24645 fill_in_loclist_baton (struct dwarf2_cu *cu,
24646                        struct dwarf2_loclist_baton *baton,
24647                        const struct attribute *attr)
24648 {
24649   struct dwarf2_per_objfile *dwarf2_per_objfile
24650     = cu->per_cu->dwarf2_per_objfile;
24651   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24652
24653   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
24654
24655   baton->per_cu = cu->per_cu;
24656   gdb_assert (baton->per_cu);
24657   /* We don't know how long the location list is, but make sure we
24658      don't run off the edge of the section.  */
24659   baton->size = section->size - DW_UNSND (attr);
24660   baton->data = section->buffer + DW_UNSND (attr);
24661   baton->base_address = cu->base_address;
24662   baton->from_dwo = cu->dwo_unit != NULL;
24663 }
24664
24665 static void
24666 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
24667                              struct dwarf2_cu *cu, int is_block)
24668 {
24669   struct dwarf2_per_objfile *dwarf2_per_objfile
24670     = cu->per_cu->dwarf2_per_objfile;
24671   struct objfile *objfile = dwarf2_per_objfile->objfile;
24672   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
24673
24674   if (attr_form_is_section_offset (attr)
24675       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
24676          the section.  If so, fall through to the complaint in the
24677          other branch.  */
24678       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
24679     {
24680       struct dwarf2_loclist_baton *baton;
24681
24682       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
24683
24684       fill_in_loclist_baton (cu, baton, attr);
24685
24686       if (cu->base_known == 0)
24687         complaint (_("Location list used without "
24688                      "specifying the CU base address."));
24689
24690       SYMBOL_ACLASS_INDEX (sym) = (is_block
24691                                    ? dwarf2_loclist_block_index
24692                                    : dwarf2_loclist_index);
24693       SYMBOL_LOCATION_BATON (sym) = baton;
24694     }
24695   else
24696     {
24697       struct dwarf2_locexpr_baton *baton;
24698
24699       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
24700       baton->per_cu = cu->per_cu;
24701       gdb_assert (baton->per_cu);
24702
24703       if (attr_form_is_block (attr))
24704         {
24705           /* Note that we're just copying the block's data pointer
24706              here, not the actual data.  We're still pointing into the
24707              info_buffer for SYM's objfile; right now we never release
24708              that buffer, but when we do clean up properly this may
24709              need to change.  */
24710           baton->size = DW_BLOCK (attr)->size;
24711           baton->data = DW_BLOCK (attr)->data;
24712         }
24713       else
24714         {
24715           dwarf2_invalid_attrib_class_complaint ("location description",
24716                                                  SYMBOL_NATURAL_NAME (sym));
24717           baton->size = 0;
24718         }
24719
24720       SYMBOL_ACLASS_INDEX (sym) = (is_block
24721                                    ? dwarf2_locexpr_block_index
24722                                    : dwarf2_locexpr_index);
24723       SYMBOL_LOCATION_BATON (sym) = baton;
24724     }
24725 }
24726
24727 /* Return the OBJFILE associated with the compilation unit CU.  If CU
24728    came from a separate debuginfo file, then the master objfile is
24729    returned.  */
24730
24731 struct objfile *
24732 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
24733 {
24734   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24735
24736   /* Return the master objfile, so that we can report and look up the
24737      correct file containing this variable.  */
24738   if (objfile->separate_debug_objfile_backlink)
24739     objfile = objfile->separate_debug_objfile_backlink;
24740
24741   return objfile;
24742 }
24743
24744 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
24745    (CU_HEADERP is unused in such case) or prepare a temporary copy at
24746    CU_HEADERP first.  */
24747
24748 static const struct comp_unit_head *
24749 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
24750                        struct dwarf2_per_cu_data *per_cu)
24751 {
24752   const gdb_byte *info_ptr;
24753
24754   if (per_cu->cu)
24755     return &per_cu->cu->header;
24756
24757   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
24758
24759   memset (cu_headerp, 0, sizeof (*cu_headerp));
24760   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
24761                        rcuh_kind::COMPILE);
24762
24763   return cu_headerp;
24764 }
24765
24766 /* Return the address size given in the compilation unit header for CU.  */
24767
24768 int
24769 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
24770 {
24771   struct comp_unit_head cu_header_local;
24772   const struct comp_unit_head *cu_headerp;
24773
24774   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24775
24776   return cu_headerp->addr_size;
24777 }
24778
24779 /* Return the offset size given in the compilation unit header for CU.  */
24780
24781 int
24782 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
24783 {
24784   struct comp_unit_head cu_header_local;
24785   const struct comp_unit_head *cu_headerp;
24786
24787   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24788
24789   return cu_headerp->offset_size;
24790 }
24791
24792 /* See its dwarf2loc.h declaration.  */
24793
24794 int
24795 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
24796 {
24797   struct comp_unit_head cu_header_local;
24798   const struct comp_unit_head *cu_headerp;
24799
24800   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
24801
24802   if (cu_headerp->version == 2)
24803     return cu_headerp->addr_size;
24804   else
24805     return cu_headerp->offset_size;
24806 }
24807
24808 /* Return the text offset of the CU.  The returned offset comes from
24809    this CU's objfile.  If this objfile came from a separate debuginfo
24810    file, then the offset may be different from the corresponding
24811    offset in the parent objfile.  */
24812
24813 CORE_ADDR
24814 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
24815 {
24816   struct objfile *objfile = per_cu->dwarf2_per_objfile->objfile;
24817
24818   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24819 }
24820
24821 /* Return DWARF version number of PER_CU.  */
24822
24823 short
24824 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
24825 {
24826   return per_cu->dwarf_version;
24827 }
24828
24829 /* Locate the .debug_info compilation unit from CU's objfile which contains
24830    the DIE at OFFSET.  Raises an error on failure.  */
24831
24832 static struct dwarf2_per_cu_data *
24833 dwarf2_find_containing_comp_unit (sect_offset sect_off,
24834                                   unsigned int offset_in_dwz,
24835                                   struct dwarf2_per_objfile *dwarf2_per_objfile)
24836 {
24837   struct dwarf2_per_cu_data *this_cu;
24838   int low, high;
24839   const sect_offset *cu_off;
24840
24841   low = 0;
24842   high = dwarf2_per_objfile->all_comp_units.size () - 1;
24843   while (high > low)
24844     {
24845       struct dwarf2_per_cu_data *mid_cu;
24846       int mid = low + (high - low) / 2;
24847
24848       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
24849       cu_off = &mid_cu->sect_off;
24850       if (mid_cu->is_dwz > offset_in_dwz
24851           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
24852         high = mid;
24853       else
24854         low = mid + 1;
24855     }
24856   gdb_assert (low == high);
24857   this_cu = dwarf2_per_objfile->all_comp_units[low];
24858   cu_off = &this_cu->sect_off;
24859   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
24860     {
24861       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
24862         error (_("Dwarf Error: could not find partial DIE containing "
24863                "offset %s [in module %s]"),
24864                sect_offset_str (sect_off),
24865                bfd_get_filename (dwarf2_per_objfile->objfile->obfd));
24866
24867       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
24868                   <= sect_off);
24869       return dwarf2_per_objfile->all_comp_units[low-1];
24870     }
24871   else
24872     {
24873       this_cu = dwarf2_per_objfile->all_comp_units[low];
24874       if (low == dwarf2_per_objfile->all_comp_units.size () - 1
24875           && sect_off >= this_cu->sect_off + this_cu->length)
24876         error (_("invalid dwarf2 offset %s"), sect_offset_str (sect_off));
24877       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
24878       return this_cu;
24879     }
24880 }
24881
24882 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
24883
24884 dwarf2_cu::dwarf2_cu (struct dwarf2_per_cu_data *per_cu_)
24885   : per_cu (per_cu_),
24886     mark (0),
24887     has_loclist (0),
24888     checked_producer (0),
24889     producer_is_gxx_lt_4_6 (0),
24890     producer_is_gcc_lt_4_3 (0),
24891     producer_is_icc_lt_14 (0),
24892     processing_has_namespace_info (0)
24893 {
24894   per_cu->cu = this;
24895 }
24896
24897 /* Destroy a dwarf2_cu.  */
24898
24899 dwarf2_cu::~dwarf2_cu ()
24900 {
24901   per_cu->cu = NULL;
24902 }
24903
24904 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
24905
24906 static void
24907 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
24908                        enum language pretend_language)
24909 {
24910   struct attribute *attr;
24911
24912   /* Set the language we're debugging.  */
24913   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
24914   if (attr)
24915     set_cu_language (DW_UNSND (attr), cu);
24916   else
24917     {
24918       cu->language = pretend_language;
24919       cu->language_defn = language_def (cu->language);
24920     }
24921
24922   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
24923 }
24924
24925 /* Increase the age counter on each cached compilation unit, and free
24926    any that are too old.  */
24927
24928 static void
24929 age_cached_comp_units (struct dwarf2_per_objfile *dwarf2_per_objfile)
24930 {
24931   struct dwarf2_per_cu_data *per_cu, **last_chain;
24932
24933   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
24934   per_cu = dwarf2_per_objfile->read_in_chain;
24935   while (per_cu != NULL)
24936     {
24937       per_cu->cu->last_used ++;
24938       if (per_cu->cu->last_used <= dwarf_max_cache_age)
24939         dwarf2_mark (per_cu->cu);
24940       per_cu = per_cu->cu->read_in_chain;
24941     }
24942
24943   per_cu = dwarf2_per_objfile->read_in_chain;
24944   last_chain = &dwarf2_per_objfile->read_in_chain;
24945   while (per_cu != NULL)
24946     {
24947       struct dwarf2_per_cu_data *next_cu;
24948
24949       next_cu = per_cu->cu->read_in_chain;
24950
24951       if (!per_cu->cu->mark)
24952         {
24953           delete per_cu->cu;
24954           *last_chain = next_cu;
24955         }
24956       else
24957         last_chain = &per_cu->cu->read_in_chain;
24958
24959       per_cu = next_cu;
24960     }
24961 }
24962
24963 /* Remove a single compilation unit from the cache.  */
24964
24965 static void
24966 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
24967 {
24968   struct dwarf2_per_cu_data *per_cu, **last_chain;
24969   struct dwarf2_per_objfile *dwarf2_per_objfile
24970     = target_per_cu->dwarf2_per_objfile;
24971
24972   per_cu = dwarf2_per_objfile->read_in_chain;
24973   last_chain = &dwarf2_per_objfile->read_in_chain;
24974   while (per_cu != NULL)
24975     {
24976       struct dwarf2_per_cu_data *next_cu;
24977
24978       next_cu = per_cu->cu->read_in_chain;
24979
24980       if (per_cu == target_per_cu)
24981         {
24982           delete per_cu->cu;
24983           per_cu->cu = NULL;
24984           *last_chain = next_cu;
24985           break;
24986         }
24987       else
24988         last_chain = &per_cu->cu->read_in_chain;
24989
24990       per_cu = next_cu;
24991     }
24992 }
24993
24994 /* Cleanup function for the dwarf2_per_objfile data.  */
24995
24996 static void
24997 dwarf2_free_objfile (struct objfile *objfile, void *datum)
24998 {
24999   struct dwarf2_per_objfile *dwarf2_per_objfile
25000     = static_cast<struct dwarf2_per_objfile *> (datum);
25001
25002   delete dwarf2_per_objfile;
25003 }
25004
25005 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
25006    We store these in a hash table separate from the DIEs, and preserve them
25007    when the DIEs are flushed out of cache.
25008
25009    The CU "per_cu" pointer is needed because offset alone is not enough to
25010    uniquely identify the type.  A file may have multiple .debug_types sections,
25011    or the type may come from a DWO file.  Furthermore, while it's more logical
25012    to use per_cu->section+offset, with Fission the section with the data is in
25013    the DWO file but we don't know that section at the point we need it.
25014    We have to use something in dwarf2_per_cu_data (or the pointer to it)
25015    because we can enter the lookup routine, get_die_type_at_offset, from
25016    outside this file, and thus won't necessarily have PER_CU->cu.
25017    Fortunately, PER_CU is stable for the life of the objfile.  */
25018
25019 struct dwarf2_per_cu_offset_and_type
25020 {
25021   const struct dwarf2_per_cu_data *per_cu;
25022   sect_offset sect_off;
25023   struct type *type;
25024 };
25025
25026 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
25027
25028 static hashval_t
25029 per_cu_offset_and_type_hash (const void *item)
25030 {
25031   const struct dwarf2_per_cu_offset_and_type *ofs
25032     = (const struct dwarf2_per_cu_offset_and_type *) item;
25033
25034   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
25035 }
25036
25037 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
25038
25039 static int
25040 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
25041 {
25042   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
25043     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
25044   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
25045     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
25046
25047   return (ofs_lhs->per_cu == ofs_rhs->per_cu
25048           && ofs_lhs->sect_off == ofs_rhs->sect_off);
25049 }
25050
25051 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
25052    table if necessary.  For convenience, return TYPE.
25053
25054    The DIEs reading must have careful ordering to:
25055     * Not cause infite loops trying to read in DIEs as a prerequisite for
25056       reading current DIE.
25057     * Not trying to dereference contents of still incompletely read in types
25058       while reading in other DIEs.
25059     * Enable referencing still incompletely read in types just by a pointer to
25060       the type without accessing its fields.
25061
25062    Therefore caller should follow these rules:
25063      * Try to fetch any prerequisite types we may need to build this DIE type
25064        before building the type and calling set_die_type.
25065      * After building type call set_die_type for current DIE as soon as
25066        possible before fetching more types to complete the current type.
25067      * Make the type as complete as possible before fetching more types.  */
25068
25069 static struct type *
25070 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
25071 {
25072   struct dwarf2_per_objfile *dwarf2_per_objfile
25073     = cu->per_cu->dwarf2_per_objfile;
25074   struct dwarf2_per_cu_offset_and_type **slot, ofs;
25075   struct objfile *objfile = dwarf2_per_objfile->objfile;
25076   struct attribute *attr;
25077   struct dynamic_prop prop;
25078
25079   /* For Ada types, make sure that the gnat-specific data is always
25080      initialized (if not already set).  There are a few types where
25081      we should not be doing so, because the type-specific area is
25082      already used to hold some other piece of info (eg: TYPE_CODE_FLT
25083      where the type-specific area is used to store the floatformat).
25084      But this is not a problem, because the gnat-specific information
25085      is actually not needed for these types.  */
25086   if (need_gnat_info (cu)
25087       && TYPE_CODE (type) != TYPE_CODE_FUNC
25088       && TYPE_CODE (type) != TYPE_CODE_FLT
25089       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
25090       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
25091       && TYPE_CODE (type) != TYPE_CODE_METHOD
25092       && !HAVE_GNAT_AUX_INFO (type))
25093     INIT_GNAT_SPECIFIC (type);
25094
25095   /* Read DW_AT_allocated and set in type.  */
25096   attr = dwarf2_attr (die, DW_AT_allocated, cu);
25097   if (attr_form_is_block (attr))
25098     {
25099       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25100         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type);
25101     }
25102   else if (attr != NULL)
25103     {
25104       complaint (_("DW_AT_allocated has the wrong form (%s) at DIE %s"),
25105                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25106                  sect_offset_str (die->sect_off));
25107     }
25108
25109   /* Read DW_AT_associated and set in type.  */
25110   attr = dwarf2_attr (die, DW_AT_associated, cu);
25111   if (attr_form_is_block (attr))
25112     {
25113       if (attr_to_dynamic_prop (attr, die, cu, &prop))
25114         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type);
25115     }
25116   else if (attr != NULL)
25117     {
25118       complaint (_("DW_AT_associated has the wrong form (%s) at DIE %s"),
25119                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
25120                  sect_offset_str (die->sect_off));
25121     }
25122
25123   /* Read DW_AT_data_location and set in type.  */
25124   attr = dwarf2_attr (die, DW_AT_data_location, cu);
25125   if (attr_to_dynamic_prop (attr, die, cu, &prop))
25126     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type);
25127
25128   if (dwarf2_per_objfile->die_type_hash == NULL)
25129     {
25130       dwarf2_per_objfile->die_type_hash =
25131         htab_create_alloc_ex (127,
25132                               per_cu_offset_and_type_hash,
25133                               per_cu_offset_and_type_eq,
25134                               NULL,
25135                               &objfile->objfile_obstack,
25136                               hashtab_obstack_allocate,
25137                               dummy_obstack_deallocate);
25138     }
25139
25140   ofs.per_cu = cu->per_cu;
25141   ofs.sect_off = die->sect_off;
25142   ofs.type = type;
25143   slot = (struct dwarf2_per_cu_offset_and_type **)
25144     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
25145   if (*slot)
25146     complaint (_("A problem internal to GDB: DIE %s has type already set"),
25147                sect_offset_str (die->sect_off));
25148   *slot = XOBNEW (&objfile->objfile_obstack,
25149                   struct dwarf2_per_cu_offset_and_type);
25150   **slot = ofs;
25151   return type;
25152 }
25153
25154 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
25155    or return NULL if the die does not have a saved type.  */
25156
25157 static struct type *
25158 get_die_type_at_offset (sect_offset sect_off,
25159                         struct dwarf2_per_cu_data *per_cu)
25160 {
25161   struct dwarf2_per_cu_offset_and_type *slot, ofs;
25162   struct dwarf2_per_objfile *dwarf2_per_objfile = per_cu->dwarf2_per_objfile;
25163
25164   if (dwarf2_per_objfile->die_type_hash == NULL)
25165     return NULL;
25166
25167   ofs.per_cu = per_cu;
25168   ofs.sect_off = sect_off;
25169   slot = ((struct dwarf2_per_cu_offset_and_type *)
25170           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
25171   if (slot)
25172     return slot->type;
25173   else
25174     return NULL;
25175 }
25176
25177 /* Look up the type for DIE in CU in die_type_hash,
25178    or return NULL if DIE does not have a saved type.  */
25179
25180 static struct type *
25181 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
25182 {
25183   return get_die_type_at_offset (die->sect_off, cu->per_cu);
25184 }
25185
25186 /* Add a dependence relationship from CU to REF_PER_CU.  */
25187
25188 static void
25189 dwarf2_add_dependence (struct dwarf2_cu *cu,
25190                        struct dwarf2_per_cu_data *ref_per_cu)
25191 {
25192   void **slot;
25193
25194   if (cu->dependencies == NULL)
25195     cu->dependencies
25196       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
25197                               NULL, &cu->comp_unit_obstack,
25198                               hashtab_obstack_allocate,
25199                               dummy_obstack_deallocate);
25200
25201   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
25202   if (*slot == NULL)
25203     *slot = ref_per_cu;
25204 }
25205
25206 /* Subroutine of dwarf2_mark to pass to htab_traverse.
25207    Set the mark field in every compilation unit in the
25208    cache that we must keep because we are keeping CU.  */
25209
25210 static int
25211 dwarf2_mark_helper (void **slot, void *data)
25212 {
25213   struct dwarf2_per_cu_data *per_cu;
25214
25215   per_cu = (struct dwarf2_per_cu_data *) *slot;
25216
25217   /* cu->dependencies references may not yet have been ever read if QUIT aborts
25218      reading of the chain.  As such dependencies remain valid it is not much
25219      useful to track and undo them during QUIT cleanups.  */
25220   if (per_cu->cu == NULL)
25221     return 1;
25222
25223   if (per_cu->cu->mark)
25224     return 1;
25225   per_cu->cu->mark = 1;
25226
25227   if (per_cu->cu->dependencies != NULL)
25228     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
25229
25230   return 1;
25231 }
25232
25233 /* Set the mark field in CU and in every other compilation unit in the
25234    cache that we must keep because we are keeping CU.  */
25235
25236 static void
25237 dwarf2_mark (struct dwarf2_cu *cu)
25238 {
25239   if (cu->mark)
25240     return;
25241   cu->mark = 1;
25242   if (cu->dependencies != NULL)
25243     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
25244 }
25245
25246 static void
25247 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
25248 {
25249   while (per_cu)
25250     {
25251       per_cu->cu->mark = 0;
25252       per_cu = per_cu->cu->read_in_chain;
25253     }
25254 }
25255
25256 /* Trivial hash function for partial_die_info: the hash value of a DIE
25257    is its offset in .debug_info for this objfile.  */
25258
25259 static hashval_t
25260 partial_die_hash (const void *item)
25261 {
25262   const struct partial_die_info *part_die
25263     = (const struct partial_die_info *) item;
25264
25265   return to_underlying (part_die->sect_off);
25266 }
25267
25268 /* Trivial comparison function for partial_die_info structures: two DIEs
25269    are equal if they have the same offset.  */
25270
25271 static int
25272 partial_die_eq (const void *item_lhs, const void *item_rhs)
25273 {
25274   const struct partial_die_info *part_die_lhs
25275     = (const struct partial_die_info *) item_lhs;
25276   const struct partial_die_info *part_die_rhs
25277     = (const struct partial_die_info *) item_rhs;
25278
25279   return part_die_lhs->sect_off == part_die_rhs->sect_off;
25280 }
25281
25282 static struct cmd_list_element *set_dwarf_cmdlist;
25283 static struct cmd_list_element *show_dwarf_cmdlist;
25284
25285 static void
25286 set_dwarf_cmd (const char *args, int from_tty)
25287 {
25288   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
25289              gdb_stdout);
25290 }
25291
25292 static void
25293 show_dwarf_cmd (const char *args, int from_tty)
25294 {
25295   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
25296 }
25297
25298 int dwarf_always_disassemble;
25299
25300 static void
25301 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25302                                struct cmd_list_element *c, const char *value)
25303 {
25304   fprintf_filtered (file,
25305                     _("Whether to always disassemble "
25306                       "DWARF expressions is %s.\n"),
25307                     value);
25308 }
25309
25310 static void
25311 show_check_physname (struct ui_file *file, int from_tty,
25312                      struct cmd_list_element *c, const char *value)
25313 {
25314   fprintf_filtered (file,
25315                     _("Whether to check \"physname\" is %s.\n"),
25316                     value);
25317 }
25318
25319 void
25320 _initialize_dwarf2_read (void)
25321 {
25322   dwarf2_objfile_data_key
25323     = register_objfile_data_with_cleanup (nullptr, dwarf2_free_objfile);
25324
25325   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25326 Set DWARF specific variables.\n\
25327 Configure DWARF variables such as the cache size"),
25328                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25329                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25330
25331   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25332 Show DWARF specific variables\n\
25333 Show DWARF variables such as the cache size"),
25334                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25335                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25336
25337   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25338                             &dwarf_max_cache_age, _("\
25339 Set the upper bound on the age of cached DWARF compilation units."), _("\
25340 Show the upper bound on the age of cached DWARF compilation units."), _("\
25341 A higher limit means that cached compilation units will be stored\n\
25342 in memory longer, and more total memory will be used.  Zero disables\n\
25343 caching, which can slow down startup."),
25344                             NULL,
25345                             show_dwarf_max_cache_age,
25346                             &set_dwarf_cmdlist,
25347                             &show_dwarf_cmdlist);
25348
25349   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25350                            &dwarf_always_disassemble, _("\
25351 Set whether `info address' always disassembles DWARF expressions."), _("\
25352 Show whether `info address' always disassembles DWARF expressions."), _("\
25353 When enabled, DWARF expressions are always printed in an assembly-like\n\
25354 syntax.  When disabled, expressions will be printed in a more\n\
25355 conversational style, when possible."),
25356                            NULL,
25357                            show_dwarf_always_disassemble,
25358                            &set_dwarf_cmdlist,
25359                            &show_dwarf_cmdlist);
25360
25361   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25362 Set debugging of the DWARF reader."), _("\
25363 Show debugging of the DWARF reader."), _("\
25364 When enabled (non-zero), debugging messages are printed during DWARF\n\
25365 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25366 information.  A value greater than 1 provides more verbose information."),
25367                             NULL,
25368                             NULL,
25369                             &setdebuglist, &showdebuglist);
25370
25371   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25372 Set debugging of the DWARF DIE reader."), _("\
25373 Show debugging of the DWARF DIE reader."), _("\
25374 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25375 The value is the maximum depth to print."),
25376                              NULL,
25377                              NULL,
25378                              &setdebuglist, &showdebuglist);
25379
25380   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25381 Set debugging of the dwarf line reader."), _("\
25382 Show debugging of the dwarf line reader."), _("\
25383 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25384 A value of 1 (one) provides basic information.\n\
25385 A value greater than 1 provides more verbose information."),
25386                              NULL,
25387                              NULL,
25388                              &setdebuglist, &showdebuglist);
25389
25390   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25391 Set cross-checking of \"physname\" code against demangler."), _("\
25392 Show cross-checking of \"physname\" code against demangler."), _("\
25393 When enabled, GDB's internal \"physname\" code is checked against\n\
25394 the demangler."),
25395                            NULL, show_check_physname,
25396                            &setdebuglist, &showdebuglist);
25397
25398   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25399                            no_class, &use_deprecated_index_sections, _("\
25400 Set whether to use deprecated gdb_index sections."), _("\
25401 Show whether to use deprecated gdb_index sections."), _("\
25402 When enabled, deprecated .gdb_index sections are used anyway.\n\
25403 Normally they are ignored either because of a missing feature or\n\
25404 performance issue.\n\
25405 Warning: This option must be enabled before gdb reads the file."),
25406                            NULL,
25407                            NULL,
25408                            &setlist, &showlist);
25409
25410   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25411                                                         &dwarf2_locexpr_funcs);
25412   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25413                                                         &dwarf2_loclist_funcs);
25414
25415   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25416                                         &dwarf2_block_frame_base_locexpr_funcs);
25417   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25418                                         &dwarf2_block_frame_base_loclist_funcs);
25419
25420 #if GDB_SELF_TEST
25421   selftests::register_test ("dw2_expand_symtabs_matching",
25422                             selftests::dw2_expand_symtabs_matching::run_test);
25423 #endif
25424 }